]> git.sur5r.net Git - openldap/blob - libraries/liblmdb/mdb.c
Merge remote-tracking branch 'origin/mdb.master' into OPENLDAP_REL_ENG_2_5
[openldap] / libraries / liblmdb / mdb.c
1 /** @file mdb.c
2  *      @brief memory-mapped database library
3  *
4  *      A Btree-based database management library modeled loosely on the
5  *      BerkeleyDB API, but much simplified.
6  */
7 /*
8  * Copyright 2011-2013 Howard Chu, Symas Corp.
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted only as authorized by the OpenLDAP
13  * Public License.
14  *
15  * A copy of this license is available in the file LICENSE in the
16  * top-level directory of the distribution or, alternatively, at
17  * <http://www.OpenLDAP.org/license.html>.
18  *
19  * This code is derived from btree.c written by Martin Hedenfalk.
20  *
21  * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
22  *
23  * Permission to use, copy, modify, and distribute this software for any
24  * purpose with or without fee is hereby granted, provided that the above
25  * copyright notice and this permission notice appear in all copies.
26  *
27  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
34  */
35 #ifndef _GNU_SOURCE
36 #define _GNU_SOURCE 1
37 #endif
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #ifdef _WIN32
41 #include <windows.h>
42 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
43  *  as int64 which is wrong. MSVC doesn't define it at all, so just
44  *  don't use it.
45  */
46 #define MDB_PID_T       int
47 #ifdef __GNUC__
48 # include <sys/param.h>
49 #else
50 # define LITTLE_ENDIAN  1234
51 # define BIG_ENDIAN     4321
52 # define BYTE_ORDER     LITTLE_ENDIAN
53 # ifndef SSIZE_MAX
54 #  define SSIZE_MAX     INT_MAX
55 # endif
56 #endif
57 #else
58 #define MDB_PID_T       pid_t
59 #include <sys/param.h>
60 #include <sys/uio.h>
61 #include <sys/mman.h>
62 #ifdef HAVE_SYS_FILE_H
63 #include <sys/file.h>
64 #endif
65 #include <fcntl.h>
66 #endif
67
68 #include <assert.h>
69 #include <errno.h>
70 #include <limits.h>
71 #include <stddef.h>
72 #include <inttypes.h>
73 #include <stdio.h>
74 #include <stdlib.h>
75 #include <string.h>
76 #include <time.h>
77 #include <unistd.h>
78
79 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
80 #include <netinet/in.h>
81 #include <resolv.h>     /* defines BYTE_ORDER on HPUX and Solaris */
82 #endif
83
84 #if defined(__APPLE__) || defined (BSD)
85 # define MDB_USE_POSIX_SEM      1
86 # define MDB_FDATASYNC          fsync
87 #elif defined(ANDROID)
88 # define MDB_FDATASYNC          fsync
89 #endif
90
91 #ifndef _WIN32
92 #include <pthread.h>
93 #ifdef MDB_USE_POSIX_SEM
94 # define MDB_USE_HASH           1
95 #include <semaphore.h>
96 #endif
97 #endif
98
99 #ifdef USE_VALGRIND
100 #include <valgrind/memcheck.h>
101 #define VGMEMP_CREATE(h,r,z)    VALGRIND_CREATE_MEMPOOL(h,r,z)
102 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
103 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
104 #define VGMEMP_DESTROY(h)       VALGRIND_DESTROY_MEMPOOL(h)
105 #define VGMEMP_DEFINED(a,s)     VALGRIND_MAKE_MEM_DEFINED(a,s)
106 #else
107 #define VGMEMP_CREATE(h,r,z)
108 #define VGMEMP_ALLOC(h,a,s)
109 #define VGMEMP_FREE(h,a)
110 #define VGMEMP_DESTROY(h)
111 #define VGMEMP_DEFINED(a,s)
112 #endif
113
114 #ifndef BYTE_ORDER
115 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
116 /* Solaris just defines one or the other */
117 #  define LITTLE_ENDIAN 1234
118 #  define BIG_ENDIAN    4321
119 #  ifdef _LITTLE_ENDIAN
120 #   define BYTE_ORDER  LITTLE_ENDIAN
121 #  else
122 #   define BYTE_ORDER  BIG_ENDIAN
123 #  endif
124 # else
125 #  define BYTE_ORDER   __BYTE_ORDER
126 # endif
127 #endif
128
129 #ifndef LITTLE_ENDIAN
130 #define LITTLE_ENDIAN   __LITTLE_ENDIAN
131 #endif
132 #ifndef BIG_ENDIAN
133 #define BIG_ENDIAN      __BIG_ENDIAN
134 #endif
135
136 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
137 #define MISALIGNED_OK   1
138 #endif
139
140 #include "lmdb.h"
141 #include "midl.h"
142
143 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
144 # error "Unknown or unsupported endianness (BYTE_ORDER)"
145 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
146 # error "Two's complement, reasonably sized integer types, please"
147 #endif
148
149 /** @defgroup internal  MDB Internals
150  *      @{
151  */
152 /** @defgroup compat    Windows Compatibility Macros
153  *      A bunch of macros to minimize the amount of platform-specific ifdefs
154  *      needed throughout the rest of the code. When the features this library
155  *      needs are similar enough to POSIX to be hidden in a one-or-two line
156  *      replacement, this macro approach is used.
157  *      @{
158  */
159 #ifdef _WIN32
160 #define MDB_USE_HASH    1
161 #define MDB_PIDLOCK     0
162 #define pthread_t       DWORD
163 #define pthread_mutex_t HANDLE
164 #define pthread_key_t   DWORD
165 #define pthread_self()  GetCurrentThreadId()
166 #define pthread_key_create(x,y) \
167         ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
168 #define pthread_key_delete(x)   TlsFree(x)
169 #define pthread_getspecific(x)  TlsGetValue(x)
170 #define pthread_setspecific(x,y)        (TlsSetValue(x,y) ? 0 : ErrCode())
171 #define pthread_mutex_unlock(x) ReleaseMutex(x)
172 #define pthread_mutex_lock(x)   WaitForSingleObject(x, INFINITE)
173 #define LOCK_MUTEX_R(env)       pthread_mutex_lock((env)->me_rmutex)
174 #define UNLOCK_MUTEX_R(env)     pthread_mutex_unlock((env)->me_rmutex)
175 #define LOCK_MUTEX_W(env)       pthread_mutex_lock((env)->me_wmutex)
176 #define UNLOCK_MUTEX_W(env)     pthread_mutex_unlock((env)->me_wmutex)
177 #define getpid()        GetCurrentProcessId()
178 #define MDB_FDATASYNC(fd)       (!FlushFileBuffers(fd))
179 #define MDB_MSYNC(addr,len,flags)       (!FlushViewOfFile(addr,len))
180 #define ErrCode()       GetLastError()
181 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
182 #define close(fd)       (CloseHandle(fd) ? 0 : -1)
183 #define munmap(ptr,len) UnmapViewOfFile(ptr)
184 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
185 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
186 #else
187 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
188 #endif
189 #define Z       "I"
190 #else
191
192 #define Z       "z"                     /**< printf format modifier for size_t */
193
194         /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
195 #define MDB_PIDLOCK                     1
196
197 #ifdef MDB_USE_POSIX_SEM
198
199 #define LOCK_MUTEX_R(env)       mdb_sem_wait((env)->me_rmutex)
200 #define UNLOCK_MUTEX_R(env)     sem_post((env)->me_rmutex)
201 #define LOCK_MUTEX_W(env)       mdb_sem_wait((env)->me_wmutex)
202 #define UNLOCK_MUTEX_W(env)     sem_post((env)->me_wmutex)
203
204 static int
205 mdb_sem_wait(sem_t *sem)
206 {
207    int rc;
208    while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
209    return rc;
210 }
211
212 #else
213         /** Lock the reader mutex.
214          */
215 #define LOCK_MUTEX_R(env)       pthread_mutex_lock(&(env)->me_txns->mti_mutex)
216         /** Unlock the reader mutex.
217          */
218 #define UNLOCK_MUTEX_R(env)     pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
219
220         /** Lock the writer mutex.
221          *      Only a single write transaction is allowed at a time. Other writers
222          *      will block waiting for this mutex.
223          */
224 #define LOCK_MUTEX_W(env)       pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
225         /** Unlock the writer mutex.
226          */
227 #define UNLOCK_MUTEX_W(env)     pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
228 #endif  /* MDB_USE_POSIX_SEM */
229
230         /** Get the error code for the last failed system function.
231          */
232 #define ErrCode()       errno
233
234         /** An abstraction for a file handle.
235          *      On POSIX systems file handles are small integers. On Windows
236          *      they're opaque pointers.
237          */
238 #define HANDLE  int
239
240         /**     A value for an invalid file handle.
241          *      Mainly used to initialize file variables and signify that they are
242          *      unused.
243          */
244 #define INVALID_HANDLE_VALUE    (-1)
245
246         /** Get the size of a memory page for the system.
247          *      This is the basic size that the platform's memory manager uses, and is
248          *      fundamental to the use of memory-mapped files.
249          */
250 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
251 #endif
252
253 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
254 #define MNAME_LEN       32
255 #else
256 #define MNAME_LEN       (sizeof(pthread_mutex_t))
257 #endif
258
259 /** @} */
260
261 #ifndef _WIN32
262 /**     A flag for opening a file and requesting synchronous data writes.
263  *      This is only used when writing a meta page. It's not strictly needed;
264  *      we could just do a normal write and then immediately perform a flush.
265  *      But if this flag is available it saves us an extra system call.
266  *
267  *      @note If O_DSYNC is undefined but exists in /usr/include,
268  * preferably set some compiler flag to get the definition.
269  * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
270  */
271 #ifndef MDB_DSYNC
272 # define MDB_DSYNC      O_DSYNC
273 #endif
274 #endif
275
276 /** Function for flushing the data of a file. Define this to fsync
277  *      if fdatasync() is not supported.
278  */
279 #ifndef MDB_FDATASYNC
280 # define MDB_FDATASYNC  fdatasync
281 #endif
282
283 #ifndef MDB_MSYNC
284 # define MDB_MSYNC(addr,len,flags)      msync(addr,len,flags)
285 #endif
286
287 #ifndef MS_SYNC
288 #define MS_SYNC 1
289 #endif
290
291 #ifndef MS_ASYNC
292 #define MS_ASYNC        0
293 #endif
294
295         /** A page number in the database.
296          *      Note that 64 bit page numbers are overkill, since pages themselves
297          *      already represent 12-13 bits of addressable memory, and the OS will
298          *      always limit applications to a maximum of 63 bits of address space.
299          *
300          *      @note In the #MDB_node structure, we only store 48 bits of this value,
301          *      which thus limits us to only 60 bits of addressable data.
302          */
303 typedef MDB_ID  pgno_t;
304
305         /** A transaction ID.
306          *      See struct MDB_txn.mt_txnid for details.
307          */
308 typedef MDB_ID  txnid_t;
309
310 /** @defgroup debug     Debug Macros
311  *      @{
312  */
313 #ifndef MDB_DEBUG
314         /**     Enable debug output.  Needs variable argument macros (a C99 feature).
315          *      Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
316          *      read from and written to the database (used for free space management).
317          */
318 #define MDB_DEBUG 0
319 #endif
320
321 #if MDB_DEBUG
322 static int mdb_debug;
323 static txnid_t mdb_debug_start;
324
325         /**     Print a debug message with printf formatting.
326          *      Requires double parenthesis around 2 or more args.
327          */
328 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
329 # define DPRINTF0(fmt, ...) \
330         fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)
331 #else
332 # define DPRINTF(args)  ((void) 0)
333 #endif
334         /**     Print a debug string.
335          *      The string is printed literally, with no format processing.
336          */
337 #define DPUTS(arg)      DPRINTF(("%s", arg))
338         /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
339 #define DDBI(mc) \
340         (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
341 /** @} */
342
343         /**     @brief The maximum size of a database page.
344          *
345          *      This is 32k, since it must fit in #MDB_page.#mp_upper.
346          *
347          *      LMDB will use database pages < OS pages if needed.
348          *      That causes more I/O in write transactions: The OS must
349          *      know (read) the whole page before writing a partial page.
350          *
351          *      Note that we don't currently support Huge pages. On Linux,
352          *      regular data files cannot use Huge pages, and in general
353          *      Huge pages aren't actually pageable. We rely on the OS
354          *      demand-pager to read our data and page it out when memory
355          *      pressure from other processes is high. So until OSs have
356          *      actual paging support for Huge pages, they're not viable.
357          */
358 #define MAX_PAGESIZE     0x8000
359
360         /** The minimum number of keys required in a database page.
361          *      Setting this to a larger value will place a smaller bound on the
362          *      maximum size of a data item. Data items larger than this size will
363          *      be pushed into overflow pages instead of being stored directly in
364          *      the B-tree node. This value used to default to 4. With a page size
365          *      of 4096 bytes that meant that any item larger than 1024 bytes would
366          *      go into an overflow page. That also meant that on average 2-3KB of
367          *      each overflow page was wasted space. The value cannot be lower than
368          *      2 because then there would no longer be a tree structure. With this
369          *      value, items larger than 2KB will go into overflow pages, and on
370          *      average only 1KB will be wasted.
371          */
372 #define MDB_MINKEYS      2
373
374         /**     A stamp that identifies a file as an MDB file.
375          *      There's nothing special about this value other than that it is easily
376          *      recognizable, and it will reflect any byte order mismatches.
377          */
378 #define MDB_MAGIC        0xBEEFC0DE
379
380         /**     The version number for a database's datafile format. */
381 #define MDB_DATA_VERSION         1
382         /**     The version number for a database's lockfile format. */
383 #define MDB_LOCK_VERSION         1
384
385         /**     @brief The maximum size of a key in the database.
386          *
387          *      The library rejects bigger keys, and cannot deal with records
388          *      with bigger keys stored by a library with bigger max keysize.
389          *
390          *      We require that keys all fit onto a regular page. This limit
391          *      could be raised a bit further if needed; to something just
392          *      under (page size / #MDB_MINKEYS / 3).
393          *
394          *      Note that data items in an #MDB_DUPSORT database are actually keys
395          *      of a subDB, so they're also limited to this size.
396          */
397 #ifndef MDB_MAXKEYSIZE
398 #define MDB_MAXKEYSIZE   511
399 #endif
400
401         /**     @brief The maximum size of a data item.
402          *
403          *      We only store a 32 bit value for node sizes.
404          */
405 #define MAXDATASIZE     0xffffffffUL
406
407 #if MDB_DEBUG
408         /**     A key buffer.
409          *      @ingroup debug
410          *      This is used for printing a hex dump of a key's contents.
411          */
412 #define DKBUF   char kbuf[(MDB_MAXKEYSIZE*2+1)]
413         /**     Display a key in hex.
414          *      @ingroup debug
415          *      Invoke a function to display a key in hex.
416          */
417 #define DKEY(x) mdb_dkey(x, kbuf)
418 #else
419 #define DKBUF
420 #define DKEY(x) 0
421 #endif
422
423         /** An invalid page number.
424          *      Mainly used to denote an empty tree.
425          */
426 #define P_INVALID        (~(pgno_t)0)
427
428         /** Test if the flags \b f are set in a flag word \b w. */
429 #define F_ISSET(w, f)    (((w) & (f)) == (f))
430
431         /**     Used for offsets within a single page.
432          *      Since memory pages are typically 4 or 8KB in size, 12-13 bits,
433          *      this is plenty.
434          */
435 typedef uint16_t         indx_t;
436
437         /**     Default size of memory map.
438          *      This is certainly too small for any actual applications. Apps should always set
439          *      the size explicitly using #mdb_env_set_mapsize().
440          */
441 #define DEFAULT_MAPSIZE 1048576
442
443 /**     @defgroup readers       Reader Lock Table
444  *      Readers don't acquire any locks for their data access. Instead, they
445  *      simply record their transaction ID in the reader table. The reader
446  *      mutex is needed just to find an empty slot in the reader table. The
447  *      slot's address is saved in thread-specific data so that subsequent read
448  *      transactions started by the same thread need no further locking to proceed.
449  *
450  *      If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
451  *
452  *      No reader table is used if the database is on a read-only filesystem, or
453  *      if #MDB_NOLOCK is set.
454  *
455  *      Since the database uses multi-version concurrency control, readers don't
456  *      actually need any locking. This table is used to keep track of which
457  *      readers are using data from which old transactions, so that we'll know
458  *      when a particular old transaction is no longer in use. Old transactions
459  *      that have discarded any data pages can then have those pages reclaimed
460  *      for use by a later write transaction.
461  *
462  *      The lock table is constructed such that reader slots are aligned with the
463  *      processor's cache line size. Any slot is only ever used by one thread.
464  *      This alignment guarantees that there will be no contention or cache
465  *      thrashing as threads update their own slot info, and also eliminates
466  *      any need for locking when accessing a slot.
467  *
468  *      A writer thread will scan every slot in the table to determine the oldest
469  *      outstanding reader transaction. Any freed pages older than this will be
470  *      reclaimed by the writer. The writer doesn't use any locks when scanning
471  *      this table. This means that there's no guarantee that the writer will
472  *      see the most up-to-date reader info, but that's not required for correct
473  *      operation - all we need is to know the upper bound on the oldest reader,
474  *      we don't care at all about the newest reader. So the only consequence of
475  *      reading stale information here is that old pages might hang around a
476  *      while longer before being reclaimed. That's actually good anyway, because
477  *      the longer we delay reclaiming old pages, the more likely it is that a
478  *      string of contiguous pages can be found after coalescing old pages from
479  *      many old transactions together.
480  *      @{
481  */
482         /**     Number of slots in the reader table.
483          *      This value was chosen somewhat arbitrarily. 126 readers plus a
484          *      couple mutexes fit exactly into 8KB on my development machine.
485          *      Applications should set the table size using #mdb_env_set_maxreaders().
486          */
487 #define DEFAULT_READERS 126
488
489         /**     The size of a CPU cache line in bytes. We want our lock structures
490          *      aligned to this size to avoid false cache line sharing in the
491          *      lock table.
492          *      This value works for most CPUs. For Itanium this should be 128.
493          */
494 #ifndef CACHELINE
495 #define CACHELINE       64
496 #endif
497
498         /**     The information we store in a single slot of the reader table.
499          *      In addition to a transaction ID, we also record the process and
500          *      thread ID that owns a slot, so that we can detect stale information,
501          *      e.g. threads or processes that went away without cleaning up.
502          *      @note We currently don't check for stale records. We simply re-init
503          *      the table when we know that we're the only process opening the
504          *      lock file.
505          */
506 typedef struct MDB_rxbody {
507         /**     Current Transaction ID when this transaction began, or (txnid_t)-1.
508          *      Multiple readers that start at the same time will probably have the
509          *      same ID here. Again, it's not important to exclude them from
510          *      anything; all we need to know is which version of the DB they
511          *      started from so we can avoid overwriting any data used in that
512          *      particular version.
513          */
514         txnid_t         mrb_txnid;
515         /** The process ID of the process owning this reader txn. */
516         MDB_PID_T       mrb_pid;
517         /** The thread ID of the thread owning this txn. */
518         pthread_t       mrb_tid;
519 } MDB_rxbody;
520
521         /** The actual reader record, with cacheline padding. */
522 typedef struct MDB_reader {
523         union {
524                 MDB_rxbody mrx;
525                 /** shorthand for mrb_txnid */
526 #define mr_txnid        mru.mrx.mrb_txnid
527 #define mr_pid  mru.mrx.mrb_pid
528 #define mr_tid  mru.mrx.mrb_tid
529                 /** cache line alignment */
530                 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
531         } mru;
532 } MDB_reader;
533
534         /** The header for the reader table.
535          *      The table resides in a memory-mapped file. (This is a different file
536          *      than is used for the main database.)
537          *
538          *      For POSIX the actual mutexes reside in the shared memory of this
539          *      mapped file. On Windows, mutexes are named objects allocated by the
540          *      kernel; we store the mutex names in this mapped file so that other
541          *      processes can grab them. This same approach is also used on
542          *      MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
543          *      process-shared POSIX mutexes. For these cases where a named object
544          *      is used, the object name is derived from a 64 bit FNV hash of the
545          *      environment pathname. As such, naming collisions are extremely
546          *      unlikely. If a collision occurs, the results are unpredictable.
547          */
548 typedef struct MDB_txbody {
549                 /** Stamp identifying this as an MDB file. It must be set
550                  *      to #MDB_MAGIC. */
551         uint32_t        mtb_magic;
552                 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
553         uint32_t        mtb_format;
554 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
555         char    mtb_rmname[MNAME_LEN];
556 #else
557                 /** Mutex protecting access to this table.
558                  *      This is the reader lock that #LOCK_MUTEX_R acquires.
559                  */
560         pthread_mutex_t mtb_mutex;
561 #endif
562                 /**     The ID of the last transaction committed to the database.
563                  *      This is recorded here only for convenience; the value can always
564                  *      be determined by reading the main database meta pages.
565                  */
566         txnid_t         mtb_txnid;
567                 /** The number of slots that have been used in the reader table.
568                  *      This always records the maximum count, it is not decremented
569                  *      when readers release their slots.
570                  */
571         unsigned        mtb_numreaders;
572 } MDB_txbody;
573
574         /** The actual reader table definition. */
575 typedef struct MDB_txninfo {
576         union {
577                 MDB_txbody mtb;
578 #define mti_magic       mt1.mtb.mtb_magic
579 #define mti_format      mt1.mtb.mtb_format
580 #define mti_mutex       mt1.mtb.mtb_mutex
581 #define mti_rmname      mt1.mtb.mtb_rmname
582 #define mti_txnid       mt1.mtb.mtb_txnid
583 #define mti_numreaders  mt1.mtb.mtb_numreaders
584                 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
585         } mt1;
586         union {
587 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
588                 char mt2_wmname[MNAME_LEN];
589 #define mti_wmname      mt2.mt2_wmname
590 #else
591                 pthread_mutex_t mt2_wmutex;
592 #define mti_wmutex      mt2.mt2_wmutex
593 #endif
594                 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
595         } mt2;
596         MDB_reader      mti_readers[1];
597 } MDB_txninfo;
598
599         /** Lockfile format signature: version, features and field layout */
600 #define MDB_LOCK_FORMAT \
601         ((uint32_t) \
602          ((MDB_LOCK_VERSION) \
603           /* Flags which describe functionality */ \
604           + (((MDB_PIDLOCK) != 0) << 16)))
605 /** @} */
606
607 /** Common header for all page types.
608  * Overflow records occupy a number of contiguous pages with no
609  * headers on any page after the first.
610  */
611 typedef struct MDB_page {
612 #define mp_pgno mp_p.p_pgno
613 #define mp_next mp_p.p_next
614         union {
615                 pgno_t          p_pgno; /**< page number */
616                 void *          p_next; /**< for in-memory list of freed structs */
617         } mp_p;
618         uint16_t        mp_pad;
619 /**     @defgroup mdb_page      Page Flags
620  *      @ingroup internal
621  *      Flags for the page headers.
622  *      @{
623  */
624 #define P_BRANCH         0x01           /**< branch page */
625 #define P_LEAF           0x02           /**< leaf page */
626 #define P_OVERFLOW       0x04           /**< overflow page */
627 #define P_META           0x08           /**< meta page */
628 #define P_DIRTY          0x10           /**< dirty page, also set for #P_SUBP pages */
629 #define P_LEAF2          0x20           /**< for #MDB_DUPFIXED records */
630 #define P_SUBP           0x40           /**< for #MDB_DUPSORT sub-pages */
631 #define P_KEEP           0x8000         /**< leave this page alone during spill */
632 /** @} */
633         uint16_t        mp_flags;               /**< @ref mdb_page */
634 #define mp_lower        mp_pb.pb.pb_lower
635 #define mp_upper        mp_pb.pb.pb_upper
636 #define mp_pages        mp_pb.pb_pages
637         union {
638                 struct {
639                         indx_t          pb_lower;               /**< lower bound of free space */
640                         indx_t          pb_upper;               /**< upper bound of free space */
641                 } pb;
642                 uint32_t        pb_pages;       /**< number of overflow pages */
643         } mp_pb;
644         indx_t          mp_ptrs[1];             /**< dynamic size */
645 } MDB_page;
646
647         /** Size of the page header, excluding dynamic data at the end */
648 #define PAGEHDRSZ        ((unsigned) offsetof(MDB_page, mp_ptrs))
649
650         /** Address of first usable data byte in a page, after the header */
651 #define METADATA(p)      ((void *)((char *)(p) + PAGEHDRSZ))
652
653         /** Number of nodes on a page */
654 #define NUMKEYS(p)       (((p)->mp_lower - PAGEHDRSZ) >> 1)
655
656         /** The amount of space remaining in the page */
657 #define SIZELEFT(p)      (indx_t)((p)->mp_upper - (p)->mp_lower)
658
659         /** The percentage of space used in the page, in tenths of a percent. */
660 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
661                                 ((env)->me_psize - PAGEHDRSZ))
662         /** The minimum page fill factor, in tenths of a percent.
663          *      Pages emptier than this are candidates for merging.
664          */
665 #define FILL_THRESHOLD   250
666
667         /** Test if a page is a leaf page */
668 #define IS_LEAF(p)       F_ISSET((p)->mp_flags, P_LEAF)
669         /** Test if a page is a LEAF2 page */
670 #define IS_LEAF2(p)      F_ISSET((p)->mp_flags, P_LEAF2)
671         /** Test if a page is a branch page */
672 #define IS_BRANCH(p)     F_ISSET((p)->mp_flags, P_BRANCH)
673         /** Test if a page is an overflow page */
674 #define IS_OVERFLOW(p)   F_ISSET((p)->mp_flags, P_OVERFLOW)
675         /** Test if a page is a sub page */
676 #define IS_SUBP(p)       F_ISSET((p)->mp_flags, P_SUBP)
677
678         /** The number of overflow pages needed to store the given size. */
679 #define OVPAGES(size, psize)    ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
680
681         /** Header for a single key/data pair within a page.
682          * We guarantee 2-byte alignment for nodes.
683          */
684 typedef struct MDB_node {
685         /** lo and hi are used for data size on leaf nodes and for
686          * child pgno on branch nodes. On 64 bit platforms, flags
687          * is also used for pgno. (Branch nodes have no flags).
688          * They are in host byte order in case that lets some
689          * accesses be optimized into a 32-bit word access.
690          */
691 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
692 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
693         unsigned short  mn_offset[2];   /**< storage for #mn_lo and #mn_hi */
694 /** @defgroup mdb_node Node Flags
695  *      @ingroup internal
696  *      Flags for node headers.
697  *      @{
698  */
699 #define F_BIGDATA        0x01                   /**< data put on overflow page */
700 #define F_SUBDATA        0x02                   /**< data is a sub-database */
701 #define F_DUPDATA        0x04                   /**< data has duplicates */
702
703 /** valid flags for #mdb_node_add() */
704 #define NODE_ADD_FLAGS  (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
705
706 /** @} */
707         unsigned short  mn_flags;               /**< @ref mdb_node */
708         unsigned short  mn_ksize;               /**< key size */
709         char            mn_data[1];                     /**< key and data are appended here */
710 } MDB_node;
711
712         /** Size of the node header, excluding dynamic data at the end */
713 #define NODESIZE         offsetof(MDB_node, mn_data)
714
715         /** Bit position of top word in page number, for shifting mn_flags */
716 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
717
718         /** Size of a node in a branch page with a given key.
719          *      This is just the node header plus the key, there is no data.
720          */
721 #define INDXSIZE(k)      (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
722
723         /** Size of a node in a leaf page with a given key and data.
724          *      This is node header plus key plus data size.
725          */
726 #define LEAFSIZE(k, d)   (NODESIZE + (k)->mv_size + (d)->mv_size)
727
728         /** Address of node \b i in page \b p */
729 #define NODEPTR(p, i)    ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
730
731         /** Address of the key for the node */
732 #define NODEKEY(node)    (void *)((node)->mn_data)
733
734         /** Address of the data for a node */
735 #define NODEDATA(node)   (void *)((char *)(node)->mn_data + (node)->mn_ksize)
736
737         /** Get the page number pointed to by a branch node */
738 #define NODEPGNO(node) \
739         ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
740          (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
741         /** Set the page number in a branch node */
742 #define SETPGNO(node,pgno)      do { \
743         (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
744         if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
745
746         /** Get the size of the data in a leaf node */
747 #define NODEDSZ(node)    ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
748         /** Set the size of the data for a leaf node */
749 #define SETDSZ(node,size)       do { \
750         (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
751         /** The size of a key in a node */
752 #define NODEKSZ(node)    ((node)->mn_ksize)
753
754         /** Copy a page number from src to dst */
755 #ifdef MISALIGNED_OK
756 #define COPY_PGNO(dst,src)      dst = src
757 #else
758 #if SIZE_MAX > 4294967295UL
759 #define COPY_PGNO(dst,src)      do { \
760         unsigned short *s, *d;  \
761         s = (unsigned short *)&(src);   \
762         d = (unsigned short *)&(dst);   \
763         *d++ = *s++;    \
764         *d++ = *s++;    \
765         *d++ = *s++;    \
766         *d = *s;        \
767 } while (0)
768 #else
769 #define COPY_PGNO(dst,src)      do { \
770         unsigned short *s, *d;  \
771         s = (unsigned short *)&(src);   \
772         d = (unsigned short *)&(dst);   \
773         *d++ = *s++;    \
774         *d = *s;        \
775 } while (0)
776 #endif
777 #endif
778         /** The address of a key in a LEAF2 page.
779          *      LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
780          *      There are no node headers, keys are stored contiguously.
781          */
782 #define LEAF2KEY(p, i, ks)      ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
783
784         /** Set the \b node's key into \b keyptr, if requested. */
785 #define MDB_GET_KEY(node, keyptr)       { if ((keyptr) != NULL) { \
786         (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
787
788         /** Set the \b node's key into \b key. */
789 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
790
791         /** Information about a single database in the environment. */
792 typedef struct MDB_db {
793         uint32_t        md_pad;         /**< also ksize for LEAF2 pages */
794         uint16_t        md_flags;       /**< @ref mdb_dbi_open */
795         uint16_t        md_depth;       /**< depth of this tree */
796         pgno_t          md_branch_pages;        /**< number of internal pages */
797         pgno_t          md_leaf_pages;          /**< number of leaf pages */
798         pgno_t          md_overflow_pages;      /**< number of overflow pages */
799         size_t          md_entries;             /**< number of data items */
800         pgno_t          md_root;                /**< the root page of this tree */
801 } MDB_db;
802
803         /** mdb_dbi_open flags */
804 #define MDB_VALID       0x8000          /**< DB handle is valid, for me_dbflags */
805 #define PERSISTENT_FLAGS        (0xffff & ~(MDB_VALID))
806 #define VALID_FLAGS     (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
807         MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
808
809         /** Handle for the DB used to track free pages. */
810 #define FREE_DBI        0
811         /** Handle for the default DB. */
812 #define MAIN_DBI        1
813
814         /** Meta page content.
815          *      A meta page is the start point for accessing a database snapshot.
816          *      Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
817          */
818 typedef struct MDB_meta {
819                 /** Stamp identifying this as an MDB file. It must be set
820                  *      to #MDB_MAGIC. */
821         uint32_t        mm_magic;
822                 /** Version number of this lock file. Must be set to #MDB_DATA_VERSION. */
823         uint32_t        mm_version;
824         void            *mm_address;            /**< address for fixed mapping */
825         size_t          mm_mapsize;                     /**< size of mmap region */
826         MDB_db          mm_dbs[2];                      /**< first is free space, 2nd is main db */
827         /** The size of pages used in this DB */
828 #define mm_psize        mm_dbs[0].md_pad
829         /** Any persistent environment flags. @ref mdb_env */
830 #define mm_flags        mm_dbs[0].md_flags
831         pgno_t          mm_last_pg;                     /**< last used page in file */
832         txnid_t         mm_txnid;                       /**< txnid that committed this page */
833 } MDB_meta;
834
835         /** Buffer for a stack-allocated meta page.
836          *      The members define size and alignment, and silence type
837          *      aliasing warnings.  They are not used directly; that could
838          *      mean incorrectly using several union members in parallel.
839          */
840 typedef union MDB_metabuf {
841         MDB_page        mb_page;
842         struct {
843                 char            mm_pad[PAGEHDRSZ];
844                 MDB_meta        mm_meta;
845         } mb_metabuf;
846 } MDB_metabuf;
847
848         /** Auxiliary DB info.
849          *      The information here is mostly static/read-only. There is
850          *      only a single copy of this record in the environment.
851          */
852 typedef struct MDB_dbx {
853         MDB_val         md_name;                /**< name of the database */
854         MDB_cmp_func    *md_cmp;        /**< function for comparing keys */
855         MDB_cmp_func    *md_dcmp;       /**< function for comparing data items */
856         MDB_rel_func    *md_rel;        /**< user relocate function */
857         void            *md_relctx;             /**< user-provided context for md_rel */
858 } MDB_dbx;
859
860         /** A database transaction.
861          *      Every operation requires a transaction handle.
862          */
863 struct MDB_txn {
864         MDB_txn         *mt_parent;             /**< parent of a nested txn */
865         MDB_txn         *mt_child;              /**< nested txn under this txn */
866         pgno_t          mt_next_pgno;   /**< next unallocated page */
867         /** The ID of this transaction. IDs are integers incrementing from 1.
868          *      Only committed write transactions increment the ID. If a transaction
869          *      aborts, the ID may be re-used by the next writer.
870          */
871         txnid_t         mt_txnid;
872         MDB_env         *mt_env;                /**< the DB environment */
873         /** The list of pages that became unused during this transaction.
874          */
875         MDB_IDL         mt_free_pgs;
876         /** The sorted list of dirty pages we temporarily wrote to disk
877          *      because the dirty list was full. page numbers in here are
878          *      shifted left by 1, deleted slots have the LSB set.
879          */
880         MDB_IDL         mt_spill_pgs;
881         union {
882                 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
883                 MDB_ID2L        dirty_list;
884                 /** For read txns: This thread/txn's reader table slot, or NULL. */
885                 MDB_reader      *reader;
886         } mt_u;
887         /** Array of records for each DB known in the environment. */
888         MDB_dbx         *mt_dbxs;
889         /** Array of MDB_db records for each known DB */
890         MDB_db          *mt_dbs;
891 /** @defgroup mt_dbflag Transaction DB Flags
892  *      @ingroup internal
893  * @{
894  */
895 #define DB_DIRTY        0x01            /**< DB was modified or is DUPSORT data */
896 #define DB_STALE        0x02            /**< Named-DB record is older than txnID */
897 #define DB_NEW          0x04            /**< Named-DB handle opened in this txn */
898 #define DB_VALID        0x08            /**< DB handle is valid, see also #MDB_VALID */
899 /** @} */
900         /** In write txns, array of cursors for each DB */
901         MDB_cursor      **mt_cursors;
902         /** Array of flags for each DB */
903         unsigned char   *mt_dbflags;
904         /**     Number of DB records in use. This number only ever increments;
905          *      we don't decrement it when individual DB handles are closed.
906          */
907         MDB_dbi         mt_numdbs;
908
909 /** @defgroup mdb_txn   Transaction Flags
910  *      @ingroup internal
911  *      @{
912  */
913 #define MDB_TXN_RDONLY          0x01            /**< read-only transaction */
914 #define MDB_TXN_ERROR           0x02            /**< an error has occurred */
915 #define MDB_TXN_DIRTY           0x04            /**< must write, even if dirty list is empty */
916 #define MDB_TXN_SPILLS          0x08            /**< txn or a parent has spilled pages */
917 /** @} */
918         unsigned int    mt_flags;               /**< @ref mdb_txn */
919         /** dirty_list room: Array size - #dirty pages visible to this txn.
920          *      Includes ancestor txns' dirty pages not hidden by other txns'
921          *      dirty/spilled pages. Thus commit(nested txn) has room to merge
922          *      dirty_list into mt_parent after freeing hidden mt_parent pages.
923          */
924         unsigned int    mt_dirty_room;
925 };
926
927 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
928  * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
929  * raise this on a 64 bit machine.
930  */
931 #define CURSOR_STACK             32
932
933 struct MDB_xcursor;
934
935         /** Cursors are used for all DB operations.
936          *      A cursor holds a path of (page pointer, key index) from the DB
937          *      root to a position in the DB, plus other state. #MDB_DUPSORT
938          *      cursors include an xcursor to the current data item. Write txns
939          *      track their cursors and keep them up to date when data moves.
940          *      Exception: An xcursor's pointer to a #P_SUBP page can be stale.
941          *      (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
942          */
943 struct MDB_cursor {
944         /** Next cursor on this DB in this txn */
945         MDB_cursor      *mc_next;
946         /** Backup of the original cursor if this cursor is a shadow */
947         MDB_cursor      *mc_backup;
948         /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
949         struct MDB_xcursor      *mc_xcursor;
950         /** The transaction that owns this cursor */
951         MDB_txn         *mc_txn;
952         /** The database handle this cursor operates on */
953         MDB_dbi         mc_dbi;
954         /** The database record for this cursor */
955         MDB_db          *mc_db;
956         /** The database auxiliary record for this cursor */
957         MDB_dbx         *mc_dbx;
958         /** The @ref mt_dbflag for this database */
959         unsigned char   *mc_dbflag;
960         unsigned short  mc_snum;        /**< number of pushed pages */
961         unsigned short  mc_top;         /**< index of top page, normally mc_snum-1 */
962 /** @defgroup mdb_cursor        Cursor Flags
963  *      @ingroup internal
964  *      Cursor state flags.
965  *      @{
966  */
967 #define C_INITIALIZED   0x01    /**< cursor has been initialized and is valid */
968 #define C_EOF   0x02                    /**< No more data */
969 #define C_SUB   0x04                    /**< Cursor is a sub-cursor */
970 #define C_DEL   0x08                    /**< last op was a cursor_del */
971 #define C_SPLITTING     0x20            /**< Cursor is in page_split */
972 #define C_UNTRACK       0x40            /**< Un-track cursor when closing */
973 /** @} */
974         unsigned int    mc_flags;       /**< @ref mdb_cursor */
975         MDB_page        *mc_pg[CURSOR_STACK];   /**< stack of pushed pages */
976         indx_t          mc_ki[CURSOR_STACK];    /**< stack of page indices */
977 };
978
979         /** Context for sorted-dup records.
980          *      We could have gone to a fully recursive design, with arbitrarily
981          *      deep nesting of sub-databases. But for now we only handle these
982          *      levels - main DB, optional sub-DB, sorted-duplicate DB.
983          */
984 typedef struct MDB_xcursor {
985         /** A sub-cursor for traversing the Dup DB */
986         MDB_cursor mx_cursor;
987         /** The database record for this Dup DB */
988         MDB_db  mx_db;
989         /**     The auxiliary DB record for this Dup DB */
990         MDB_dbx mx_dbx;
991         /** The @ref mt_dbflag for this Dup DB */
992         unsigned char mx_dbflag;
993 } MDB_xcursor;
994
995         /** State of FreeDB old pages, stored in the MDB_env */
996 typedef struct MDB_pgstate {
997         pgno_t          *mf_pghead;     /**< Reclaimed freeDB pages, or NULL before use */
998         txnid_t         mf_pglast;      /**< ID of last used record, or 0 if !mf_pghead */
999 } MDB_pgstate;
1000
1001         /** The database environment. */
1002 struct MDB_env {
1003         HANDLE          me_fd;          /**< The main data file */
1004         HANDLE          me_lfd;         /**< The lock file */
1005         HANDLE          me_mfd;                 /**< just for writing the meta pages */
1006         /** Failed to update the meta page. Probably an I/O error. */
1007 #define MDB_FATAL_ERROR 0x80000000U
1008         /** Some fields are initialized. */
1009 #define MDB_ENV_ACTIVE  0x20000000U
1010         /** me_txkey is set */
1011 #define MDB_ENV_TXKEY   0x10000000U
1012         /** Have liveness lock in reader table */
1013 #define MDB_LIVE_READER 0x08000000U
1014         uint32_t        me_flags;               /**< @ref mdb_env */
1015         unsigned int    me_psize;       /**< DB page size, inited from me_os_psize */
1016         unsigned int    me_os_psize;    /**< OS page size, from #GET_PAGESIZE */
1017         unsigned int    me_maxreaders;  /**< size of the reader table */
1018         unsigned int    me_numreaders;  /**< max numreaders set by this env */
1019         MDB_dbi         me_numdbs;              /**< number of DBs opened */
1020         MDB_dbi         me_maxdbs;              /**< size of the DB table */
1021         MDB_PID_T       me_pid;         /**< process ID of this env */
1022         char            *me_path;               /**< path to the DB files */
1023         char            *me_map;                /**< the memory map of the data file */
1024         MDB_txninfo     *me_txns;               /**< the memory map of the lock file or NULL */
1025         MDB_meta        *me_metas[2];   /**< pointers to the two meta pages */
1026         void            *me_pbuf;               /**< scratch area for DUPSORT put() */
1027         MDB_txn         *me_txn;                /**< current write transaction */
1028         size_t          me_mapsize;             /**< size of the data memory map */
1029         off_t           me_size;                /**< current file size */
1030         pgno_t          me_maxpg;               /**< me_mapsize / me_psize */
1031         MDB_dbx         *me_dbxs;               /**< array of static DB info */
1032         uint16_t        *me_dbflags;    /**< array of flags from MDB_db.md_flags */
1033         pthread_key_t   me_txkey;       /**< thread-key for readers */
1034         MDB_pgstate     me_pgstate;             /**< state of old pages from freeDB */
1035 #       define          me_pglast       me_pgstate.mf_pglast
1036 #       define          me_pghead       me_pgstate.mf_pghead
1037         MDB_page        *me_dpages;             /**< list of malloc'd blocks for re-use */
1038         /** IDL of pages that became unused in a write txn */
1039         MDB_IDL         me_free_pgs;
1040         /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1041         MDB_ID2L        me_dirty_list;
1042         /** Max number of freelist items that can fit in a single overflow page */
1043         int                     me_maxfree_1pg;
1044         /** Max size of a node on a page */
1045         unsigned int    me_nodemax;
1046 #ifdef _WIN32
1047         int             me_pidquery;            /**< Used in OpenProcess */
1048         HANDLE          me_rmutex;              /* Windows mutexes don't reside in shared mem */
1049         HANDLE          me_wmutex;
1050 #elif defined(MDB_USE_POSIX_SEM)
1051         sem_t           *me_rmutex;             /* Shared mutexes are not supported */
1052         sem_t           *me_wmutex;
1053 #endif
1054 };
1055
1056         /** Nested transaction */
1057 typedef struct MDB_ntxn {
1058         MDB_txn         mnt_txn;                /**< the transaction */
1059         MDB_pgstate     mnt_pgstate;    /**< parent transaction's saved freestate */
1060 } MDB_ntxn;
1061
1062         /** max number of pages to commit in one writev() call */
1063 #define MDB_COMMIT_PAGES         64
1064 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1065 #undef MDB_COMMIT_PAGES
1066 #define MDB_COMMIT_PAGES        IOV_MAX
1067 #endif
1068
1069         /* max bytes to write in one call */
1070 #define MAX_WRITE               (0x80000000U >> (sizeof(ssize_t) == 4))
1071
1072 static int  mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1073 static int  mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1074 static int  mdb_page_touch(MDB_cursor *mc);
1075
1076 static int  mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1077 static int  mdb_page_search_root(MDB_cursor *mc,
1078                             MDB_val *key, int modify);
1079 #define MDB_PS_MODIFY   1
1080 #define MDB_PS_ROOTONLY 2
1081 #define MDB_PS_FIRST    4
1082 #define MDB_PS_LAST             8
1083 static int  mdb_page_search(MDB_cursor *mc,
1084                             MDB_val *key, int flags);
1085 static int      mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1086
1087 #define MDB_SPLIT_REPLACE       MDB_APPENDDUP   /**< newkey is not new */
1088 static int      mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1089                                 pgno_t newpgno, unsigned int nflags);
1090
1091 static int  mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1092 static int  mdb_env_pick_meta(const MDB_env *env);
1093 static int  mdb_env_write_meta(MDB_txn *txn);
1094 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1095 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1096 #endif
1097 static void mdb_env_close0(MDB_env *env, int excl);
1098
1099 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1100 static int  mdb_node_add(MDB_cursor *mc, indx_t indx,
1101                             MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1102 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
1103 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1104 static int      mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1105 static int  mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1106 static size_t   mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1107 static size_t   mdb_branch_size(MDB_env *env, MDB_val *key);
1108
1109 static int      mdb_rebalance(MDB_cursor *mc);
1110 static int      mdb_update_key(MDB_cursor *mc, MDB_val *key);
1111
1112 static void     mdb_cursor_pop(MDB_cursor *mc);
1113 static int      mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1114
1115 static int      mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1116 static int      mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1117 static int      mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1118 static int      mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1119 static int      mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1120                                 int *exactp);
1121 static int      mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1122 static int      mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1123
1124 static void     mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1125 static void     mdb_xcursor_init0(MDB_cursor *mc);
1126 static void     mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1127
1128 static int      mdb_drop0(MDB_cursor *mc, int subs);
1129 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1130
1131 /** @cond */
1132 static MDB_cmp_func     mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1133 /** @endcond */
1134
1135 #ifdef _WIN32
1136 static SECURITY_DESCRIPTOR mdb_null_sd;
1137 static SECURITY_ATTRIBUTES mdb_all_sa;
1138 static int mdb_sec_inited;
1139 #endif
1140
1141 /** Return the library version info. */
1142 char *
1143 mdb_version(int *major, int *minor, int *patch)
1144 {
1145         if (major) *major = MDB_VERSION_MAJOR;
1146         if (minor) *minor = MDB_VERSION_MINOR;
1147         if (patch) *patch = MDB_VERSION_PATCH;
1148         return MDB_VERSION_STRING;
1149 }
1150
1151 /** Table of descriptions for MDB @ref errors */
1152 static char *const mdb_errstr[] = {
1153         "MDB_KEYEXIST: Key/data pair already exists",
1154         "MDB_NOTFOUND: No matching key/data pair found",
1155         "MDB_PAGE_NOTFOUND: Requested page not found",
1156         "MDB_CORRUPTED: Located page was wrong type",
1157         "MDB_PANIC: Update of meta page failed",
1158         "MDB_VERSION_MISMATCH: Database environment version mismatch",
1159         "MDB_INVALID: File is not an MDB file",
1160         "MDB_MAP_FULL: Environment mapsize limit reached",
1161         "MDB_DBS_FULL: Environment maxdbs limit reached",
1162         "MDB_READERS_FULL: Environment maxreaders limit reached",
1163         "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1164         "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1165         "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1166         "MDB_PAGE_FULL: Internal error - page has no more space",
1167         "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1168         "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1169         "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1170         "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1171         "MDB_BAD_VALSIZE: Too big key/data, key is empty, or wrong DUPFIXED size",
1172 };
1173
1174 char *
1175 mdb_strerror(int err)
1176 {
1177         int i;
1178         if (!err)
1179                 return ("Successful return: 0");
1180
1181         if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1182                 i = err - MDB_KEYEXIST;
1183                 return mdb_errstr[i];
1184         }
1185
1186         return strerror(err);
1187 }
1188
1189 #if MDB_DEBUG
1190 /** Display a key in hexadecimal and return the address of the result.
1191  * @param[in] key the key to display
1192  * @param[in] buf the buffer to write into. Should always be #DKBUF.
1193  * @return The key in hexadecimal form.
1194  */
1195 char *
1196 mdb_dkey(MDB_val *key, char *buf)
1197 {
1198         char *ptr = buf;
1199         unsigned char *c = key->mv_data;
1200         unsigned int i;
1201
1202         if (!key)
1203                 return "";
1204
1205         if (key->mv_size > MDB_MAXKEYSIZE)
1206                 return "MDB_MAXKEYSIZE";
1207         /* may want to make this a dynamic check: if the key is mostly
1208          * printable characters, print it as-is instead of converting to hex.
1209          */
1210 #if 1
1211         buf[0] = '\0';
1212         for (i=0; i<key->mv_size; i++)
1213                 ptr += sprintf(ptr, "%02x", *c++);
1214 #else
1215         sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1216 #endif
1217         return buf;
1218 }
1219
1220 /** Display all the keys in the page. */
1221 void
1222 mdb_page_list(MDB_page *mp)
1223 {
1224         MDB_node *node;
1225         unsigned int i, nkeys, nsize;
1226         MDB_val key;
1227         DKBUF;
1228
1229         nkeys = NUMKEYS(mp);
1230         fprintf(stderr, "Page %"Z"u numkeys %d\n", mp->mp_pgno, nkeys);
1231         for (i=0; i<nkeys; i++) {
1232                 node = NODEPTR(mp, i);
1233                 key.mv_size = node->mn_ksize;
1234                 key.mv_data = node->mn_data;
1235                 nsize = NODESIZE + NODEKSZ(node) + sizeof(indx_t);
1236                 if (IS_BRANCH(mp)) {
1237                         fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1238                                 DKEY(&key));
1239                 } else {
1240                         if (F_ISSET(node->mn_flags, F_BIGDATA))
1241                                 nsize += sizeof(pgno_t);
1242                         else
1243                                 nsize += NODEDSZ(node);
1244                         fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1245                 }
1246         }
1247 }
1248
1249 void
1250 mdb_cursor_chk(MDB_cursor *mc)
1251 {
1252         unsigned int i;
1253         MDB_node *node;
1254         MDB_page *mp;
1255
1256         if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1257         for (i=0; i<mc->mc_top; i++) {
1258                 mp = mc->mc_pg[i];
1259                 node = NODEPTR(mp, mc->mc_ki[i]);
1260                 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1261                         printf("oops!\n");
1262         }
1263         if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1264                 printf("ack!\n");
1265 }
1266 #endif
1267
1268 #if (MDB_DEBUG) > 2
1269 /** Count all the pages in each DB and in the freelist
1270  *  and make sure it matches the actual number of pages
1271  *  being used.
1272  */
1273 static void mdb_audit(MDB_txn *txn)
1274 {
1275         MDB_cursor mc;
1276         MDB_val key, data;
1277         MDB_ID freecount, count;
1278         MDB_dbi i;
1279         int rc;
1280
1281         freecount = 0;
1282         mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1283         while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1284                 freecount += *(MDB_ID *)data.mv_data;
1285
1286         count = 0;
1287         for (i = 0; i<txn->mt_numdbs; i++) {
1288                 MDB_xcursor mx;
1289                 mdb_cursor_init(&mc, txn, i, &mx);
1290                 if (txn->mt_dbs[i].md_root == P_INVALID)
1291                         continue;
1292                 count += txn->mt_dbs[i].md_branch_pages +
1293                         txn->mt_dbs[i].md_leaf_pages +
1294                         txn->mt_dbs[i].md_overflow_pages;
1295                 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1296                         mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1297                         do {
1298                                 unsigned j;
1299                                 MDB_page *mp;
1300                                 mp = mc.mc_pg[mc.mc_top];
1301                                 for (j=0; j<NUMKEYS(mp); j++) {
1302                                         MDB_node *leaf = NODEPTR(mp, j);
1303                                         if (leaf->mn_flags & F_SUBDATA) {
1304                                                 MDB_db db;
1305                                                 memcpy(&db, NODEDATA(leaf), sizeof(db));
1306                                                 count += db.md_branch_pages + db.md_leaf_pages +
1307                                                         db.md_overflow_pages;
1308                                         }
1309                                 }
1310                         }
1311                         while (mdb_cursor_sibling(&mc, 1) == 0);
1312                 }
1313         }
1314         if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1315                 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1316                         txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1317         }
1318 }
1319 #endif
1320
1321 int
1322 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1323 {
1324         return txn->mt_dbxs[dbi].md_cmp(a, b);
1325 }
1326
1327 int
1328 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1329 {
1330         return txn->mt_dbxs[dbi].md_dcmp(a, b);
1331 }
1332
1333 /** Allocate memory for a page.
1334  * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1335  */
1336 static MDB_page *
1337 mdb_page_malloc(MDB_txn *txn, unsigned num)
1338 {
1339         MDB_env *env = txn->mt_env;
1340         MDB_page *ret = env->me_dpages;
1341         size_t psize = env->me_psize, sz = psize, off;
1342         /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1343          * For a single page alloc, we init everything after the page header.
1344          * For multi-page, we init the final page; if the caller needed that
1345          * many pages they will be filling in at least up to the last page.
1346          */
1347         if (num == 1) {
1348                 if (ret) {
1349                         VGMEMP_ALLOC(env, ret, sz);
1350                         VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1351                         env->me_dpages = ret->mp_next;
1352                         return ret;
1353                 }
1354                 psize -= off = PAGEHDRSZ;
1355         } else {
1356                 sz *= num;
1357                 off = sz - psize;
1358         }
1359         if ((ret = malloc(sz)) != NULL) {
1360                 if (!(env->me_flags & MDB_NOMEMINIT)) {
1361                         memset((char *)ret + off, 0, psize);
1362                         ret->mp_pad = 0;
1363                 }
1364                 VGMEMP_ALLOC(env, ret, sz);
1365         }
1366         return ret;
1367 }
1368
1369 /** Free a single page.
1370  * Saves single pages to a list, for future reuse.
1371  * (This is not used for multi-page overflow pages.)
1372  */
1373 static void
1374 mdb_page_free(MDB_env *env, MDB_page *mp)
1375 {
1376         mp->mp_next = env->me_dpages;
1377         VGMEMP_FREE(env, mp);
1378         env->me_dpages = mp;
1379 }
1380
1381 /** Free a dirty page */
1382 static void
1383 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1384 {
1385         if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1386                 mdb_page_free(env, dp);
1387         } else {
1388                 /* large pages just get freed directly */
1389                 VGMEMP_FREE(env, dp);
1390                 free(dp);
1391         }
1392 }
1393
1394 /**     Return all dirty pages to dpage list */
1395 static void
1396 mdb_dlist_free(MDB_txn *txn)
1397 {
1398         MDB_env *env = txn->mt_env;
1399         MDB_ID2L dl = txn->mt_u.dirty_list;
1400         unsigned i, n = dl[0].mid;
1401
1402         for (i = 1; i <= n; i++) {
1403                 mdb_dpage_free(env, dl[i].mptr);
1404         }
1405         dl[0].mid = 0;
1406 }
1407
1408 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1409  * @param[in] mc A cursor handle for the current operation.
1410  * @param[in] pflags Flags of the pages to update:
1411  * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1412  * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1413  * @return 0 on success, non-zero on failure.
1414  */
1415 static int
1416 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1417 {
1418         enum { Mask = P_SUBP|P_DIRTY|P_KEEP };
1419         MDB_txn *txn = mc->mc_txn;
1420         MDB_cursor *m3;
1421         MDB_xcursor *mx;
1422         MDB_page *dp, *mp;
1423         MDB_node *leaf;
1424         unsigned i, j;
1425         int rc = MDB_SUCCESS, level;
1426
1427         /* Mark pages seen by cursors */
1428         if (mc->mc_flags & C_UNTRACK)
1429                 mc = NULL;                              /* will find mc in mt_cursors */
1430         for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1431                 for (; mc; mc=mc->mc_next) {
1432                         if (!(mc->mc_flags & C_INITIALIZED))
1433                                 continue;
1434                         for (m3 = mc;; m3 = &mx->mx_cursor) {
1435                                 mp = NULL;
1436                                 for (j=0; j<m3->mc_snum; j++) {
1437                                         mp = m3->mc_pg[j];
1438                                         if ((mp->mp_flags & Mask) == pflags)
1439                                                 mp->mp_flags ^= P_KEEP;
1440                                 }
1441                                 mx = m3->mc_xcursor;
1442                                 /* Proceed to mx if it is at a sub-database */
1443                                 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1444                                         break;
1445                                 if (! (mp && (mp->mp_flags & P_LEAF)))
1446                                         break;
1447                                 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1448                                 if (!(leaf->mn_flags & F_SUBDATA))
1449                                         break;
1450                         }
1451                 }
1452                 if (i == 0)
1453                         break;
1454         }
1455
1456         if (all) {
1457                 /* Mark dirty root pages */
1458                 for (i=0; i<txn->mt_numdbs; i++) {
1459                         if (txn->mt_dbflags[i] & DB_DIRTY) {
1460                                 pgno_t pgno = txn->mt_dbs[i].md_root;
1461                                 if (pgno == P_INVALID)
1462                                         continue;
1463                                 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1464                                         break;
1465                                 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1466                                         dp->mp_flags ^= P_KEEP;
1467                         }
1468                 }
1469         }
1470
1471         return rc;
1472 }
1473
1474 static int mdb_page_flush(MDB_txn *txn, int keep);
1475
1476 /**     Spill pages from the dirty list back to disk.
1477  * This is intended to prevent running into #MDB_TXN_FULL situations,
1478  * but note that they may still occur in a few cases:
1479  *      1) our estimate of the txn size could be too small. Currently this
1480  *       seems unlikely, except with a large number of #MDB_MULTIPLE items.
1481  *      2) child txns may run out of space if their parents dirtied a
1482  *       lot of pages and never spilled them. TODO: we probably should do
1483  *       a preemptive spill during #mdb_txn_begin() of a child txn, if
1484  *       the parent's dirty_room is below a given threshold.
1485  *
1486  * Otherwise, if not using nested txns, it is expected that apps will
1487  * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1488  * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1489  * If the txn never references them again, they can be left alone.
1490  * If the txn only reads them, they can be used without any fuss.
1491  * If the txn writes them again, they can be dirtied immediately without
1492  * going thru all of the work of #mdb_page_touch(). Such references are
1493  * handled by #mdb_page_unspill().
1494  *
1495  * Also note, we never spill DB root pages, nor pages of active cursors,
1496  * because we'll need these back again soon anyway. And in nested txns,
1497  * we can't spill a page in a child txn if it was already spilled in a
1498  * parent txn. That would alter the parent txns' data even though
1499  * the child hasn't committed yet, and we'd have no way to undo it if
1500  * the child aborted.
1501  *
1502  * @param[in] m0 cursor A cursor handle identifying the transaction and
1503  *      database for which we are checking space.
1504  * @param[in] key For a put operation, the key being stored.
1505  * @param[in] data For a put operation, the data being stored.
1506  * @return 0 on success, non-zero on failure.
1507  */
1508 static int
1509 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1510 {
1511         MDB_txn *txn = m0->mc_txn;
1512         MDB_page *dp;
1513         MDB_ID2L dl = txn->mt_u.dirty_list;
1514         unsigned int i, j, need;
1515         int rc;
1516
1517         if (m0->mc_flags & C_SUB)
1518                 return MDB_SUCCESS;
1519
1520         /* Estimate how much space this op will take */
1521         i = m0->mc_db->md_depth;
1522         /* Named DBs also dirty the main DB */
1523         if (m0->mc_dbi > MAIN_DBI)
1524                 i += txn->mt_dbs[MAIN_DBI].md_depth;
1525         /* For puts, roughly factor in the key+data size */
1526         if (key)
1527                 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1528         i += i; /* double it for good measure */
1529         need = i;
1530
1531         if (txn->mt_dirty_room > i)
1532                 return MDB_SUCCESS;
1533
1534         if (!txn->mt_spill_pgs) {
1535                 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1536                 if (!txn->mt_spill_pgs)
1537                         return ENOMEM;
1538         } else {
1539                 /* purge deleted slots */
1540                 MDB_IDL sl = txn->mt_spill_pgs;
1541                 unsigned int num = sl[0];
1542                 j=0;
1543                 for (i=1; i<=num; i++) {
1544                         if (!(sl[i] & 1))
1545                                 sl[++j] = sl[i];
1546                 }
1547                 sl[0] = j;
1548         }
1549
1550         /* Preserve pages which may soon be dirtied again */
1551         if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1552                 goto done;
1553
1554         /* Less aggressive spill - we originally spilled the entire dirty list,
1555          * with a few exceptions for cursor pages and DB root pages. But this
1556          * turns out to be a lot of wasted effort because in a large txn many
1557          * of those pages will need to be used again. So now we spill only 1/8th
1558          * of the dirty pages. Testing revealed this to be a good tradeoff,
1559          * better than 1/2, 1/4, or 1/10.
1560          */
1561         if (need < MDB_IDL_UM_MAX / 8)
1562                 need = MDB_IDL_UM_MAX / 8;
1563
1564         /* Save the page IDs of all the pages we're flushing */
1565         /* flush from the tail forward, this saves a lot of shifting later on. */
1566         for (i=dl[0].mid; i && need; i--) {
1567                 MDB_ID pn = dl[i].mid << 1;
1568                 dp = dl[i].mptr;
1569                 if (dp->mp_flags & P_KEEP)
1570                         continue;
1571                 /* Can't spill twice, make sure it's not already in a parent's
1572                  * spill list.
1573                  */
1574                 if (txn->mt_parent) {
1575                         MDB_txn *tx2;
1576                         for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1577                                 if (tx2->mt_spill_pgs) {
1578                                         j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1579                                         if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1580                                                 dp->mp_flags |= P_KEEP;
1581                                                 break;
1582                                         }
1583                                 }
1584                         }
1585                         if (tx2)
1586                                 continue;
1587                 }
1588                 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1589                         goto done;
1590                 need--;
1591         }
1592         mdb_midl_sort(txn->mt_spill_pgs);
1593
1594         /* Flush the spilled part of dirty list */
1595         if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1596                 goto done;
1597
1598         /* Reset any dirty pages we kept that page_flush didn't see */
1599         rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1600
1601 done:
1602         txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1603         return rc;
1604 }
1605
1606 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1607 static txnid_t
1608 mdb_find_oldest(MDB_txn *txn)
1609 {
1610         int i;
1611         txnid_t mr, oldest = txn->mt_txnid - 1;
1612         if (txn->mt_env->me_txns) {
1613                 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1614                 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1615                         if (r[i].mr_pid) {
1616                                 mr = r[i].mr_txnid;
1617                                 if (oldest > mr)
1618                                         oldest = mr;
1619                         }
1620                 }
1621         }
1622         return oldest;
1623 }
1624
1625 /** Add a page to the txn's dirty list */
1626 static void
1627 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1628 {
1629         MDB_ID2 mid;
1630         int (*insert)(MDB_ID2L, MDB_ID2 *);
1631
1632         if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1633                 insert = mdb_mid2l_append;
1634         } else {
1635                 insert = mdb_mid2l_insert;
1636         }
1637         mid.mid = mp->mp_pgno;
1638         mid.mptr = mp;
1639         insert(txn->mt_u.dirty_list, &mid);
1640         txn->mt_dirty_room--;
1641 }
1642
1643 /** Allocate page numbers and memory for writing.  Maintain me_pglast,
1644  * me_pghead and mt_next_pgno.
1645  *
1646  * If there are free pages available from older transactions, they
1647  * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1648  * Do not modify the freedB, just merge freeDB records into me_pghead[]
1649  * and move me_pglast to say which records were consumed.  Only this
1650  * function can create me_pghead and move me_pglast/mt_next_pgno.
1651  * @param[in] mc cursor A cursor handle identifying the transaction and
1652  *      database for which we are allocating.
1653  * @param[in] num the number of pages to allocate.
1654  * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1655  *  will always be satisfied by a single contiguous chunk of memory.
1656  * @return 0 on success, non-zero on failure.
1657  */
1658 static int
1659 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1660 {
1661 #ifdef MDB_PARANOID     /* Seems like we can ignore this now */
1662         /* Get at most <Max_retries> more freeDB records once me_pghead
1663          * has enough pages.  If not enough, use new pages from the map.
1664          * If <Paranoid> and mc is updating the freeDB, only get new
1665          * records if me_pghead is empty. Then the freelist cannot play
1666          * catch-up with itself by growing while trying to save it.
1667          */
1668         enum { Paranoid = 1, Max_retries = 500 };
1669 #else
1670         enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1671 #endif
1672         int rc, n2 = num-1, retry = Max_retries;
1673         MDB_txn *txn = mc->mc_txn;
1674         MDB_env *env = txn->mt_env;
1675         pgno_t pgno, *mop = env->me_pghead;
1676         unsigned i, j, k, mop_len = mop ? mop[0] : 0;
1677         MDB_page *np;
1678         txnid_t oldest = 0, last;
1679         MDB_cursor_op op;
1680         MDB_cursor m2;
1681
1682         *mp = NULL;
1683
1684         /* If our dirty list is already full, we can't do anything */
1685         if (txn->mt_dirty_room == 0)
1686                 return MDB_TXN_FULL;
1687
1688         for (op = MDB_FIRST;; op = MDB_NEXT) {
1689                 MDB_val key, data;
1690                 MDB_node *leaf;
1691                 pgno_t *idl, old_id, new_id;
1692
1693                 /* Seek a big enough contiguous page range. Prefer
1694                  * pages at the tail, just truncating the list.
1695                  */
1696                 if (mop_len >= (unsigned)num) {
1697                         i = mop_len;
1698                         do {
1699                                 pgno = mop[i];
1700                                 if (mop[i-n2] == pgno+n2)
1701                                         goto search_done;
1702                         } while (--i >= (unsigned)num);
1703                         if (Max_retries < INT_MAX && --retry < 0)
1704                                 break;
1705                 }
1706
1707                 if (op == MDB_FIRST) {  /* 1st iteration */
1708                         /* Prepare to fetch more and coalesce */
1709                         oldest = mdb_find_oldest(txn);
1710                         last = env->me_pglast;
1711                         mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1712                         if (last) {
1713                                 op = MDB_SET_RANGE;
1714                                 key.mv_data = &last; /* will look up last+1 */
1715                                 key.mv_size = sizeof(last);
1716                         }
1717                         if (Paranoid && mc->mc_dbi == FREE_DBI)
1718                                 retry = -1;
1719                 }
1720                 if (Paranoid && retry < 0 && mop_len)
1721                         break;
1722
1723                 last++;
1724                 /* Do not fetch more if the record will be too recent */
1725                 if (oldest <= last)
1726                         break;
1727                 rc = mdb_cursor_get(&m2, &key, NULL, op);
1728                 if (rc) {
1729                         if (rc == MDB_NOTFOUND)
1730                                 break;
1731                         return rc;
1732                 }
1733                 last = *(txnid_t*)key.mv_data;
1734                 if (oldest <= last)
1735                         break;
1736                 np = m2.mc_pg[m2.mc_top];
1737                 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1738                 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1739                         return rc;
1740
1741                 idl = (MDB_ID *) data.mv_data;
1742                 i = idl[0];
1743                 if (!mop) {
1744                         if (!(env->me_pghead = mop = mdb_midl_alloc(i)))
1745                                 return ENOMEM;
1746                 } else {
1747                         if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1748                                 return rc;
1749                         mop = env->me_pghead;
1750                 }
1751                 env->me_pglast = last;
1752 #if (MDB_DEBUG) > 1
1753                 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
1754                         last, txn->mt_dbs[FREE_DBI].md_root, i));
1755                 for (k = i; k; k--)
1756                         DPRINTF(("IDL %"Z"u", idl[k]));
1757 #endif
1758                 /* Merge in descending sorted order */
1759                 j = mop_len;
1760                 k = mop_len += i;
1761                 mop[0] = (pgno_t)-1;
1762                 old_id = mop[j];
1763                 while (i) {
1764                         new_id = idl[i--];
1765                         for (; old_id < new_id; old_id = mop[--j])
1766                                 mop[k--] = old_id;
1767                         mop[k--] = new_id;
1768                 }
1769                 mop[0] = mop_len;
1770         }
1771
1772         /* Use new pages from the map when nothing suitable in the freeDB */
1773         i = 0;
1774         pgno = txn->mt_next_pgno;
1775         if (pgno + num >= env->me_maxpg) {
1776                         DPUTS("DB size maxed out");
1777                         return MDB_MAP_FULL;
1778         }
1779
1780 search_done:
1781         if (env->me_flags & MDB_WRITEMAP) {
1782                 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
1783         } else {
1784                 if (!(np = mdb_page_malloc(txn, num)))
1785                         return ENOMEM;
1786         }
1787         if (i) {
1788                 mop[0] = mop_len -= num;
1789                 /* Move any stragglers down */
1790                 for (j = i-num; j < mop_len; )
1791                         mop[++j] = mop[++i];
1792         } else {
1793                 txn->mt_next_pgno = pgno + num;
1794         }
1795         np->mp_pgno = pgno;
1796         mdb_page_dirty(txn, np);
1797         *mp = np;
1798
1799         return MDB_SUCCESS;
1800 }
1801
1802 /** Copy the used portions of a non-overflow page.
1803  * @param[in] dst page to copy into
1804  * @param[in] src page to copy from
1805  * @param[in] psize size of a page
1806  */
1807 static void
1808 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1809 {
1810         enum { Align = sizeof(pgno_t) };
1811         indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
1812
1813         /* If page isn't full, just copy the used portion. Adjust
1814          * alignment so memcpy may copy words instead of bytes.
1815          */
1816         if ((unused &= -Align) && !IS_LEAF2(src)) {
1817                 upper &= -Align;
1818                 memcpy(dst, src, (lower + (Align-1)) & -Align);
1819                 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
1820                         psize - upper);
1821         } else {
1822                 memcpy(dst, src, psize - unused);
1823         }
1824 }
1825
1826 /** Pull a page off the txn's spill list, if present.
1827  * If a page being referenced was spilled to disk in this txn, bring
1828  * it back and make it dirty/writable again.
1829  * @param[in] txn the transaction handle.
1830  * @param[in] mp the page being referenced.
1831  * @param[out] ret the writable page, if any. ret is unchanged if
1832  * mp wasn't spilled.
1833  */
1834 static int
1835 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
1836 {
1837         MDB_env *env = txn->mt_env;
1838         const MDB_txn *tx2;
1839         unsigned x;
1840         pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
1841
1842         for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
1843                 if (!tx2->mt_spill_pgs)
1844                         continue;
1845                 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
1846                 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
1847                         MDB_page *np;
1848                         int num;
1849                         if (txn->mt_dirty_room == 0)
1850                                 return MDB_TXN_FULL;
1851                         if (IS_OVERFLOW(mp))
1852                                 num = mp->mp_pages;
1853                         else
1854                                 num = 1;
1855                         if (env->me_flags & MDB_WRITEMAP) {
1856                                 np = mp;
1857                         } else {
1858                                 np = mdb_page_malloc(txn, num);
1859                                 if (!np)
1860                                         return ENOMEM;
1861                                 if (num > 1)
1862                                         memcpy(np, mp, num * env->me_psize);
1863                                 else
1864                                         mdb_page_copy(np, mp, env->me_psize);
1865                         }
1866                         if (tx2 == txn) {
1867                                 /* If in current txn, this page is no longer spilled.
1868                                  * If it happens to be the last page, truncate the spill list.
1869                                  * Otherwise mark it as deleted by setting the LSB.
1870                                  */
1871                                 if (x == txn->mt_spill_pgs[0])
1872                                         txn->mt_spill_pgs[0]--;
1873                                 else
1874                                         txn->mt_spill_pgs[x] |= 1;
1875                         }       /* otherwise, if belonging to a parent txn, the
1876                                  * page remains spilled until child commits
1877                                  */
1878
1879                         mdb_page_dirty(txn, np);
1880                         np->mp_flags |= P_DIRTY;
1881                         *ret = np;
1882                         break;
1883                 }
1884         }
1885         return MDB_SUCCESS;
1886 }
1887
1888 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1889  * @param[in] mc cursor pointing to the page to be touched
1890  * @return 0 on success, non-zero on failure.
1891  */
1892 static int
1893 mdb_page_touch(MDB_cursor *mc)
1894 {
1895         MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
1896         MDB_txn *txn = mc->mc_txn;
1897         MDB_cursor *m2, *m3;
1898         pgno_t  pgno;
1899         int rc;
1900
1901         if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1902                 if (txn->mt_flags & MDB_TXN_SPILLS) {
1903                         np = NULL;
1904                         rc = mdb_page_unspill(txn, mp, &np);
1905                         if (rc)
1906                                 return rc;
1907                         if (np)
1908                                 goto done;
1909                 }
1910                 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
1911                         (rc = mdb_page_alloc(mc, 1, &np)))
1912                         return rc;
1913                 pgno = np->mp_pgno;
1914                 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
1915                         mp->mp_pgno, pgno));
1916                 assert(mp->mp_pgno != pgno);
1917                 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
1918                 /* Update the parent page, if any, to point to the new page */
1919                 if (mc->mc_top) {
1920                         MDB_page *parent = mc->mc_pg[mc->mc_top-1];
1921                         MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
1922                         SETPGNO(node, pgno);
1923                 } else {
1924                         mc->mc_db->md_root = pgno;
1925                 }
1926         } else if (txn->mt_parent && !IS_SUBP(mp)) {
1927                 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
1928                 pgno = mp->mp_pgno;
1929                 /* If txn has a parent, make sure the page is in our
1930                  * dirty list.
1931                  */
1932                 if (dl[0].mid) {
1933                         unsigned x = mdb_mid2l_search(dl, pgno);
1934                         if (x <= dl[0].mid && dl[x].mid == pgno) {
1935                                 if (mp != dl[x].mptr) { /* bad cursor? */
1936                                         mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1937                                         return MDB_CORRUPTED;
1938                                 }
1939                                 return 0;
1940                         }
1941                 }
1942                 assert(dl[0].mid < MDB_IDL_UM_MAX);
1943                 /* No - copy it */
1944                 np = mdb_page_malloc(txn, 1);
1945                 if (!np)
1946                         return ENOMEM;
1947                 mid.mid = pgno;
1948                 mid.mptr = np;
1949                 mdb_mid2l_insert(dl, &mid);
1950         } else {
1951                 return 0;
1952         }
1953
1954         mdb_page_copy(np, mp, txn->mt_env->me_psize);
1955         np->mp_pgno = pgno;
1956         np->mp_flags |= P_DIRTY;
1957
1958 done:
1959         /* Adjust cursors pointing to mp */
1960         mc->mc_pg[mc->mc_top] = np;
1961         m2 = txn->mt_cursors[mc->mc_dbi];
1962         if (mc->mc_flags & C_SUB) {
1963                 for (; m2; m2=m2->mc_next) {
1964                         m3 = &m2->mc_xcursor->mx_cursor;
1965                         if (m3->mc_snum < mc->mc_snum) continue;
1966                         if (m3->mc_pg[mc->mc_top] == mp)
1967                                 m3->mc_pg[mc->mc_top] = np;
1968                 }
1969         } else {
1970                 for (; m2; m2=m2->mc_next) {
1971                         if (m2->mc_snum < mc->mc_snum) continue;
1972                         if (m2->mc_pg[mc->mc_top] == mp) {
1973                                 m2->mc_pg[mc->mc_top] = np;
1974                                 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
1975                                         m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
1976                                 {
1977                                         MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
1978                                         if (!(leaf->mn_flags & F_SUBDATA))
1979                                                 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
1980                                 }
1981                         }
1982                 }
1983         }
1984         return 0;
1985 }
1986
1987 int
1988 mdb_env_sync(MDB_env *env, int force)
1989 {
1990         int rc = 0;
1991         if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1992                 if (env->me_flags & MDB_WRITEMAP) {
1993                         int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
1994                                 ? MS_ASYNC : MS_SYNC;
1995                         if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
1996                                 rc = ErrCode();
1997 #ifdef _WIN32
1998                         else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
1999                                 rc = ErrCode();
2000 #endif
2001                 } else {
2002                         if (MDB_FDATASYNC(env->me_fd))
2003                                 rc = ErrCode();
2004                 }
2005         }
2006         return rc;
2007 }
2008
2009 /** Back up parent txn's cursors, then grab the originals for tracking */
2010 static int
2011 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2012 {
2013         MDB_cursor *mc, *bk;
2014         MDB_xcursor *mx;
2015         size_t size;
2016         int i;
2017
2018         for (i = src->mt_numdbs; --i >= 0; ) {
2019                 if ((mc = src->mt_cursors[i]) != NULL) {
2020                         size = sizeof(MDB_cursor);
2021                         if (mc->mc_xcursor)
2022                                 size += sizeof(MDB_xcursor);
2023                         for (; mc; mc = bk->mc_next) {
2024                                 bk = malloc(size);
2025                                 if (!bk)
2026                                         return ENOMEM;
2027                                 *bk = *mc;
2028                                 mc->mc_backup = bk;
2029                                 mc->mc_db = &dst->mt_dbs[i];
2030                                 /* Kill pointers into src - and dst to reduce abuse: The
2031                                  * user may not use mc until dst ends. Otherwise we'd...
2032                                  */
2033                                 mc->mc_txn    = NULL;   /* ...set this to dst */
2034                                 mc->mc_dbflag = NULL;   /* ...and &dst->mt_dbflags[i] */
2035                                 if ((mx = mc->mc_xcursor) != NULL) {
2036                                         *(MDB_xcursor *)(bk+1) = *mx;
2037                                         mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2038                                 }
2039                                 mc->mc_next = dst->mt_cursors[i];
2040                                 dst->mt_cursors[i] = mc;
2041                         }
2042                 }
2043         }
2044         return MDB_SUCCESS;
2045 }
2046
2047 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2048  * @param[in] txn the transaction handle.
2049  * @param[in] merge true to keep changes to parent cursors, false to revert.
2050  * @return 0 on success, non-zero on failure.
2051  */
2052 static void
2053 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2054 {
2055         MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2056         MDB_xcursor *mx;
2057         int i;
2058
2059         for (i = txn->mt_numdbs; --i >= 0; ) {
2060                 for (mc = cursors[i]; mc; mc = next) {
2061                         next = mc->mc_next;
2062                         if ((bk = mc->mc_backup) != NULL) {
2063                                 if (merge) {
2064                                         /* Commit changes to parent txn */
2065                                         mc->mc_next = bk->mc_next;
2066                                         mc->mc_backup = bk->mc_backup;
2067                                         mc->mc_txn = bk->mc_txn;
2068                                         mc->mc_db = bk->mc_db;
2069                                         mc->mc_dbflag = bk->mc_dbflag;
2070                                         if ((mx = mc->mc_xcursor) != NULL)
2071                                                 mx->mx_cursor.mc_txn = bk->mc_txn;
2072                                 } else {
2073                                         /* Abort nested txn */
2074                                         *mc = *bk;
2075                                         if ((mx = mc->mc_xcursor) != NULL)
2076                                                 *mx = *(MDB_xcursor *)(bk+1);
2077                                 }
2078                                 mc = bk;
2079                         }
2080                         /* Only malloced cursors are permanently tracked. */
2081                         free(mc);
2082                 }
2083                 cursors[i] = NULL;
2084         }
2085 }
2086
2087 #if !(MDB_DEBUG)
2088 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2089 #endif
2090 static void
2091 mdb_txn_reset0(MDB_txn *txn, const char *act);
2092
2093 #if !(MDB_PIDLOCK)              /* Currently the same as defined(_WIN32) */
2094 enum Pidlock_op {
2095         Pidset, Pidcheck
2096 };
2097 #else
2098 enum Pidlock_op {
2099         Pidset = F_SETLK, Pidcheck = F_GETLK
2100 };
2101 #endif
2102
2103 /** Set or check a pid lock. Set returns 0 on success.
2104  * Check returns 0 if the process is certainly dead, nonzero if it may
2105  * be alive (the lock exists or an error happened so we do not know).
2106  *
2107  * On Windows Pidset is a no-op, we merely check for the existence
2108  * of the process with the given pid. On POSIX we use a single byte
2109  * lock on the lockfile, set at an offset equal to the pid.
2110  */
2111 static int
2112 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2113 {
2114 #if !(MDB_PIDLOCK)              /* Currently the same as defined(_WIN32) */
2115         int ret = 0;
2116         HANDLE h;
2117         if (op == Pidcheck) {
2118                 h = OpenProcess(env->me_pidquery, FALSE, pid);
2119                 /* No documented "no such process" code, but other program use this: */
2120                 if (!h)
2121                         return ErrCode() != ERROR_INVALID_PARAMETER;
2122                 /* A process exists until all handles to it close. Has it exited? */
2123                 ret = WaitForSingleObject(h, 0) != 0;
2124                 CloseHandle(h);
2125         }
2126         return ret;
2127 #else
2128         for (;;) {
2129                 int rc;
2130                 struct flock lock_info;
2131                 memset(&lock_info, 0, sizeof(lock_info));
2132                 lock_info.l_type = F_WRLCK;
2133                 lock_info.l_whence = SEEK_SET;
2134                 lock_info.l_start = pid;
2135                 lock_info.l_len = 1;
2136                 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2137                         if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2138                                 rc = -1;
2139                 } else if ((rc = ErrCode()) == EINTR) {
2140                         continue;
2141                 }
2142                 return rc;
2143         }
2144 #endif
2145 }
2146
2147 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2148  * @param[in] txn the transaction handle to initialize
2149  * @return 0 on success, non-zero on failure.
2150  */
2151 static int
2152 mdb_txn_renew0(MDB_txn *txn)
2153 {
2154         MDB_env *env = txn->mt_env;
2155         MDB_txninfo *ti = env->me_txns;
2156         MDB_meta *meta;
2157         unsigned int i, nr;
2158         uint16_t x;
2159         int rc, new_notls = 0;
2160
2161         /* Setup db info */
2162         txn->mt_numdbs = env->me_numdbs;
2163         txn->mt_dbxs = env->me_dbxs;    /* mostly static anyway */
2164
2165         if (txn->mt_flags & MDB_TXN_RDONLY) {
2166                 if (!ti) {
2167                         meta = env->me_metas[ mdb_env_pick_meta(env) ];
2168                         txn->mt_txnid = meta->mm_txnid;
2169                         txn->mt_u.reader = NULL;
2170                 } else {
2171                         MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2172                                 pthread_getspecific(env->me_txkey);
2173                         if (r) {
2174                                 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2175                                         return MDB_BAD_RSLOT;
2176                         } else {
2177                                 MDB_PID_T pid = env->me_pid;
2178                                 pthread_t tid = pthread_self();
2179
2180                                 if (!(env->me_flags & MDB_LIVE_READER)) {
2181                                         rc = mdb_reader_pid(env, Pidset, pid);
2182                                         if (rc) {
2183                                                 UNLOCK_MUTEX_R(env);
2184                                                 return rc;
2185                                         }
2186                                         env->me_flags |= MDB_LIVE_READER;
2187                                 }
2188
2189                                 LOCK_MUTEX_R(env);
2190                                 nr = ti->mti_numreaders;
2191                                 for (i=0; i<nr; i++)
2192                                         if (ti->mti_readers[i].mr_pid == 0)
2193                                                 break;
2194                                 if (i == env->me_maxreaders) {
2195                                         UNLOCK_MUTEX_R(env);
2196                                         return MDB_READERS_FULL;
2197                                 }
2198                                 ti->mti_readers[i].mr_pid = pid;
2199                                 ti->mti_readers[i].mr_tid = tid;
2200                                 if (i == nr)
2201                                         ti->mti_numreaders = ++nr;
2202                                 /* Save numreaders for un-mutexed mdb_env_close() */
2203                                 env->me_numreaders = nr;
2204                                 UNLOCK_MUTEX_R(env);
2205
2206                                 r = &ti->mti_readers[i];
2207                                 new_notls = (env->me_flags & MDB_NOTLS);
2208                                 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2209                                         r->mr_pid = 0;
2210                                         return rc;
2211                                 }
2212                         }
2213                         txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
2214                         txn->mt_u.reader = r;
2215                         meta = env->me_metas[txn->mt_txnid & 1];
2216                 }
2217         } else {
2218                 if (ti) {
2219                         LOCK_MUTEX_W(env);
2220
2221                         txn->mt_txnid = ti->mti_txnid;
2222                         meta = env->me_metas[txn->mt_txnid & 1];
2223                 } else {
2224                         meta = env->me_metas[ mdb_env_pick_meta(env) ];
2225                         txn->mt_txnid = meta->mm_txnid;
2226                 }
2227                 txn->mt_txnid++;
2228 #if MDB_DEBUG
2229                 if (txn->mt_txnid == mdb_debug_start)
2230                         mdb_debug = 1;
2231 #endif
2232                 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2233                 txn->mt_u.dirty_list = env->me_dirty_list;
2234                 txn->mt_u.dirty_list[0].mid = 0;
2235                 txn->mt_free_pgs = env->me_free_pgs;
2236                 txn->mt_free_pgs[0] = 0;
2237                 txn->mt_spill_pgs = NULL;
2238                 env->me_txn = txn;
2239         }
2240
2241         /* Copy the DB info and flags */
2242         memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2243
2244         /* Moved to here to avoid a data race in read TXNs */
2245         txn->mt_next_pgno = meta->mm_last_pg+1;
2246
2247         for (i=2; i<txn->mt_numdbs; i++) {
2248                 x = env->me_dbflags[i];
2249                 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2250                 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2251         }
2252         txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2253
2254         if (env->me_maxpg < txn->mt_next_pgno) {
2255                 mdb_txn_reset0(txn, "renew0-mapfail");
2256                 if (new_notls) {
2257                         txn->mt_u.reader->mr_pid = 0;
2258                         txn->mt_u.reader = NULL;
2259                 }
2260                 return MDB_MAP_RESIZED;
2261         }
2262
2263         return MDB_SUCCESS;
2264 }
2265
2266 int
2267 mdb_txn_renew(MDB_txn *txn)
2268 {
2269         int rc;
2270
2271         if (!txn || txn->mt_dbxs)       /* A reset txn has mt_dbxs==NULL */
2272                 return EINVAL;
2273
2274         if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2275                 DPUTS("environment had fatal error, must shutdown!");
2276                 return MDB_PANIC;
2277         }
2278
2279         rc = mdb_txn_renew0(txn);
2280         if (rc == MDB_SUCCESS) {
2281                 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2282                         txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2283                         (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2284         }
2285         return rc;
2286 }
2287
2288 int
2289 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2290 {
2291         MDB_txn *txn;
2292         MDB_ntxn *ntxn;
2293         int rc, size, tsize = sizeof(MDB_txn);
2294
2295         if (env->me_flags & MDB_FATAL_ERROR) {
2296                 DPUTS("environment had fatal error, must shutdown!");
2297                 return MDB_PANIC;
2298         }
2299         if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2300                 return EACCES;
2301         if (parent) {
2302                 /* Nested transactions: Max 1 child, write txns only, no writemap */
2303                 if (parent->mt_child ||
2304                         (flags & MDB_RDONLY) ||
2305                         (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2306                         (env->me_flags & MDB_WRITEMAP))
2307                 {
2308                         return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2309                 }
2310                 tsize = sizeof(MDB_ntxn);
2311         }
2312         size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2313         if (!(flags & MDB_RDONLY))
2314                 size += env->me_maxdbs * sizeof(MDB_cursor *);
2315
2316         if ((txn = calloc(1, size)) == NULL) {
2317                 DPRINTF(("calloc: %s", strerror(ErrCode())));
2318                 return ENOMEM;
2319         }
2320         txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2321         if (flags & MDB_RDONLY) {
2322                 txn->mt_flags |= MDB_TXN_RDONLY;
2323                 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2324         } else {
2325                 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2326                 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2327         }
2328         txn->mt_env = env;
2329
2330         if (parent) {
2331                 unsigned int i;
2332                 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2333                 if (!txn->mt_u.dirty_list ||
2334                         !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2335                 {
2336                         free(txn->mt_u.dirty_list);
2337                         free(txn);
2338                         return ENOMEM;
2339                 }
2340                 txn->mt_txnid = parent->mt_txnid;
2341                 txn->mt_dirty_room = parent->mt_dirty_room;
2342                 txn->mt_u.dirty_list[0].mid = 0;
2343                 txn->mt_spill_pgs = NULL;
2344                 txn->mt_next_pgno = parent->mt_next_pgno;
2345                 parent->mt_child = txn;
2346                 txn->mt_parent = parent;
2347                 txn->mt_numdbs = parent->mt_numdbs;
2348                 txn->mt_flags = parent->mt_flags;
2349                 txn->mt_dbxs = parent->mt_dbxs;
2350                 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2351                 /* Copy parent's mt_dbflags, but clear DB_NEW */
2352                 for (i=0; i<txn->mt_numdbs; i++)
2353                         txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2354                 rc = 0;
2355                 ntxn = (MDB_ntxn *)txn;
2356                 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2357                 if (env->me_pghead) {
2358                         size = MDB_IDL_SIZEOF(env->me_pghead);
2359                         env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2360                         if (env->me_pghead)
2361                                 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2362                         else
2363                                 rc = ENOMEM;
2364                 }
2365                 if (!rc)
2366                         rc = mdb_cursor_shadow(parent, txn);
2367                 if (rc)
2368                         mdb_txn_reset0(txn, "beginchild-fail");
2369         } else {
2370                 rc = mdb_txn_renew0(txn);
2371         }
2372         if (rc)
2373                 free(txn);
2374         else {
2375                 *ret = txn;
2376                 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2377                         txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2378                         (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2379         }
2380
2381         return rc;
2382 }
2383
2384 MDB_env *
2385 mdb_txn_env(MDB_txn *txn)
2386 {
2387         if(!txn) return NULL;
2388         return txn->mt_env;
2389 }
2390
2391 /** Export or close DBI handles opened in this txn. */
2392 static void
2393 mdb_dbis_update(MDB_txn *txn, int keep)
2394 {
2395         int i;
2396         MDB_dbi n = txn->mt_numdbs;
2397         MDB_env *env = txn->mt_env;
2398         unsigned char *tdbflags = txn->mt_dbflags;
2399
2400         for (i = n; --i >= 2;) {
2401                 if (tdbflags[i] & DB_NEW) {
2402                         if (keep) {
2403                                 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2404                         } else {
2405                                 char *ptr = env->me_dbxs[i].md_name.mv_data;
2406                                 env->me_dbxs[i].md_name.mv_data = NULL;
2407                                 env->me_dbxs[i].md_name.mv_size = 0;
2408                                 env->me_dbflags[i] = 0;
2409                                 free(ptr);
2410                         }
2411                 }
2412         }
2413         if (keep && env->me_numdbs < n)
2414                 env->me_numdbs = n;
2415 }
2416
2417 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2418  * May be called twice for readonly txns: First reset it, then abort.
2419  * @param[in] txn the transaction handle to reset
2420  * @param[in] act why the transaction is being reset
2421  */
2422 static void
2423 mdb_txn_reset0(MDB_txn *txn, const char *act)
2424 {
2425         MDB_env *env = txn->mt_env;
2426
2427         /* Close any DBI handles opened in this txn */
2428         mdb_dbis_update(txn, 0);
2429
2430         DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2431                 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2432                 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2433
2434         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2435                 if (txn->mt_u.reader) {
2436                         txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2437                         if (!(env->me_flags & MDB_NOTLS))
2438                                 txn->mt_u.reader = NULL; /* txn does not own reader */
2439                 }
2440                 txn->mt_numdbs = 0;             /* close nothing if called again */
2441                 txn->mt_dbxs = NULL;    /* mark txn as reset */
2442         } else {
2443                 mdb_cursors_close(txn, 0);
2444
2445                 if (!(env->me_flags & MDB_WRITEMAP)) {
2446                         mdb_dlist_free(txn);
2447                 }
2448                 mdb_midl_free(env->me_pghead);
2449
2450                 if (txn->mt_parent) {
2451                         txn->mt_parent->mt_child = NULL;
2452                         env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2453                         mdb_midl_free(txn->mt_free_pgs);
2454                         mdb_midl_free(txn->mt_spill_pgs);
2455                         free(txn->mt_u.dirty_list);
2456                         return;
2457                 }
2458
2459                 if (mdb_midl_shrink(&txn->mt_free_pgs))
2460                         env->me_free_pgs = txn->mt_free_pgs;
2461                 env->me_pghead = NULL;
2462                 env->me_pglast = 0;
2463
2464                 env->me_txn = NULL;
2465                 /* The writer mutex was locked in mdb_txn_begin. */
2466                 if (env->me_txns)
2467                         UNLOCK_MUTEX_W(env);
2468         }
2469 }
2470
2471 void
2472 mdb_txn_reset(MDB_txn *txn)
2473 {
2474         if (txn == NULL)
2475                 return;
2476
2477         /* This call is only valid for read-only txns */
2478         if (!(txn->mt_flags & MDB_TXN_RDONLY))
2479                 return;
2480
2481         mdb_txn_reset0(txn, "reset");
2482 }
2483
2484 void
2485 mdb_txn_abort(MDB_txn *txn)
2486 {
2487         if (txn == NULL)
2488                 return;
2489
2490         if (txn->mt_child)
2491                 mdb_txn_abort(txn->mt_child);
2492
2493         mdb_txn_reset0(txn, "abort");
2494         /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2495         if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2496                 txn->mt_u.reader->mr_pid = 0;
2497
2498         free(txn);
2499 }
2500
2501 /** Save the freelist as of this transaction to the freeDB.
2502  * This changes the freelist. Keep trying until it stabilizes.
2503  */
2504 static int
2505 mdb_freelist_save(MDB_txn *txn)
2506 {
2507         /* env->me_pghead[] can grow and shrink during this call.
2508          * env->me_pglast and txn->mt_free_pgs[] can only grow.
2509          * Page numbers cannot disappear from txn->mt_free_pgs[].
2510          */
2511         MDB_cursor mc;
2512         MDB_env *env = txn->mt_env;
2513         int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2514         txnid_t pglast = 0, head_id = 0;
2515         pgno_t  freecnt = 0, *free_pgs, *mop;
2516         ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2517
2518         mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2519
2520         if (env->me_pghead) {
2521                 /* Make sure first page of freeDB is touched and on freelist */
2522                 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2523                 if (rc && rc != MDB_NOTFOUND)
2524                         return rc;
2525         }
2526
2527         /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2528         clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2529                 ? SSIZE_MAX : maxfree_1pg;
2530
2531         for (;;) {
2532                 /* Come back here after each Put() in case freelist changed */
2533                 MDB_val key, data;
2534                 pgno_t *pgs;
2535                 ssize_t j;
2536
2537                 /* If using records from freeDB which we have not yet
2538                  * deleted, delete them and any we reserved for me_pghead.
2539                  */
2540                 while (pglast < env->me_pglast) {
2541                         rc = mdb_cursor_first(&mc, &key, NULL);
2542                         if (rc)
2543                                 return rc;
2544                         pglast = head_id = *(txnid_t *)key.mv_data;
2545                         total_room = head_room = 0;
2546                         assert(pglast <= env->me_pglast);
2547                         rc = mdb_cursor_del(&mc, 0);
2548                         if (rc)
2549                                 return rc;
2550                 }
2551
2552                 /* Save the IDL of pages freed by this txn, to a single record */
2553                 if (freecnt < txn->mt_free_pgs[0]) {
2554                         if (!freecnt) {
2555                                 /* Make sure last page of freeDB is touched and on freelist */
2556                                 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2557                                 if (rc && rc != MDB_NOTFOUND)
2558                                         return rc;
2559                         }
2560                         free_pgs = txn->mt_free_pgs;
2561                         /* Write to last page of freeDB */
2562                         key.mv_size = sizeof(txn->mt_txnid);
2563                         key.mv_data = &txn->mt_txnid;
2564                         do {
2565                                 freecnt = free_pgs[0];
2566                                 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2567                                 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2568                                 if (rc)
2569                                         return rc;
2570                                 /* Retry if mt_free_pgs[] grew during the Put() */
2571                                 free_pgs = txn->mt_free_pgs;
2572                         } while (freecnt < free_pgs[0]);
2573                         mdb_midl_sort(free_pgs);
2574                         memcpy(data.mv_data, free_pgs, data.mv_size);
2575 #if (MDB_DEBUG) > 1
2576                         {
2577                                 unsigned int i = free_pgs[0];
2578                                 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2579                                         txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2580                                 for (; i; i--)
2581                                         DPRINTF(("IDL %"Z"u", free_pgs[i]));
2582                         }
2583 #endif
2584                         continue;
2585                 }
2586
2587                 mop = env->me_pghead;
2588                 mop_len = mop ? mop[0] : 0;
2589
2590                 /* Reserve records for me_pghead[]. Split it if multi-page,
2591                  * to avoid searching freeDB for a page range. Use keys in
2592                  * range [1,me_pglast]: Smaller than txnid of oldest reader.
2593                  */
2594                 if (total_room >= mop_len) {
2595                         if (total_room == mop_len || --more < 0)
2596                                 break;
2597                 } else if (head_room >= maxfree_1pg && head_id > 1) {
2598                         /* Keep current record (overflow page), add a new one */
2599                         head_id--;
2600                         head_room = 0;
2601                 }
2602                 /* (Re)write {key = head_id, IDL length = head_room} */
2603                 total_room -= head_room;
2604                 head_room = mop_len - total_room;
2605                 if (head_room > maxfree_1pg && head_id > 1) {
2606                         /* Overflow multi-page for part of me_pghead */
2607                         head_room /= head_id; /* amortize page sizes */
2608                         head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2609                 } else if (head_room < 0) {
2610                         /* Rare case, not bothering to delete this record */
2611                         head_room = 0;
2612                 }
2613                 key.mv_size = sizeof(head_id);
2614                 key.mv_data = &head_id;
2615                 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2616                 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2617                 if (rc)
2618                         return rc;
2619                 /* IDL is initially empty, zero out at least the length */
2620                 pgs = (pgno_t *)data.mv_data;
2621                 j = head_room > clean_limit ? head_room : 0;
2622                 do {
2623                         pgs[j] = 0;
2624                 } while (--j >= 0);
2625                 total_room += head_room;
2626         }
2627
2628         /* Fill in the reserved me_pghead records */
2629         rc = MDB_SUCCESS;
2630         if (mop_len) {
2631                 MDB_val key, data;
2632
2633                 mop += mop_len;
2634                 rc = mdb_cursor_first(&mc, &key, &data);
2635                 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2636                         unsigned flags = MDB_CURRENT;
2637                         txnid_t id = *(txnid_t *)key.mv_data;
2638                         ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2639                         MDB_ID save;
2640
2641                         assert(len >= 0 && id <= env->me_pglast);
2642                         key.mv_data = &id;
2643                         if (len > mop_len) {
2644                                 len = mop_len;
2645                                 data.mv_size = (len + 1) * sizeof(MDB_ID);
2646                                 flags = 0;
2647                         }
2648                         data.mv_data = mop -= len;
2649                         save = mop[0];
2650                         mop[0] = len;
2651                         rc = mdb_cursor_put(&mc, &key, &data, flags);
2652                         mop[0] = save;
2653                         if (rc || !(mop_len -= len))
2654                                 break;
2655                 }
2656         }
2657         return rc;
2658 }
2659
2660 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
2661  * @param[in] txn the transaction that's being committed
2662  * @param[in] keep number of initial pages in dirty_list to keep dirty.
2663  * @return 0 on success, non-zero on failure.
2664  */
2665 static int
2666 mdb_page_flush(MDB_txn *txn, int keep)
2667 {
2668         MDB_env         *env = txn->mt_env;
2669         MDB_ID2L        dl = txn->mt_u.dirty_list;
2670         unsigned        psize = env->me_psize, j;
2671         int                     i, pagecount = dl[0].mid, rc;
2672         size_t          size = 0, pos = 0;
2673         pgno_t          pgno = 0;
2674         MDB_page        *dp = NULL;
2675 #ifdef _WIN32
2676         OVERLAPPED      ov;
2677 #else
2678         struct iovec iov[MDB_COMMIT_PAGES];
2679         ssize_t         wpos = 0, wsize = 0, wres;
2680         size_t          next_pos = 1; /* impossible pos, so pos != next_pos */
2681         int                     n = 0;
2682 #endif
2683
2684         j = i = keep;
2685
2686         if (env->me_flags & MDB_WRITEMAP) {
2687                 /* Clear dirty flags */
2688                 while (++i <= pagecount) {
2689                         dp = dl[i].mptr;
2690                         /* Don't flush this page yet */
2691                         if (dp->mp_flags & P_KEEP) {
2692                                 dp->mp_flags ^= P_KEEP;
2693                                 dl[++j] = dl[i];
2694                                 continue;
2695                         }
2696                         dp->mp_flags &= ~P_DIRTY;
2697                 }
2698                 goto done;
2699         }
2700
2701         /* Write the pages */
2702         for (;;) {
2703                 if (++i <= pagecount) {
2704                         dp = dl[i].mptr;
2705                         /* Don't flush this page yet */
2706                         if (dp->mp_flags & P_KEEP) {
2707                                 dp->mp_flags ^= P_KEEP;
2708                                 dl[i].mid = 0;
2709                                 continue;
2710                         }
2711                         pgno = dl[i].mid;
2712                         /* clear dirty flag */
2713                         dp->mp_flags &= ~P_DIRTY;
2714                         pos = pgno * psize;
2715                         size = psize;
2716                         if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
2717                 }
2718 #ifdef _WIN32
2719                 else break;
2720
2721                 /* Windows actually supports scatter/gather I/O, but only on
2722                  * unbuffered file handles. Since we're relying on the OS page
2723                  * cache for all our data, that's self-defeating. So we just
2724                  * write pages one at a time. We use the ov structure to set
2725                  * the write offset, to at least save the overhead of a Seek
2726                  * system call.
2727                  */
2728                 DPRINTF(("committing page %"Z"u", pgno));
2729                 memset(&ov, 0, sizeof(ov));
2730                 ov.Offset = pos & 0xffffffff;
2731                 ov.OffsetHigh = pos >> 16 >> 16;
2732                 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
2733                         rc = ErrCode();
2734                         DPRINTF(("WriteFile: %d", rc));
2735                         return rc;
2736                 }
2737 #else
2738                 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
2739                 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
2740                         if (n) {
2741                                 /* Write previous page(s) */
2742 #ifdef MDB_USE_PWRITEV
2743                                 wres = pwritev(env->me_fd, iov, n, wpos);
2744 #else
2745                                 if (n == 1) {
2746                                         wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
2747                                 } else {
2748                                         if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
2749                                                 rc = ErrCode();
2750                                                 DPRINTF(("lseek: %s", strerror(rc)));
2751                                                 return rc;
2752                                         }
2753                                         wres = writev(env->me_fd, iov, n);
2754                                 }
2755 #endif
2756                                 if (wres != wsize) {
2757                                         if (wres < 0) {
2758                                                 rc = ErrCode();
2759                                                 DPRINTF(("Write error: %s", strerror(rc)));
2760                                         } else {
2761                                                 rc = EIO; /* TODO: Use which error code? */
2762                                                 DPUTS("short write, filesystem full?");
2763                                         }
2764                                         return rc;
2765                                 }
2766                                 n = 0;
2767                         }
2768                         if (i > pagecount)
2769                                 break;
2770                         wpos = pos;
2771                         wsize = 0;
2772                 }
2773                 DPRINTF(("committing page %"Z"u", pgno));
2774                 next_pos = pos + size;
2775                 iov[n].iov_len = size;
2776                 iov[n].iov_base = (char *)dp;
2777                 wsize += size;
2778                 n++;
2779 #endif  /* _WIN32 */
2780         }
2781
2782         for (i = keep; ++i <= pagecount; ) {
2783                 dp = dl[i].mptr;
2784                 /* This is a page we skipped above */
2785                 if (!dl[i].mid) {
2786                         dl[++j] = dl[i];
2787                         dl[j].mid = dp->mp_pgno;
2788                         continue;
2789                 }
2790                 mdb_dpage_free(env, dp);
2791         }
2792
2793 done:
2794         i--;
2795         txn->mt_dirty_room += i - j;
2796         dl[0].mid = j;
2797         return MDB_SUCCESS;
2798 }
2799
2800 int
2801 mdb_txn_commit(MDB_txn *txn)
2802 {
2803         int             rc;
2804         unsigned int i;
2805         MDB_env *env;
2806
2807         assert(txn != NULL);
2808         assert(txn->mt_env != NULL);
2809
2810         if (txn->mt_child) {
2811                 rc = mdb_txn_commit(txn->mt_child);
2812                 txn->mt_child = NULL;
2813                 if (rc)
2814                         goto fail;
2815         }
2816
2817         env = txn->mt_env;
2818
2819         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2820                 mdb_dbis_update(txn, 1);
2821                 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
2822                 mdb_txn_abort(txn);
2823                 return MDB_SUCCESS;
2824         }
2825
2826         if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2827                 DPUTS("error flag is set, can't commit");
2828                 if (txn->mt_parent)
2829                         txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
2830                 rc = MDB_BAD_TXN;
2831                 goto fail;
2832         }
2833
2834         if (txn->mt_parent) {
2835                 MDB_txn *parent = txn->mt_parent;
2836                 MDB_ID2L dst, src;
2837                 MDB_IDL pspill;
2838                 unsigned x, y, len, ps_len;
2839
2840                 /* Append our free list to parent's */
2841                 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
2842                 if (rc)
2843                         goto fail;
2844                 mdb_midl_free(txn->mt_free_pgs);
2845                 /* Failures after this must either undo the changes
2846                  * to the parent or set MDB_TXN_ERROR in the parent.
2847                  */
2848
2849                 parent->mt_next_pgno = txn->mt_next_pgno;
2850                 parent->mt_flags = txn->mt_flags;
2851
2852                 /* Merge our cursors into parent's and close them */
2853                 mdb_cursors_close(txn, 1);
2854
2855                 /* Update parent's DB table. */
2856                 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2857                 parent->mt_numdbs = txn->mt_numdbs;
2858                 parent->mt_dbflags[0] = txn->mt_dbflags[0];
2859                 parent->mt_dbflags[1] = txn->mt_dbflags[1];
2860                 for (i=2; i<txn->mt_numdbs; i++) {
2861                         /* preserve parent's DB_NEW status */
2862                         x = parent->mt_dbflags[i] & DB_NEW;
2863                         parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
2864                 }
2865
2866                 dst = parent->mt_u.dirty_list;
2867                 src = txn->mt_u.dirty_list;
2868                 /* Remove anything in our dirty list from parent's spill list */
2869                 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
2870                         x = y = ps_len;
2871                         pspill[0] = (pgno_t)-1;
2872                         /* Mark our dirty pages as deleted in parent spill list */
2873                         for (i=0, len=src[0].mid; ++i <= len; ) {
2874                                 MDB_ID pn = src[i].mid << 1;
2875                                 while (pn > pspill[x])
2876                                         x--;
2877                                 if (pn == pspill[x]) {
2878                                         pspill[x] = 1;
2879                                         y = --x;
2880                                 }
2881                         }
2882                         /* Squash deleted pagenums if we deleted any */
2883                         for (x=y; ++x <= ps_len; )
2884                                 if (!(pspill[x] & 1))
2885                                         pspill[++y] = pspill[x];
2886                         pspill[0] = y;
2887                 }
2888
2889                 /* Find len = length of merging our dirty list with parent's */
2890                 x = dst[0].mid;
2891                 dst[0].mid = 0;         /* simplify loops */
2892                 if (parent->mt_parent) {
2893                         len = x + src[0].mid;
2894                         y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
2895                         for (i = x; y && i; y--) {
2896                                 pgno_t yp = src[y].mid;
2897                                 while (yp < dst[i].mid)
2898                                         i--;
2899                                 if (yp == dst[i].mid) {
2900                                         i--;
2901                                         len--;
2902                                 }
2903                         }
2904                 } else { /* Simplify the above for single-ancestor case */
2905                         len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
2906                 }
2907                 /* Merge our dirty list with parent's */
2908                 y = src[0].mid;
2909                 for (i = len; y; dst[i--] = src[y--]) {
2910                         pgno_t yp = src[y].mid;
2911                         while (yp < dst[x].mid)
2912                                 dst[i--] = dst[x--];
2913                         if (yp == dst[x].mid)
2914                                 free(dst[x--].mptr);
2915                 }
2916                 assert(i == x);
2917                 dst[0].mid = len;
2918                 free(txn->mt_u.dirty_list);
2919                 parent->mt_dirty_room = txn->mt_dirty_room;
2920                 if (txn->mt_spill_pgs) {
2921                         if (parent->mt_spill_pgs) {
2922                                 /* TODO: Prevent failure here, so parent does not fail */
2923                                 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
2924                                 if (rc)
2925                                         parent->mt_flags |= MDB_TXN_ERROR;
2926                                 mdb_midl_free(txn->mt_spill_pgs);
2927                                 mdb_midl_sort(parent->mt_spill_pgs);
2928                         } else {
2929                                 parent->mt_spill_pgs = txn->mt_spill_pgs;
2930                         }
2931                 }
2932
2933                 parent->mt_child = NULL;
2934                 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
2935                 free(txn);
2936                 return rc;
2937         }
2938
2939         if (txn != env->me_txn) {
2940                 DPUTS("attempt to commit unknown transaction");
2941                 rc = EINVAL;
2942                 goto fail;
2943         }
2944
2945         mdb_cursors_close(txn, 0);
2946
2947         if (!txn->mt_u.dirty_list[0].mid &&
2948                 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
2949                 goto done;
2950
2951         DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
2952             txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
2953
2954         /* Update DB root pointers */
2955         if (txn->mt_numdbs > 2) {
2956                 MDB_cursor mc;
2957                 MDB_dbi i;
2958                 MDB_val data;
2959                 data.mv_size = sizeof(MDB_db);
2960
2961                 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2962                 for (i = 2; i < txn->mt_numdbs; i++) {
2963                         if (txn->mt_dbflags[i] & DB_DIRTY) {
2964                                 data.mv_data = &txn->mt_dbs[i];
2965                                 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2966                                 if (rc)
2967                                         goto fail;
2968                         }
2969                 }
2970         }
2971
2972         rc = mdb_freelist_save(txn);
2973         if (rc)
2974                 goto fail;
2975
2976         mdb_midl_free(env->me_pghead);
2977         env->me_pghead = NULL;
2978         if (mdb_midl_shrink(&txn->mt_free_pgs))
2979                 env->me_free_pgs = txn->mt_free_pgs;
2980
2981 #if (MDB_DEBUG) > 2
2982         mdb_audit(txn);
2983 #endif
2984
2985         if ((rc = mdb_page_flush(txn, 0)) ||
2986                 (rc = mdb_env_sync(env, 0)) ||
2987                 (rc = mdb_env_write_meta(txn)))
2988                 goto fail;
2989
2990 done:
2991         env->me_pglast = 0;
2992         env->me_txn = NULL;
2993         mdb_dbis_update(txn, 1);
2994
2995         if (env->me_txns)
2996                 UNLOCK_MUTEX_W(env);
2997         free(txn);
2998
2999         return MDB_SUCCESS;
3000
3001 fail:
3002         mdb_txn_abort(txn);
3003         return rc;
3004 }
3005
3006 /** Read the environment parameters of a DB environment before
3007  * mapping it into memory.
3008  * @param[in] env the environment handle
3009  * @param[out] meta address of where to store the meta information
3010  * @return 0 on success, non-zero on failure.
3011  */
3012 static int
3013 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3014 {
3015         MDB_metabuf     pbuf;
3016         MDB_page        *p;
3017         MDB_meta        *m;
3018         int                     i, rc, off;
3019         enum { Size = sizeof(pbuf) };
3020
3021         /* We don't know the page size yet, so use a minimum value.
3022          * Read both meta pages so we can use the latest one.
3023          */
3024
3025         for (i=off=0; i<2; i++, off = meta->mm_psize) {
3026 #ifdef _WIN32
3027                 DWORD len;
3028                 OVERLAPPED ov;
3029                 memset(&ov, 0, sizeof(ov));
3030                 ov.Offset = off;
3031                 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3032                 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3033                         rc = 0;
3034 #else
3035                 rc = pread(env->me_fd, &pbuf, Size, off);
3036 #endif
3037                 if (rc != Size) {
3038                         if (rc == 0 && off == 0)
3039                                 return ENOENT;
3040                         rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3041                         DPRINTF(("read: %s", mdb_strerror(rc)));
3042                         return rc;
3043                 }
3044
3045                 p = (MDB_page *)&pbuf;
3046
3047                 if (!F_ISSET(p->mp_flags, P_META)) {
3048                         DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3049                         return MDB_INVALID;
3050                 }
3051
3052                 m = METADATA(p);
3053                 if (m->mm_magic != MDB_MAGIC) {
3054                         DPUTS("meta has invalid magic");
3055                         return MDB_INVALID;
3056                 }
3057
3058                 if (m->mm_version != MDB_DATA_VERSION) {
3059                         DPRINTF(("database is version %u, expected version %u",
3060                                 m->mm_version, MDB_DATA_VERSION));
3061                         return MDB_VERSION_MISMATCH;
3062                 }
3063
3064                 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3065                         *meta = *m;
3066         }
3067         return 0;
3068 }
3069
3070 /** Write the environment parameters of a freshly created DB environment.
3071  * @param[in] env the environment handle
3072  * @param[out] meta address of where to store the meta information
3073  * @return 0 on success, non-zero on failure.
3074  */
3075 static int
3076 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3077 {
3078         MDB_page *p, *q;
3079         int rc;
3080         unsigned int     psize;
3081 #ifdef _WIN32
3082         DWORD len;
3083         OVERLAPPED ov;
3084         memset(&ov, 0, sizeof(ov));
3085 #define DO_PWRITE(rc, fd, ptr, size, len, pos)  do { \
3086         ov.Offset = pos;        \
3087         rc = WriteFile(fd, ptr, size, &len, &ov);       } while(0)
3088 #else
3089         int len;
3090 #define DO_PWRITE(rc, fd, ptr, size, len, pos)  do { \
3091         len = pwrite(fd, ptr, size, pos);       \
3092         rc = (len >= 0); } while(0)
3093 #endif
3094
3095         DPUTS("writing new meta page");
3096
3097         psize = env->me_psize;
3098
3099         meta->mm_magic = MDB_MAGIC;
3100         meta->mm_version = MDB_DATA_VERSION;
3101         meta->mm_mapsize = env->me_mapsize;
3102         meta->mm_psize = psize;
3103         meta->mm_last_pg = 1;
3104         meta->mm_flags = env->me_flags & 0xffff;
3105         meta->mm_flags |= MDB_INTEGERKEY;
3106         meta->mm_dbs[0].md_root = P_INVALID;
3107         meta->mm_dbs[1].md_root = P_INVALID;
3108
3109         p = calloc(2, psize);
3110         p->mp_pgno = 0;
3111         p->mp_flags = P_META;
3112         *(MDB_meta *)METADATA(p) = *meta;
3113
3114         q = (MDB_page *)((char *)p + psize);
3115         q->mp_pgno = 1;
3116         q->mp_flags = P_META;
3117         *(MDB_meta *)METADATA(q) = *meta;
3118
3119         DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3120         if (!rc)
3121                 rc = ErrCode();
3122         else if ((unsigned) len == psize * 2)
3123                 rc = MDB_SUCCESS;
3124         else
3125                 rc = ENOSPC;
3126         free(p);
3127         return rc;
3128 }
3129
3130 /** Update the environment info to commit a transaction.
3131  * @param[in] txn the transaction that's being committed
3132  * @return 0 on success, non-zero on failure.
3133  */
3134 static int
3135 mdb_env_write_meta(MDB_txn *txn)
3136 {
3137         MDB_env *env;
3138         MDB_meta        meta, metab, *mp;
3139         off_t off;
3140         int rc, len, toggle;
3141         char *ptr;
3142         HANDLE mfd;
3143 #ifdef _WIN32
3144         OVERLAPPED ov;
3145 #else
3146         int r2;
3147 #endif
3148
3149         assert(txn != NULL);
3150         assert(txn->mt_env != NULL);
3151
3152         toggle = txn->mt_txnid & 1;
3153         DPRINTF(("writing meta page %d for root page %"Z"u",
3154                 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3155
3156         env = txn->mt_env;
3157         mp = env->me_metas[toggle];
3158
3159         if (env->me_flags & MDB_WRITEMAP) {
3160                 /* Persist any increases of mapsize config */
3161                 if (env->me_mapsize > mp->mm_mapsize)
3162                         mp->mm_mapsize = env->me_mapsize;
3163                 mp->mm_dbs[0] = txn->mt_dbs[0];
3164                 mp->mm_dbs[1] = txn->mt_dbs[1];
3165                 mp->mm_last_pg = txn->mt_next_pgno - 1;
3166                 mp->mm_txnid = txn->mt_txnid;
3167                 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3168                         unsigned meta_size = env->me_psize;
3169                         rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3170                         ptr = env->me_map;
3171                         if (toggle) {
3172 #ifndef _WIN32  /* POSIX msync() requires ptr = start of OS page */
3173                                 if (meta_size < env->me_os_psize)
3174                                         meta_size += meta_size;
3175                                 else
3176 #endif
3177                                         ptr += meta_size;
3178                         }
3179                         if (MDB_MSYNC(ptr, meta_size, rc)) {
3180                                 rc = ErrCode();
3181                                 goto fail;
3182                         }
3183                 }
3184                 goto done;
3185         }
3186         metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3187         metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3188
3189         ptr = (char *)&meta;
3190         if (env->me_mapsize > mp->mm_mapsize) {
3191                 /* Persist any increases of mapsize config */
3192                 meta.mm_mapsize = env->me_mapsize;
3193                 off = offsetof(MDB_meta, mm_mapsize);
3194         } else {
3195                 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
3196         }
3197         len = sizeof(MDB_meta) - off;
3198
3199         ptr += off;
3200         meta.mm_dbs[0] = txn->mt_dbs[0];
3201         meta.mm_dbs[1] = txn->mt_dbs[1];
3202         meta.mm_last_pg = txn->mt_next_pgno - 1;
3203         meta.mm_txnid = txn->mt_txnid;
3204
3205         if (toggle)
3206                 off += env->me_psize;
3207         off += PAGEHDRSZ;
3208
3209         /* Write to the SYNC fd */
3210         mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3211                 env->me_fd : env->me_mfd;
3212 #ifdef _WIN32
3213         {
3214                 memset(&ov, 0, sizeof(ov));
3215                 ov.Offset = off;
3216                 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3217                         rc = -1;
3218         }
3219 #else
3220         rc = pwrite(mfd, ptr, len, off);
3221 #endif
3222         if (rc != len) {
3223                 rc = rc < 0 ? ErrCode() : EIO;
3224                 DPUTS("write failed, disk error?");
3225                 /* On a failure, the pagecache still contains the new data.
3226                  * Write some old data back, to prevent it from being used.
3227                  * Use the non-SYNC fd; we know it will fail anyway.
3228                  */
3229                 meta.mm_last_pg = metab.mm_last_pg;
3230                 meta.mm_txnid = metab.mm_txnid;
3231 #ifdef _WIN32
3232                 memset(&ov, 0, sizeof(ov));
3233                 ov.Offset = off;
3234                 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3235 #else
3236                 r2 = pwrite(env->me_fd, ptr, len, off);
3237                 (void)r2;       /* Silence warnings. We don't care about pwrite's return value */
3238 #endif
3239 fail:
3240                 env->me_flags |= MDB_FATAL_ERROR;
3241                 return rc;
3242         }
3243 done:
3244         /* Memory ordering issues are irrelevant; since the entire writer
3245          * is wrapped by wmutex, all of these changes will become visible
3246          * after the wmutex is unlocked. Since the DB is multi-version,
3247          * readers will get consistent data regardless of how fresh or
3248          * how stale their view of these values is.
3249          */
3250         if (env->me_txns)
3251                 env->me_txns->mti_txnid = txn->mt_txnid;
3252
3253         return MDB_SUCCESS;
3254 }
3255
3256 /** Check both meta pages to see which one is newer.
3257  * @param[in] env the environment handle
3258  * @return meta toggle (0 or 1).
3259  */
3260 static int
3261 mdb_env_pick_meta(const MDB_env *env)
3262 {
3263         return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3264 }
3265
3266 int
3267 mdb_env_create(MDB_env **env)
3268 {
3269         MDB_env *e;
3270
3271         e = calloc(1, sizeof(MDB_env));
3272         if (!e)
3273                 return ENOMEM;
3274
3275         e->me_maxreaders = DEFAULT_READERS;
3276         e->me_maxdbs = e->me_numdbs = 2;
3277         e->me_fd = INVALID_HANDLE_VALUE;
3278         e->me_lfd = INVALID_HANDLE_VALUE;
3279         e->me_mfd = INVALID_HANDLE_VALUE;
3280 #ifdef MDB_USE_POSIX_SEM
3281         e->me_rmutex = SEM_FAILED;
3282         e->me_wmutex = SEM_FAILED;
3283 #endif
3284         e->me_pid = getpid();
3285         GET_PAGESIZE(e->me_os_psize);
3286         VGMEMP_CREATE(e,0,0);
3287         *env = e;
3288         return MDB_SUCCESS;
3289 }
3290
3291 static int
3292 mdb_env_map(MDB_env *env, void *addr, int newsize)
3293 {
3294         MDB_page *p;
3295         unsigned int flags = env->me_flags;
3296 #ifdef _WIN32
3297         int rc;
3298         HANDLE mh;
3299         LONG sizelo, sizehi;
3300         sizelo = env->me_mapsize & 0xffffffff;
3301         sizehi = env->me_mapsize >> 16 >> 16; /* only needed on Win64 */
3302
3303         /* Windows won't create mappings for zero length files.
3304          * Just allocate the maxsize right now.
3305          */
3306         if (newsize) {
3307                 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3308                         || !SetEndOfFile(env->me_fd)
3309                         || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3310                         return ErrCode();
3311         }
3312         mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3313                 PAGE_READWRITE : PAGE_READONLY,
3314                 sizehi, sizelo, NULL);
3315         if (!mh)
3316                 return ErrCode();
3317         env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3318                 FILE_MAP_WRITE : FILE_MAP_READ,
3319                 0, 0, env->me_mapsize, addr);
3320         rc = env->me_map ? 0 : ErrCode();
3321         CloseHandle(mh);
3322         if (rc)
3323                 return rc;
3324 #else
3325         int prot = PROT_READ;
3326         if (flags & MDB_WRITEMAP) {
3327                 prot |= PROT_WRITE;
3328                 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3329                         return ErrCode();
3330         }
3331         env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3332                 env->me_fd, 0);
3333         if (env->me_map == MAP_FAILED) {
3334                 env->me_map = NULL;
3335                 return ErrCode();
3336         }
3337
3338         if (flags & MDB_NORDAHEAD) {
3339                 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3340 #ifdef MADV_RANDOM
3341                 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3342 #else
3343 #ifdef POSIX_MADV_RANDOM
3344                 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3345 #endif /* POSIX_MADV_RANDOM */
3346 #endif /* MADV_RANDOM */
3347         }
3348 #endif /* _WIN32 */
3349
3350         /* Can happen because the address argument to mmap() is just a
3351          * hint.  mmap() can pick another, e.g. if the range is in use.
3352          * The MAP_FIXED flag would prevent that, but then mmap could
3353          * instead unmap existing pages to make room for the new map.
3354          */
3355         if (addr && env->me_map != addr)
3356                 return EBUSY;   /* TODO: Make a new MDB_* error code? */
3357
3358         p = (MDB_page *)env->me_map;
3359         env->me_metas[0] = METADATA(p);
3360         env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3361
3362         return MDB_SUCCESS;
3363 }
3364
3365 int
3366 mdb_env_set_mapsize(MDB_env *env, size_t size)
3367 {
3368         /* If env is already open, caller is responsible for making
3369          * sure there are no active txns.
3370          */
3371         if (env->me_map) {
3372                 int rc;
3373                 void *old;
3374                 if (env->me_txn)
3375                         return EINVAL;
3376                 if (!size)
3377                         size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3378                 else if (size < env->me_mapsize) {
3379                         /* If the configured size is smaller, make sure it's
3380                          * still big enough. Silently round up to minimum if not.
3381                          */
3382                         size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3383                         if (size < minsize)
3384                                 size = minsize;
3385                 }
3386                 munmap(env->me_map, env->me_mapsize);
3387                 env->me_mapsize = size;
3388                 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3389                 rc = mdb_env_map(env, old, 1);
3390                 if (rc)
3391                         return rc;
3392         }
3393         env->me_mapsize = size;
3394         if (env->me_psize)
3395                 env->me_maxpg = env->me_mapsize / env->me_psize;
3396         return MDB_SUCCESS;
3397 }
3398
3399 int
3400 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3401 {
3402         if (env->me_map)
3403                 return EINVAL;
3404         env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3405         return MDB_SUCCESS;
3406 }
3407
3408 int
3409 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3410 {
3411         if (env->me_map || readers < 1)
3412                 return EINVAL;
3413         env->me_maxreaders = readers;
3414         return MDB_SUCCESS;
3415 }
3416
3417 int
3418 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3419 {
3420         if (!env || !readers)
3421                 return EINVAL;
3422         *readers = env->me_maxreaders;
3423         return MDB_SUCCESS;
3424 }
3425
3426 /** Further setup required for opening an MDB environment
3427  */
3428 static int
3429 mdb_env_open2(MDB_env *env)
3430 {
3431         unsigned int flags = env->me_flags;
3432         int i, newenv = 0, rc;
3433         MDB_meta meta;
3434
3435 #ifdef _WIN32
3436         /* See if we should use QueryLimited */
3437         rc = GetVersion();
3438         if ((rc & 0xff) > 5)
3439                 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3440         else
3441                 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3442 #endif /* _WIN32 */
3443
3444         memset(&meta, 0, sizeof(meta));
3445
3446         if ((i = mdb_env_read_header(env, &meta)) != 0) {
3447                 if (i != ENOENT)
3448                         return i;
3449                 DPUTS("new mdbenv");
3450                 newenv = 1;
3451                 env->me_psize = env->me_os_psize;
3452                 if (env->me_psize > MAX_PAGESIZE)
3453                         env->me_psize = MAX_PAGESIZE;
3454         } else {
3455                 env->me_psize = meta.mm_psize;
3456         }
3457
3458         /* Was a mapsize configured? */
3459         if (!env->me_mapsize) {
3460                 /* If this is a new environment, take the default,
3461                  * else use the size recorded in the existing env.
3462                  */
3463                 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3464         } else if (env->me_mapsize < meta.mm_mapsize) {
3465                 /* If the configured size is smaller, make sure it's
3466                  * still big enough. Silently round up to minimum if not.
3467                  */
3468                 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3469                 if (env->me_mapsize < minsize)
3470                         env->me_mapsize = minsize;
3471         }
3472
3473         rc = mdb_env_map(env, meta.mm_address, newenv);
3474         if (rc)
3475                 return rc;
3476
3477         if (newenv) {
3478                 if (flags & MDB_FIXEDMAP)
3479                         meta.mm_address = env->me_map;
3480                 i = mdb_env_init_meta(env, &meta);
3481                 if (i != MDB_SUCCESS) {
3482                         return i;
3483                 }
3484         }
3485         env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3486         env->me_nodemax = (env->me_psize - PAGEHDRSZ) / MDB_MINKEYS;
3487
3488         env->me_maxpg = env->me_mapsize / env->me_psize;
3489 #if MDB_DEBUG
3490         {
3491                 int toggle = mdb_env_pick_meta(env);
3492                 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3493
3494                 DPRINTF(("opened database version %u, pagesize %u",
3495                         env->me_metas[0]->mm_version, env->me_psize));
3496                 DPRINTF(("using meta page %d",    toggle));
3497                 DPRINTF(("depth: %u",             db->md_depth));
3498                 DPRINTF(("entries: %"Z"u",        db->md_entries));
3499                 DPRINTF(("branch pages: %"Z"u",   db->md_branch_pages));
3500                 DPRINTF(("leaf pages: %"Z"u",     db->md_leaf_pages));
3501                 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3502                 DPRINTF(("root: %"Z"u",           db->md_root));
3503         }
3504 #endif
3505
3506         return MDB_SUCCESS;
3507 }
3508
3509
3510 /** Release a reader thread's slot in the reader lock table.
3511  *      This function is called automatically when a thread exits.
3512  * @param[in] ptr This points to the slot in the reader lock table.
3513  */
3514 static void
3515 mdb_env_reader_dest(void *ptr)
3516 {
3517         MDB_reader *reader = ptr;
3518
3519         reader->mr_pid = 0;
3520 }
3521
3522 #ifdef _WIN32
3523 /** Junk for arranging thread-specific callbacks on Windows. This is
3524  *      necessarily platform and compiler-specific. Windows supports up
3525  *      to 1088 keys. Let's assume nobody opens more than 64 environments
3526  *      in a single process, for now. They can override this if needed.
3527  */
3528 #ifndef MAX_TLS_KEYS
3529 #define MAX_TLS_KEYS    64
3530 #endif
3531 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3532 static int mdb_tls_nkeys;
3533
3534 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3535 {
3536         int i;
3537         switch(reason) {
3538         case DLL_PROCESS_ATTACH: break;
3539         case DLL_THREAD_ATTACH: break;
3540         case DLL_THREAD_DETACH:
3541                 for (i=0; i<mdb_tls_nkeys; i++) {
3542                         MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3543                         mdb_env_reader_dest(r);
3544                 }
3545                 break;
3546         case DLL_PROCESS_DETACH: break;
3547         }
3548 }
3549 #ifdef __GNUC__
3550 #ifdef _WIN64
3551 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3552 #else
3553 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3554 #endif
3555 #else
3556 #ifdef _WIN64
3557 /* Force some symbol references.
3558  *      _tls_used forces the linker to create the TLS directory if not already done
3559  *      mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3560  */
3561 #pragma comment(linker, "/INCLUDE:_tls_used")
3562 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3563 #pragma const_seg(".CRT$XLB")
3564 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
3565 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3566 #pragma const_seg()
3567 #else   /* WIN32 */
3568 #pragma comment(linker, "/INCLUDE:__tls_used")
3569 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3570 #pragma data_seg(".CRT$XLB")
3571 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3572 #pragma data_seg()
3573 #endif  /* WIN 32/64 */
3574 #endif  /* !__GNUC__ */
3575 #endif
3576
3577 /** Downgrade the exclusive lock on the region back to shared */
3578 static int
3579 mdb_env_share_locks(MDB_env *env, int *excl)
3580 {
3581         int rc = 0, toggle = mdb_env_pick_meta(env);
3582
3583         env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3584
3585 #ifdef _WIN32
3586         {
3587                 OVERLAPPED ov;
3588                 /* First acquire a shared lock. The Unlock will
3589                  * then release the existing exclusive lock.
3590                  */
3591                 memset(&ov, 0, sizeof(ov));
3592                 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3593                         rc = ErrCode();
3594                 } else {
3595                         UnlockFile(env->me_lfd, 0, 0, 1, 0);
3596                         *excl = 0;
3597                 }
3598         }
3599 #else
3600         {
3601                 struct flock lock_info;
3602                 /* The shared lock replaces the existing lock */
3603                 memset((void *)&lock_info, 0, sizeof(lock_info));
3604                 lock_info.l_type = F_RDLCK;
3605                 lock_info.l_whence = SEEK_SET;
3606                 lock_info.l_start = 0;
3607                 lock_info.l_len = 1;
3608                 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3609                                 (rc = ErrCode()) == EINTR) ;
3610                 *excl = rc ? -1 : 0;    /* error may mean we lost the lock */
3611         }
3612 #endif
3613
3614         return rc;
3615 }
3616
3617 /** Try to get exlusive lock, otherwise shared.
3618  *      Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3619  */
3620 static int
3621 mdb_env_excl_lock(MDB_env *env, int *excl)
3622 {
3623         int rc = 0;
3624 #ifdef _WIN32
3625         if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3626                 *excl = 1;
3627         } else {
3628                 OVERLAPPED ov;
3629                 memset(&ov, 0, sizeof(ov));
3630                 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3631                         *excl = 0;
3632                 } else {
3633                         rc = ErrCode();
3634                 }
3635         }
3636 #else
3637         struct flock lock_info;
3638         memset((void *)&lock_info, 0, sizeof(lock_info));
3639         lock_info.l_type = F_WRLCK;
3640         lock_info.l_whence = SEEK_SET;
3641         lock_info.l_start = 0;
3642         lock_info.l_len = 1;
3643         while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3644                         (rc = ErrCode()) == EINTR) ;
3645         if (!rc) {
3646                 *excl = 1;
3647         } else
3648 # ifdef MDB_USE_POSIX_SEM
3649         if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3650 # endif
3651         {
3652                 lock_info.l_type = F_RDLCK;
3653                 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3654                                 (rc = ErrCode()) == EINTR) ;
3655                 if (rc == 0)
3656                         *excl = 0;
3657         }
3658 #endif
3659         return rc;
3660 }
3661
3662 #ifdef MDB_USE_HASH
3663 /*
3664  * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3665  *
3666  * @(#) $Revision: 5.1 $
3667  * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3668  * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3669  *
3670  *        http://www.isthe.com/chongo/tech/comp/fnv/index.html
3671  *
3672  ***
3673  *
3674  * Please do not copyright this code.  This code is in the public domain.
3675  *
3676  * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3677  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3678  * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3679  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3680  * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3681  * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3682  * PERFORMANCE OF THIS SOFTWARE.
3683  *
3684  * By:
3685  *      chongo <Landon Curt Noll> /\oo/\
3686  *        http://www.isthe.com/chongo/
3687  *
3688  * Share and Enjoy!     :-)
3689  */
3690
3691 typedef unsigned long long      mdb_hash_t;
3692 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3693
3694 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3695  * @param[in] val       value to hash
3696  * @param[in] hval      initial value for hash
3697  * @return 64 bit hash
3698  *
3699  * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3700  *       hval arg on the first call.
3701  */
3702 static mdb_hash_t
3703 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3704 {
3705         unsigned char *s = (unsigned char *)val->mv_data;       /* unsigned string */
3706         unsigned char *end = s + val->mv_size;
3707         /*
3708          * FNV-1a hash each octet of the string
3709          */
3710         while (s < end) {
3711                 /* xor the bottom with the current octet */
3712                 hval ^= (mdb_hash_t)*s++;
3713
3714                 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3715                 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3716                         (hval << 7) + (hval << 8) + (hval << 40);
3717         }
3718         /* return our new hash value */
3719         return hval;
3720 }
3721
3722 /** Hash the string and output the encoded hash.
3723  * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
3724  * very short name limits. We don't care about the encoding being reversible,
3725  * we just want to preserve as many bits of the input as possible in a
3726  * small printable string.
3727  * @param[in] str string to hash
3728  * @param[out] encbuf an array of 11 chars to hold the hash
3729  */
3730 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
3731
3732 static void
3733 mdb_pack85(unsigned long l, char *out)
3734 {
3735         int i;
3736
3737         for (i=0; i<5; i++) {
3738                 *out++ = mdb_a85[l % 85];
3739                 l /= 85;
3740         }
3741 }
3742
3743 static void
3744 mdb_hash_enc(MDB_val *val, char *encbuf)
3745 {
3746         mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3747
3748         mdb_pack85(h, encbuf);
3749         mdb_pack85(h>>32, encbuf+5);
3750         encbuf[10] = '\0';
3751 }
3752 #endif
3753
3754 /** Open and/or initialize the lock region for the environment.
3755  * @param[in] env The MDB environment.
3756  * @param[in] lpath The pathname of the file used for the lock region.
3757  * @param[in] mode The Unix permissions for the file, if we create it.
3758  * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
3759  * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
3760  * @return 0 on success, non-zero on failure.
3761  */
3762 static int
3763 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
3764 {
3765 #ifdef _WIN32
3766 #       define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
3767 #else
3768 #       define MDB_ERRCODE_ROFS EROFS
3769 #ifdef O_CLOEXEC        /* Linux: Open file and set FD_CLOEXEC atomically */
3770 #       define MDB_CLOEXEC              O_CLOEXEC
3771 #else
3772         int fdflags;
3773 #       define MDB_CLOEXEC              0
3774 #endif
3775 #endif
3776         int rc;
3777         off_t size, rsize;
3778
3779 #ifdef _WIN32
3780         env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
3781                 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
3782                 FILE_ATTRIBUTE_NORMAL, NULL);
3783 #else
3784         env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
3785 #endif
3786         if (env->me_lfd == INVALID_HANDLE_VALUE) {
3787                 rc = ErrCode();
3788                 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
3789                         return MDB_SUCCESS;
3790                 }
3791                 goto fail_errno;
3792         }
3793 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
3794         /* Lose record locks when exec*() */
3795         if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
3796                         fcntl(env->me_lfd, F_SETFD, fdflags);
3797 #endif
3798
3799         if (!(env->me_flags & MDB_NOTLS)) {
3800                 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3801                 if (rc)
3802                         goto fail;
3803                 env->me_flags |= MDB_ENV_TXKEY;
3804 #ifdef _WIN32
3805                 /* Windows TLS callbacks need help finding their TLS info. */
3806                 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
3807                         rc = MDB_TLS_FULL;
3808                         goto fail;
3809                 }
3810                 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3811 #endif
3812         }
3813
3814         /* Try to get exclusive lock. If we succeed, then
3815          * nobody is using the lock region and we should initialize it.
3816          */
3817         if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3818
3819 #ifdef _WIN32
3820         size = GetFileSize(env->me_lfd, NULL);
3821 #else
3822         size = lseek(env->me_lfd, 0, SEEK_END);
3823         if (size == -1) goto fail_errno;
3824 #endif
3825         rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
3826         if (size < rsize && *excl > 0) {
3827 #ifdef _WIN32
3828                 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
3829                         || !SetEndOfFile(env->me_lfd))
3830                         goto fail_errno;
3831 #else
3832                 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
3833 #endif
3834         } else {
3835                 rsize = size;
3836                 size = rsize - sizeof(MDB_txninfo);
3837                 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
3838         }
3839         {
3840 #ifdef _WIN32
3841                 HANDLE mh;
3842                 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
3843                         0, 0, NULL);
3844                 if (!mh) goto fail_errno;
3845                 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
3846                 CloseHandle(mh);
3847                 if (!env->me_txns) goto fail_errno;
3848 #else
3849                 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
3850                         env->me_lfd, 0);
3851                 if (m == MAP_FAILED) goto fail_errno;
3852                 env->me_txns = m;
3853 #endif
3854         }
3855         if (*excl > 0) {
3856 #ifdef _WIN32
3857                 BY_HANDLE_FILE_INFORMATION stbuf;
3858                 struct {
3859                         DWORD volume;
3860                         DWORD nhigh;
3861                         DWORD nlow;
3862                 } idbuf;
3863                 MDB_val val;
3864                 char encbuf[11];
3865
3866                 if (!mdb_sec_inited) {
3867                         InitializeSecurityDescriptor(&mdb_null_sd,
3868                                 SECURITY_DESCRIPTOR_REVISION);
3869                         SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
3870                         mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
3871                         mdb_all_sa.bInheritHandle = FALSE;
3872                         mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
3873                         mdb_sec_inited = 1;
3874                 }
3875                 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
3876                 idbuf.volume = stbuf.dwVolumeSerialNumber;
3877                 idbuf.nhigh  = stbuf.nFileIndexHigh;
3878                 idbuf.nlow   = stbuf.nFileIndexLow;
3879                 val.mv_data = &idbuf;
3880                 val.mv_size = sizeof(idbuf);
3881                 mdb_hash_enc(&val, encbuf);
3882                 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
3883                 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
3884                 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3885                 if (!env->me_rmutex) goto fail_errno;
3886                 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3887                 if (!env->me_wmutex) goto fail_errno;
3888 #elif defined(MDB_USE_POSIX_SEM)
3889                 struct stat stbuf;
3890                 struct {
3891                         dev_t dev;
3892                         ino_t ino;
3893                 } idbuf;
3894                 MDB_val val;
3895                 char encbuf[11];
3896
3897 #if defined(__NetBSD__)
3898 #define MDB_SHORT_SEMNAMES      1       /* limited to 14 chars */
3899 #endif
3900                 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3901                 idbuf.dev = stbuf.st_dev;
3902                 idbuf.ino = stbuf.st_ino;
3903                 val.mv_data = &idbuf;
3904                 val.mv_size = sizeof(idbuf);
3905                 mdb_hash_enc(&val, encbuf);
3906 #ifdef MDB_SHORT_SEMNAMES
3907                 encbuf[9] = '\0';       /* drop name from 15 chars to 14 chars */
3908 #endif
3909                 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
3910                 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
3911                 /* Clean up after a previous run, if needed:  Try to
3912                  * remove both semaphores before doing anything else.
3913                  */
3914                 sem_unlink(env->me_txns->mti_rmname);
3915                 sem_unlink(env->me_txns->mti_wmname);
3916                 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3917                         O_CREAT|O_EXCL, mode, 1);
3918                 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3919                 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3920                         O_CREAT|O_EXCL, mode, 1);
3921                 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3922 #else   /* MDB_USE_POSIX_SEM */
3923                 pthread_mutexattr_t mattr;
3924
3925                 if ((rc = pthread_mutexattr_init(&mattr))
3926                         || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3927                         || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3928                         || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3929                         goto fail;
3930                 pthread_mutexattr_destroy(&mattr);
3931 #endif  /* _WIN32 || MDB_USE_POSIX_SEM */
3932
3933                 env->me_txns->mti_magic = MDB_MAGIC;
3934                 env->me_txns->mti_format = MDB_LOCK_FORMAT;
3935                 env->me_txns->mti_txnid = 0;
3936                 env->me_txns->mti_numreaders = 0;
3937
3938         } else {
3939                 if (env->me_txns->mti_magic != MDB_MAGIC) {
3940                         DPUTS("lock region has invalid magic");
3941                         rc = MDB_INVALID;
3942                         goto fail;
3943                 }
3944                 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
3945                         DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
3946                                 env->me_txns->mti_format, MDB_LOCK_FORMAT));
3947                         rc = MDB_VERSION_MISMATCH;
3948                         goto fail;
3949                 }
3950                 rc = ErrCode();
3951                 if (rc && rc != EACCES && rc != EAGAIN) {
3952                         goto fail;
3953                 }
3954 #ifdef _WIN32
3955                 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
3956                 if (!env->me_rmutex) goto fail_errno;
3957                 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
3958                 if (!env->me_wmutex) goto fail_errno;
3959 #elif defined(MDB_USE_POSIX_SEM)
3960                 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
3961                 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3962                 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
3963                 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3964 #endif
3965         }
3966         return MDB_SUCCESS;
3967
3968 fail_errno:
3969         rc = ErrCode();
3970 fail:
3971         return rc;
3972 }
3973
3974         /** The name of the lock file in the DB environment */
3975 #define LOCKNAME        "/lock.mdb"
3976         /** The name of the data file in the DB environment */
3977 #define DATANAME        "/data.mdb"
3978         /** The suffix of the lock file when no subdir is used */
3979 #define LOCKSUFF        "-lock"
3980         /** Only a subset of the @ref mdb_env flags can be changed
3981          *      at runtime. Changing other flags requires closing the
3982          *      environment and re-opening it with the new flags.
3983          */
3984 #define CHANGEABLE      (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
3985 #define CHANGELESS      (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP| \
3986         MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
3987
3988 int
3989 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
3990 {
3991         int             oflags, rc, len, excl = -1;
3992         char *lpath, *dpath;
3993
3994         if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
3995                 return EINVAL;
3996
3997         len = strlen(path);
3998         if (flags & MDB_NOSUBDIR) {
3999                 rc = len + sizeof(LOCKSUFF) + len + 1;
4000         } else {
4001                 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4002         }
4003         lpath = malloc(rc);
4004         if (!lpath)
4005                 return ENOMEM;
4006         if (flags & MDB_NOSUBDIR) {
4007                 dpath = lpath + len + sizeof(LOCKSUFF);
4008                 sprintf(lpath, "%s" LOCKSUFF, path);
4009                 strcpy(dpath, path);
4010         } else {
4011                 dpath = lpath + len + sizeof(LOCKNAME);
4012                 sprintf(lpath, "%s" LOCKNAME, path);
4013                 sprintf(dpath, "%s" DATANAME, path);
4014         }
4015
4016         rc = MDB_SUCCESS;
4017         flags |= env->me_flags;
4018         if (flags & MDB_RDONLY) {
4019                 /* silently ignore WRITEMAP when we're only getting read access */
4020                 flags &= ~MDB_WRITEMAP;
4021         } else {
4022                 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4023                           (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4024                         rc = ENOMEM;
4025         }
4026         env->me_flags = flags |= MDB_ENV_ACTIVE;
4027         if (rc)
4028                 goto leave;
4029
4030         env->me_path = strdup(path);
4031         env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4032         env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4033         if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
4034                 rc = ENOMEM;
4035                 goto leave;
4036         }
4037
4038         /* For RDONLY, get lockfile after we know datafile exists */
4039         if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4040                 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4041                 if (rc)
4042                         goto leave;
4043         }
4044
4045 #ifdef _WIN32
4046         if (F_ISSET(flags, MDB_RDONLY)) {
4047                 oflags = GENERIC_READ;
4048                 len = OPEN_EXISTING;
4049         } else {
4050                 oflags = GENERIC_READ|GENERIC_WRITE;
4051                 len = OPEN_ALWAYS;
4052         }
4053         mode = FILE_ATTRIBUTE_NORMAL;
4054         env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4055                 NULL, len, mode, NULL);
4056 #else
4057         if (F_ISSET(flags, MDB_RDONLY))
4058                 oflags = O_RDONLY;
4059         else
4060                 oflags = O_RDWR | O_CREAT;
4061
4062         env->me_fd = open(dpath, oflags, mode);
4063 #endif
4064         if (env->me_fd == INVALID_HANDLE_VALUE) {
4065                 rc = ErrCode();
4066                 goto leave;
4067         }
4068
4069         if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4070                 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4071                 if (rc)
4072                         goto leave;
4073         }
4074
4075         if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4076                 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4077                         env->me_mfd = env->me_fd;
4078                 } else {
4079                         /* Synchronous fd for meta writes. Needed even with
4080                          * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4081                          */
4082 #ifdef _WIN32
4083                         len = OPEN_EXISTING;
4084                         env->me_mfd = CreateFile(dpath, oflags,
4085                                 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4086                                 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4087 #else
4088                         oflags &= ~O_CREAT;
4089                         env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4090 #endif
4091                         if (env->me_mfd == INVALID_HANDLE_VALUE) {
4092                                 rc = ErrCode();
4093                                 goto leave;
4094                         }
4095                 }
4096                 DPRINTF(("opened dbenv %p", (void *) env));
4097                 if (excl > 0) {
4098                         rc = mdb_env_share_locks(env, &excl);
4099                         if (rc)
4100                                 goto leave;
4101                 }
4102                 if (!((flags & MDB_RDONLY) ||
4103                           (env->me_pbuf = calloc(1, env->me_psize))))
4104                         rc = ENOMEM;
4105         }
4106
4107 leave:
4108         if (rc) {
4109                 mdb_env_close0(env, excl);
4110         }
4111         free(lpath);
4112         return rc;
4113 }
4114
4115 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4116 static void
4117 mdb_env_close0(MDB_env *env, int excl)
4118 {
4119         int i;
4120
4121         if (!(env->me_flags & MDB_ENV_ACTIVE))
4122                 return;
4123
4124         /* Doing this here since me_dbxs may not exist during mdb_env_close */
4125         for (i = env->me_maxdbs; --i > MAIN_DBI; )
4126                 free(env->me_dbxs[i].md_name.mv_data);
4127
4128         free(env->me_pbuf);
4129         free(env->me_dbflags);
4130         free(env->me_dbxs);
4131         free(env->me_path);
4132         free(env->me_dirty_list);
4133         mdb_midl_free(env->me_free_pgs);
4134
4135         if (env->me_flags & MDB_ENV_TXKEY) {
4136                 pthread_key_delete(env->me_txkey);
4137 #ifdef _WIN32
4138                 /* Delete our key from the global list */
4139                 for (i=0; i<mdb_tls_nkeys; i++)
4140                         if (mdb_tls_keys[i] == env->me_txkey) {
4141                                 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4142                                 mdb_tls_nkeys--;
4143                                 break;
4144                         }
4145 #endif
4146         }
4147
4148         if (env->me_map) {
4149                 munmap(env->me_map, env->me_mapsize);
4150         }
4151         if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4152                 (void) close(env->me_mfd);
4153         if (env->me_fd != INVALID_HANDLE_VALUE)
4154                 (void) close(env->me_fd);
4155         if (env->me_txns) {
4156                 MDB_PID_T pid = env->me_pid;
4157                 /* Clearing readers is done in this function because
4158                  * me_txkey with its destructor must be disabled first.
4159                  */
4160                 for (i = env->me_numreaders; --i >= 0; )
4161                         if (env->me_txns->mti_readers[i].mr_pid == pid)
4162                                 env->me_txns->mti_readers[i].mr_pid = 0;
4163 #ifdef _WIN32
4164                 if (env->me_rmutex) {
4165                         CloseHandle(env->me_rmutex);
4166                         if (env->me_wmutex) CloseHandle(env->me_wmutex);
4167                 }
4168                 /* Windows automatically destroys the mutexes when
4169                  * the last handle closes.
4170                  */
4171 #elif defined(MDB_USE_POSIX_SEM)
4172                 if (env->me_rmutex != SEM_FAILED) {
4173                         sem_close(env->me_rmutex);
4174                         if (env->me_wmutex != SEM_FAILED)
4175                                 sem_close(env->me_wmutex);
4176                         /* If we have the filelock:  If we are the
4177                          * only remaining user, clean up semaphores.
4178                          */
4179                         if (excl == 0)
4180                                 mdb_env_excl_lock(env, &excl);
4181                         if (excl > 0) {
4182                                 sem_unlink(env->me_txns->mti_rmname);
4183                                 sem_unlink(env->me_txns->mti_wmname);
4184                         }
4185                 }
4186 #endif
4187                 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4188         }
4189         if (env->me_lfd != INVALID_HANDLE_VALUE) {
4190 #ifdef _WIN32
4191                 if (excl >= 0) {
4192                         /* Unlock the lockfile.  Windows would have unlocked it
4193                          * after closing anyway, but not necessarily at once.
4194                          */
4195                         UnlockFile(env->me_lfd, 0, 0, 1, 0);
4196                 }
4197 #endif
4198                 (void) close(env->me_lfd);
4199         }
4200
4201         env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4202 }
4203
4204 int
4205 mdb_env_copyfd(MDB_env *env, HANDLE fd)
4206 {
4207         MDB_txn *txn = NULL;
4208         int rc;
4209         size_t wsize;
4210         char *ptr;
4211 #ifdef _WIN32
4212         DWORD len, w2;
4213 #define DO_WRITE(rc, fd, ptr, w2, len)  rc = WriteFile(fd, ptr, w2, &len, NULL)
4214 #else
4215         ssize_t len;
4216         size_t w2;
4217 #define DO_WRITE(rc, fd, ptr, w2, len)  len = write(fd, ptr, w2); rc = (len >= 0)
4218 #endif
4219
4220         /* Do the lock/unlock of the reader mutex before starting the
4221          * write txn.  Otherwise other read txns could block writers.
4222          */
4223         rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
4224         if (rc)
4225                 return rc;
4226
4227         if (env->me_txns) {
4228                 /* We must start the actual read txn after blocking writers */
4229                 mdb_txn_reset0(txn, "reset-stage1");
4230
4231                 /* Temporarily block writers until we snapshot the meta pages */
4232                 LOCK_MUTEX_W(env);
4233
4234                 rc = mdb_txn_renew0(txn);
4235                 if (rc) {
4236                         UNLOCK_MUTEX_W(env);
4237                         goto leave;
4238                 }
4239         }
4240
4241         wsize = env->me_psize * 2;
4242         ptr = env->me_map;
4243         w2 = wsize;
4244         while (w2 > 0) {
4245                 DO_WRITE(rc, fd, ptr, w2, len);
4246                 if (!rc) {
4247                         rc = ErrCode();
4248                         break;
4249                 } else if (len > 0) {
4250                         rc = MDB_SUCCESS;
4251                         ptr += len;
4252                         w2 -= len;
4253                         continue;
4254                 } else {
4255                         /* Non-blocking or async handles are not supported */
4256                         rc = EIO;
4257                         break;
4258                 }
4259         }
4260         if (env->me_txns)
4261                 UNLOCK_MUTEX_W(env);
4262
4263         if (rc)
4264                 goto leave;
4265
4266         wsize = txn->mt_next_pgno * env->me_psize - wsize;
4267         while (wsize > 0) {
4268                 if (wsize > MAX_WRITE)
4269                         w2 = MAX_WRITE;
4270                 else
4271                         w2 = wsize;
4272                 DO_WRITE(rc, fd, ptr, w2, len);
4273                 if (!rc) {
4274                         rc = ErrCode();
4275                         break;
4276                 } else if (len > 0) {
4277                         rc = MDB_SUCCESS;
4278                         ptr += len;
4279                         wsize -= len;
4280                         continue;
4281                 } else {
4282                         rc = EIO;
4283                         break;
4284                 }
4285         }
4286
4287 leave:
4288         mdb_txn_abort(txn);
4289         return rc;
4290 }
4291
4292 int
4293 mdb_env_copy(MDB_env *env, const char *path)
4294 {
4295         int rc, len;
4296         char *lpath;
4297         HANDLE newfd = INVALID_HANDLE_VALUE;
4298
4299         if (env->me_flags & MDB_NOSUBDIR) {
4300                 lpath = (char *)path;
4301         } else {
4302                 len = strlen(path);
4303                 len += sizeof(DATANAME);
4304                 lpath = malloc(len);
4305                 if (!lpath)
4306                         return ENOMEM;
4307                 sprintf(lpath, "%s" DATANAME, path);
4308         }
4309
4310         /* The destination path must exist, but the destination file must not.
4311          * We don't want the OS to cache the writes, since the source data is
4312          * already in the OS cache.
4313          */
4314 #ifdef _WIN32
4315         newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4316                                 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
4317 #else
4318         newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
4319 #endif
4320         if (newfd == INVALID_HANDLE_VALUE) {
4321                 rc = ErrCode();
4322                 goto leave;
4323         }
4324
4325 #ifdef O_DIRECT
4326         /* Set O_DIRECT if the file system supports it */
4327         if ((rc = fcntl(newfd, F_GETFL)) != -1)
4328                 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
4329 #endif
4330 #ifdef F_NOCACHE        /* __APPLE__ */
4331         rc = fcntl(newfd, F_NOCACHE, 1);
4332         if (rc) {
4333                 rc = ErrCode();
4334                 goto leave;
4335         }
4336 #endif
4337
4338         rc = mdb_env_copyfd(env, newfd);
4339
4340 leave:
4341         if (!(env->me_flags & MDB_NOSUBDIR))
4342                 free(lpath);
4343         if (newfd != INVALID_HANDLE_VALUE)
4344                 if (close(newfd) < 0 && rc == MDB_SUCCESS)
4345                         rc = ErrCode();
4346
4347         return rc;
4348 }
4349
4350 void
4351 mdb_env_close(MDB_env *env)
4352 {
4353         MDB_page *dp;
4354
4355         if (env == NULL)
4356                 return;
4357
4358         VGMEMP_DESTROY(env);
4359         while ((dp = env->me_dpages) != NULL) {
4360                 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4361                 env->me_dpages = dp->mp_next;
4362                 free(dp);
4363         }
4364
4365         mdb_env_close0(env, 0);
4366         free(env);
4367 }
4368
4369 /** Compare two items pointing at aligned size_t's */
4370 static int
4371 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4372 {
4373         return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4374                 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4375 }
4376
4377 /** Compare two items pointing at aligned unsigned int's */
4378 static int
4379 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4380 {
4381         return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4382                 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4383 }
4384
4385 /** Compare two items pointing at unsigned ints of unknown alignment.
4386  *      Nodes and keys are guaranteed to be 2-byte aligned.
4387  */
4388 static int
4389 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4390 {
4391 #if BYTE_ORDER == LITTLE_ENDIAN
4392         unsigned short *u, *c;
4393         int x;
4394
4395         u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4396         c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4397         do {
4398                 x = *--u - *--c;
4399         } while(!x && u > (unsigned short *)a->mv_data);
4400         return x;
4401 #else
4402         return memcmp(a->mv_data, b->mv_data, a->mv_size);
4403 #endif
4404 }
4405
4406 /** Compare two items lexically */
4407 static int
4408 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4409 {
4410         int diff;
4411         ssize_t len_diff;
4412         unsigned int len;
4413
4414         len = a->mv_size;
4415         len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4416         if (len_diff > 0) {
4417                 len = b->mv_size;
4418                 len_diff = 1;
4419         }
4420
4421         diff = memcmp(a->mv_data, b->mv_data, len);
4422         return diff ? diff : len_diff<0 ? -1 : len_diff;
4423 }
4424
4425 /** Compare two items in reverse byte order */
4426 static int
4427 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4428 {
4429         const unsigned char     *p1, *p2, *p1_lim;
4430         ssize_t len_diff;
4431         int diff;
4432
4433         p1_lim = (const unsigned char *)a->mv_data;
4434         p1 = (const unsigned char *)a->mv_data + a->mv_size;
4435         p2 = (const unsigned char *)b->mv_data + b->mv_size;
4436
4437         len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4438         if (len_diff > 0) {
4439                 p1_lim += len_diff;
4440                 len_diff = 1;
4441         }
4442
4443         while (p1 > p1_lim) {
4444                 diff = *--p1 - *--p2;
4445                 if (diff)
4446                         return diff;
4447         }
4448         return len_diff<0 ? -1 : len_diff;
4449 }
4450
4451 /** Search for key within a page, using binary search.
4452  * Returns the smallest entry larger or equal to the key.
4453  * If exactp is non-null, stores whether the found entry was an exact match
4454  * in *exactp (1 or 0).
4455  * Updates the cursor index with the index of the found entry.
4456  * If no entry larger or equal to the key is found, returns NULL.
4457  */
4458 static MDB_node *
4459 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4460 {
4461         unsigned int     i = 0, nkeys;
4462         int              low, high;
4463         int              rc = 0;
4464         MDB_page *mp = mc->mc_pg[mc->mc_top];
4465         MDB_node        *node = NULL;
4466         MDB_val  nodekey;
4467         MDB_cmp_func *cmp;
4468         DKBUF;
4469
4470         nkeys = NUMKEYS(mp);
4471
4472 #if MDB_DEBUG
4473         {
4474         pgno_t pgno;
4475         COPY_PGNO(pgno, mp->mp_pgno);
4476         DPRINTF(("searching %u keys in %s %spage %"Z"u",
4477             nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4478             pgno));
4479         }
4480 #endif
4481
4482         assert(nkeys > 0);
4483
4484         low = IS_LEAF(mp) ? 0 : 1;
4485         high = nkeys - 1;
4486         cmp = mc->mc_dbx->md_cmp;
4487
4488         /* Branch pages have no data, so if using integer keys,
4489          * alignment is guaranteed. Use faster mdb_cmp_int.
4490          */
4491         if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4492                 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4493                         cmp = mdb_cmp_long;
4494                 else
4495                         cmp = mdb_cmp_int;
4496         }
4497
4498         if (IS_LEAF2(mp)) {
4499                 nodekey.mv_size = mc->mc_db->md_pad;
4500                 node = NODEPTR(mp, 0);  /* fake */
4501                 while (low <= high) {
4502                         i = (low + high) >> 1;
4503                         nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4504                         rc = cmp(key, &nodekey);
4505                         DPRINTF(("found leaf index %u [%s], rc = %i",
4506                             i, DKEY(&nodekey), rc));
4507                         if (rc == 0)
4508                                 break;
4509                         if (rc > 0)
4510                                 low = i + 1;
4511                         else
4512                                 high = i - 1;
4513                 }
4514         } else {
4515                 while (low <= high) {
4516                         i = (low + high) >> 1;
4517
4518                         node = NODEPTR(mp, i);
4519                         nodekey.mv_size = NODEKSZ(node);
4520                         nodekey.mv_data = NODEKEY(node);
4521
4522                         rc = cmp(key, &nodekey);
4523 #if MDB_DEBUG
4524                         if (IS_LEAF(mp))
4525                                 DPRINTF(("found leaf index %u [%s], rc = %i",
4526                                     i, DKEY(&nodekey), rc));
4527                         else
4528                                 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4529                                     i, DKEY(&nodekey), NODEPGNO(node), rc));
4530 #endif
4531                         if (rc == 0)
4532                                 break;
4533                         if (rc > 0)
4534                                 low = i + 1;
4535                         else
4536                                 high = i - 1;
4537                 }
4538         }
4539
4540         if (rc > 0) {   /* Found entry is less than the key. */
4541                 i++;    /* Skip to get the smallest entry larger than key. */
4542                 if (!IS_LEAF2(mp))
4543                         node = NODEPTR(mp, i);
4544         }
4545         if (exactp)
4546                 *exactp = (rc == 0);
4547         /* store the key index */
4548         mc->mc_ki[mc->mc_top] = i;
4549         if (i >= nkeys)
4550                 /* There is no entry larger or equal to the key. */
4551                 return NULL;
4552
4553         /* nodeptr is fake for LEAF2 */
4554         return node;
4555 }
4556
4557 #if 0
4558 static void
4559 mdb_cursor_adjust(MDB_cursor *mc, func)
4560 {
4561         MDB_cursor *m2;
4562
4563         for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4564                 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4565                         func(mc, m2);
4566                 }
4567         }
4568 }
4569 #endif
4570
4571 /** Pop a page off the top of the cursor's stack. */
4572 static void
4573 mdb_cursor_pop(MDB_cursor *mc)
4574 {
4575         if (mc->mc_snum) {
4576 #if MDB_DEBUG
4577                 MDB_page        *top = mc->mc_pg[mc->mc_top];
4578 #endif
4579                 mc->mc_snum--;
4580                 if (mc->mc_snum)
4581                         mc->mc_top--;
4582
4583                 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4584                         DDBI(mc), (void *) mc));
4585         }
4586 }
4587
4588 /** Push a page onto the top of the cursor's stack. */
4589 static int
4590 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4591 {
4592         DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4593                 DDBI(mc), (void *) mc));
4594
4595         if (mc->mc_snum >= CURSOR_STACK) {
4596                 assert(mc->mc_snum < CURSOR_STACK);
4597                 return MDB_CURSOR_FULL;
4598         }
4599
4600         mc->mc_top = mc->mc_snum++;
4601         mc->mc_pg[mc->mc_top] = mp;
4602         mc->mc_ki[mc->mc_top] = 0;
4603
4604         return MDB_SUCCESS;
4605 }
4606
4607 /** Find the address of the page corresponding to a given page number.
4608  * @param[in] txn the transaction for this access.
4609  * @param[in] pgno the page number for the page to retrieve.
4610  * @param[out] ret address of a pointer where the page's address will be stored.
4611  * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4612  * @return 0 on success, non-zero on failure.
4613  */
4614 static int
4615 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4616 {
4617         MDB_env *env = txn->mt_env;
4618         MDB_page *p = NULL;
4619         int level;
4620
4621         if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
4622                 MDB_txn *tx2 = txn;
4623                 level = 1;
4624                 do {
4625                         MDB_ID2L dl = tx2->mt_u.dirty_list;
4626                         unsigned x;
4627                         /* Spilled pages were dirtied in this txn and flushed
4628                          * because the dirty list got full. Bring this page
4629                          * back in from the map (but don't unspill it here,
4630                          * leave that unless page_touch happens again).
4631                          */
4632                         if (tx2->mt_spill_pgs) {
4633                                 MDB_ID pn = pgno << 1;
4634                                 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
4635                                 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
4636                                         p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4637                                         goto done;
4638                                 }
4639                         }
4640                         if (dl[0].mid) {
4641                                 unsigned x = mdb_mid2l_search(dl, pgno);
4642                                 if (x <= dl[0].mid && dl[x].mid == pgno) {
4643                                         p = dl[x].mptr;
4644                                         goto done;
4645                                 }
4646                         }
4647                         level++;
4648                 } while ((tx2 = tx2->mt_parent) != NULL);
4649         }
4650
4651         if (pgno < txn->mt_next_pgno) {
4652                 level = 0;
4653                 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4654         } else {
4655                 DPRINTF(("page %"Z"u not found", pgno));
4656                 assert(p != NULL);
4657                 return MDB_PAGE_NOTFOUND;
4658         }
4659
4660 done:
4661         *ret = p;
4662         if (lvl)
4663                 *lvl = level;
4664         return MDB_SUCCESS;
4665 }
4666
4667 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
4668  *      The cursor is at the root page, set up the rest of it.
4669  */
4670 static int
4671 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
4672 {
4673         MDB_page        *mp = mc->mc_pg[mc->mc_top];
4674         int rc;
4675         DKBUF;
4676
4677         while (IS_BRANCH(mp)) {
4678                 MDB_node        *node;
4679                 indx_t          i;
4680
4681                 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
4682                 assert(NUMKEYS(mp) > 1);
4683                 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
4684
4685                 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
4686                         i = 0;
4687                         if (flags & MDB_PS_LAST)
4688                                 i = NUMKEYS(mp) - 1;
4689                 } else {
4690                         int      exact;
4691                         node = mdb_node_search(mc, key, &exact);
4692                         if (node == NULL)
4693                                 i = NUMKEYS(mp) - 1;
4694                         else {
4695                                 i = mc->mc_ki[mc->mc_top];
4696                                 if (!exact) {
4697                                         assert(i > 0);
4698                                         i--;
4699                                 }
4700                         }
4701                         DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
4702                 }
4703
4704                 assert(i < NUMKEYS(mp));
4705                 node = NODEPTR(mp, i);
4706
4707                 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4708                         return rc;
4709
4710                 mc->mc_ki[mc->mc_top] = i;
4711                 if ((rc = mdb_cursor_push(mc, mp)))
4712                         return rc;
4713
4714                 if (flags & MDB_PS_MODIFY) {
4715                         if ((rc = mdb_page_touch(mc)) != 0)
4716                                 return rc;
4717                         mp = mc->mc_pg[mc->mc_top];
4718                 }
4719         }
4720
4721         if (!IS_LEAF(mp)) {
4722                 DPRINTF(("internal error, index points to a %02X page!?",
4723                     mp->mp_flags));
4724                 return MDB_CORRUPTED;
4725         }
4726
4727         DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
4728             key ? DKEY(key) : "null"));
4729         mc->mc_flags |= C_INITIALIZED;
4730         mc->mc_flags &= ~C_EOF;
4731
4732         return MDB_SUCCESS;
4733 }
4734
4735 /** Search for the lowest key under the current branch page.
4736  * This just bypasses a NUMKEYS check in the current page
4737  * before calling mdb_page_search_root(), because the callers
4738  * are all in situations where the current page is known to
4739  * be underfilled.
4740  */
4741 static int
4742 mdb_page_search_lowest(MDB_cursor *mc)
4743 {
4744         MDB_page        *mp = mc->mc_pg[mc->mc_top];
4745         MDB_node        *node = NODEPTR(mp, 0);
4746         int rc;
4747
4748         if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4749                 return rc;
4750
4751         mc->mc_ki[mc->mc_top] = 0;
4752         if ((rc = mdb_cursor_push(mc, mp)))
4753                 return rc;
4754         return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
4755 }
4756
4757 /** Search for the page a given key should be in.
4758  * Push it and its parent pages on the cursor stack.
4759  * @param[in,out] mc the cursor for this operation.
4760  * @param[in] key the key to search for, or NULL for first/last page.
4761  * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
4762  *   are touched (updated with new page numbers).
4763  *   If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
4764  *   This is used by #mdb_cursor_first() and #mdb_cursor_last().
4765  *   If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4766  * @return 0 on success, non-zero on failure.
4767  */
4768 static int
4769 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4770 {
4771         int              rc;
4772         pgno_t           root;
4773
4774         /* Make sure the txn is still viable, then find the root from
4775          * the txn's db table and set it as the root of the cursor's stack.
4776          */
4777         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4778                 DPUTS("transaction has failed, must abort");
4779                 return MDB_BAD_TXN;
4780         } else {
4781                 /* Make sure we're using an up-to-date root */
4782                 if (*mc->mc_dbflag & DB_STALE) {
4783                                 MDB_cursor mc2;
4784                                 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4785                                 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
4786                                 if (rc)
4787                                         return rc;
4788                                 {
4789                                         MDB_val data;
4790                                         int exact = 0;
4791                                         uint16_t flags;
4792                                         MDB_node *leaf = mdb_node_search(&mc2,
4793                                                 &mc->mc_dbx->md_name, &exact);
4794                                         if (!exact)
4795                                                 return MDB_NOTFOUND;
4796                                         rc = mdb_node_read(mc->mc_txn, leaf, &data);
4797                                         if (rc)
4798                                                 return rc;
4799                                         memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4800                                                 sizeof(uint16_t));
4801                                         /* The txn may not know this DBI, or another process may
4802                                          * have dropped and recreated the DB with other flags.
4803                                          */
4804                                         if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4805                                                 return MDB_INCOMPATIBLE;
4806                                         memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4807                                 }
4808                                 *mc->mc_dbflag &= ~DB_STALE;
4809                 }
4810                 root = mc->mc_db->md_root;
4811
4812                 if (root == P_INVALID) {                /* Tree is empty. */
4813                         DPUTS("tree is empty");
4814                         return MDB_NOTFOUND;
4815                 }
4816         }
4817
4818         assert(root > 1);
4819         if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4820                 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
4821                         return rc;
4822
4823         mc->mc_snum = 1;
4824         mc->mc_top = 0;
4825
4826         DPRINTF(("db %d root page %"Z"u has flags 0x%X",
4827                 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
4828
4829         if (flags & MDB_PS_MODIFY) {
4830                 if ((rc = mdb_page_touch(mc)))
4831                         return rc;
4832         }
4833
4834         if (flags & MDB_PS_ROOTONLY)
4835                 return MDB_SUCCESS;
4836
4837         return mdb_page_search_root(mc, key, flags);
4838 }
4839
4840 static int
4841 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
4842 {
4843         MDB_txn *txn = mc->mc_txn;
4844         pgno_t pg = mp->mp_pgno;
4845         unsigned x = 0, ovpages = mp->mp_pages;
4846         MDB_env *env = txn->mt_env;
4847         MDB_IDL sl = txn->mt_spill_pgs;
4848         MDB_ID pn = pg << 1;
4849         int rc;
4850
4851         DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
4852         /* If the page is dirty or on the spill list we just acquired it,
4853          * so we should give it back to our current free list, if any.
4854          * Otherwise put it onto the list of pages we freed in this txn.
4855          *
4856          * Won't create me_pghead: me_pglast must be inited along with it.
4857          * Unsupported in nested txns: They would need to hide the page
4858          * range in ancestor txns' dirty and spilled lists.
4859          */
4860         if (env->me_pghead &&
4861                 !txn->mt_parent &&
4862                 ((mp->mp_flags & P_DIRTY) ||
4863                  (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
4864         {
4865                 unsigned i, j;
4866                 pgno_t *mop;
4867                 MDB_ID2 *dl, ix, iy;
4868                 rc = mdb_midl_need(&env->me_pghead, ovpages);
4869                 if (rc)
4870                         return rc;
4871                 if (!(mp->mp_flags & P_DIRTY)) {
4872                         /* This page is no longer spilled */
4873                         if (x == sl[0])
4874                                 sl[0]--;
4875                         else
4876                                 sl[x] |= 1;
4877                         goto release;
4878                 }
4879                 /* Remove from dirty list */
4880                 dl = txn->mt_u.dirty_list;
4881                 x = dl[0].mid--;
4882                 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
4883                         if (x > 1) {
4884                                 x--;
4885                                 iy = dl[x];
4886                                 dl[x] = ix;
4887                         } else {
4888                                 assert(x > 1);
4889                                 j = ++(dl[0].mid);
4890                                 dl[j] = ix;             /* Unsorted. OK when MDB_TXN_ERROR. */
4891                                 txn->mt_flags |= MDB_TXN_ERROR;
4892                                 return MDB_CORRUPTED;
4893                         }
4894                 }
4895                 if (!(env->me_flags & MDB_WRITEMAP))
4896                         mdb_dpage_free(env, mp);
4897 release:
4898                 /* Insert in me_pghead */
4899                 mop = env->me_pghead;
4900                 j = mop[0] + ovpages;
4901                 for (i = mop[0]; i && mop[i] < pg; i--)
4902                         mop[j--] = mop[i];
4903                 while (j>i)
4904                         mop[j--] = pg++;
4905                 mop[0] += ovpages;
4906         } else {
4907                 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
4908                 if (rc)
4909                         return rc;
4910         }
4911         mc->mc_db->md_overflow_pages -= ovpages;
4912         return 0;
4913 }
4914
4915 /** Return the data associated with a given node.
4916  * @param[in] txn The transaction for this operation.
4917  * @param[in] leaf The node being read.
4918  * @param[out] data Updated to point to the node's data.
4919  * @return 0 on success, non-zero on failure.
4920  */
4921 static int
4922 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
4923 {
4924         MDB_page        *omp;           /* overflow page */
4925         pgno_t           pgno;
4926         int rc;
4927
4928         if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4929                 data->mv_size = NODEDSZ(leaf);
4930                 data->mv_data = NODEDATA(leaf);
4931                 return MDB_SUCCESS;
4932         }
4933
4934         /* Read overflow data.
4935          */
4936         data->mv_size = NODEDSZ(leaf);
4937         memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
4938         if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
4939                 DPRINTF(("read overflow page %"Z"u failed", pgno));
4940                 return rc;
4941         }
4942         data->mv_data = METADATA(omp);
4943
4944         return MDB_SUCCESS;
4945 }
4946
4947 int
4948 mdb_get(MDB_txn *txn, MDB_dbi dbi,
4949     MDB_val *key, MDB_val *data)
4950 {
4951         MDB_cursor      mc;
4952         MDB_xcursor     mx;
4953         int exact = 0;
4954         DKBUF;
4955
4956         assert(key);
4957         assert(data);
4958         DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
4959
4960         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
4961                 return EINVAL;
4962
4963         if (txn->mt_flags & MDB_TXN_ERROR)
4964                 return MDB_BAD_TXN;
4965
4966         if (key->mv_size > MDB_MAXKEYSIZE) {
4967                 return MDB_BAD_VALSIZE;
4968         }
4969
4970         mdb_cursor_init(&mc, txn, dbi, &mx);
4971         return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
4972 }
4973
4974 /** Find a sibling for a page.
4975  * Replaces the page at the top of the cursor's stack with the
4976  * specified sibling, if one exists.
4977  * @param[in] mc The cursor for this operation.
4978  * @param[in] move_right Non-zero if the right sibling is requested,
4979  * otherwise the left sibling.
4980  * @return 0 on success, non-zero on failure.
4981  */
4982 static int
4983 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
4984 {
4985         int              rc;
4986         MDB_node        *indx;
4987         MDB_page        *mp;
4988
4989         if (mc->mc_snum < 2) {
4990                 return MDB_NOTFOUND;            /* root has no siblings */
4991         }
4992
4993         mdb_cursor_pop(mc);
4994         DPRINTF(("parent page is page %"Z"u, index %u",
4995                 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
4996
4997         if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
4998                        : (mc->mc_ki[mc->mc_top] == 0)) {
4999                 DPRINTF(("no more keys left, moving to %s sibling",
5000                     move_right ? "right" : "left"));
5001                 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5002                         /* undo cursor_pop before returning */
5003                         mc->mc_top++;
5004                         mc->mc_snum++;
5005                         return rc;
5006                 }
5007         } else {
5008                 if (move_right)
5009                         mc->mc_ki[mc->mc_top]++;
5010                 else
5011                         mc->mc_ki[mc->mc_top]--;
5012                 DPRINTF(("just moving to %s index key %u",
5013                     move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5014         }
5015         assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
5016
5017         indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5018         if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5019                 /* mc will be inconsistent if caller does mc_snum++ as above */
5020                 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5021                 return rc;
5022         }
5023
5024         mdb_cursor_push(mc, mp);
5025         if (!move_right)
5026                 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5027
5028         return MDB_SUCCESS;
5029 }
5030
5031 /** Move the cursor to the next data item. */
5032 static int
5033 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5034 {
5035         MDB_page        *mp;
5036         MDB_node        *leaf;
5037         int rc;
5038
5039         if (mc->mc_flags & C_EOF) {
5040                 return MDB_NOTFOUND;
5041         }
5042
5043         assert(mc->mc_flags & C_INITIALIZED);
5044
5045         mp = mc->mc_pg[mc->mc_top];
5046
5047         if (mc->mc_db->md_flags & MDB_DUPSORT) {
5048                 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5049                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5050                         if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5051                                 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5052                                 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5053                                         if (rc == MDB_SUCCESS)
5054                                                 MDB_GET_KEY(leaf, key);
5055                                         return rc;
5056                                 }
5057                         }
5058                 } else {
5059                         mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5060                         if (op == MDB_NEXT_DUP)
5061                                 return MDB_NOTFOUND;
5062                 }
5063         }
5064
5065         DPRINTF(("cursor_next: top page is %"Z"u in cursor %p", mp->mp_pgno, (void *) mc));
5066         if (mc->mc_flags & C_DEL)
5067                 goto skip;
5068
5069         if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5070                 DPUTS("=====> move to next sibling page");
5071                 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5072                         mc->mc_flags |= C_EOF;
5073                         return rc;
5074                 }
5075                 mp = mc->mc_pg[mc->mc_top];
5076                 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5077         } else
5078                 mc->mc_ki[mc->mc_top]++;
5079
5080 skip:
5081         DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5082             mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5083
5084         if (IS_LEAF2(mp)) {
5085                 key->mv_size = mc->mc_db->md_pad;
5086                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5087                 return MDB_SUCCESS;
5088         }
5089
5090         assert(IS_LEAF(mp));
5091         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5092
5093         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5094                 mdb_xcursor_init1(mc, leaf);
5095         }
5096         if (data) {
5097                 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5098                         return rc;
5099
5100                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5101                         rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5102                         if (rc != MDB_SUCCESS)
5103                                 return rc;
5104                 }
5105         }
5106
5107         MDB_GET_KEY(leaf, key);
5108         return MDB_SUCCESS;
5109 }
5110
5111 /** Move the cursor to the previous data item. */
5112 static int
5113 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5114 {
5115         MDB_page        *mp;
5116         MDB_node        *leaf;
5117         int rc;
5118
5119         assert(mc->mc_flags & C_INITIALIZED);
5120
5121         mp = mc->mc_pg[mc->mc_top];
5122
5123         if (mc->mc_db->md_flags & MDB_DUPSORT) {
5124                 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5125                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5126                         if (op == MDB_PREV || op == MDB_PREV_DUP) {
5127                                 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5128                                 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5129                                         if (rc == MDB_SUCCESS)
5130                                                 MDB_GET_KEY(leaf, key);
5131                                         return rc;
5132                                 }
5133                         } else {
5134                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5135                                 if (op == MDB_PREV_DUP)
5136                                         return MDB_NOTFOUND;
5137                         }
5138                 }
5139         }
5140
5141         DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p", mp->mp_pgno, (void *) mc));
5142
5143         if (mc->mc_ki[mc->mc_top] == 0)  {
5144                 DPUTS("=====> move to prev sibling page");
5145                 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5146                         return rc;
5147                 }
5148                 mp = mc->mc_pg[mc->mc_top];
5149                 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5150                 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5151         } else
5152                 mc->mc_ki[mc->mc_top]--;
5153
5154         mc->mc_flags &= ~C_EOF;
5155
5156         DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5157             mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5158
5159         if (IS_LEAF2(mp)) {
5160                 key->mv_size = mc->mc_db->md_pad;
5161                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5162                 return MDB_SUCCESS;
5163         }
5164
5165         assert(IS_LEAF(mp));
5166         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5167
5168         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5169                 mdb_xcursor_init1(mc, leaf);
5170         }
5171         if (data) {
5172                 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5173                         return rc;
5174
5175                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5176                         rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5177                         if (rc != MDB_SUCCESS)
5178                                 return rc;
5179                 }
5180         }
5181
5182         MDB_GET_KEY(leaf, key);
5183         return MDB_SUCCESS;
5184 }
5185
5186 /** Set the cursor on a specific data item. */
5187 static int
5188 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5189     MDB_cursor_op op, int *exactp)
5190 {
5191         int              rc;
5192         MDB_page        *mp;
5193         MDB_node        *leaf = NULL;
5194         DKBUF;
5195
5196         assert(mc);
5197         assert(key);
5198         if (key->mv_size == 0)
5199                 return MDB_BAD_VALSIZE;
5200
5201         if (mc->mc_xcursor)
5202                 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5203
5204         /* See if we're already on the right page */
5205         if (mc->mc_flags & C_INITIALIZED) {
5206                 MDB_val nodekey;
5207
5208                 mp = mc->mc_pg[mc->mc_top];
5209                 if (!NUMKEYS(mp)) {
5210                         mc->mc_ki[mc->mc_top] = 0;
5211                         return MDB_NOTFOUND;
5212                 }
5213                 if (mp->mp_flags & P_LEAF2) {
5214                         nodekey.mv_size = mc->mc_db->md_pad;
5215                         nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5216                 } else {
5217                         leaf = NODEPTR(mp, 0);
5218                         MDB_GET_KEY2(leaf, nodekey);
5219                 }
5220                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5221                 if (rc == 0) {
5222                         /* Probably happens rarely, but first node on the page
5223                          * was the one we wanted.
5224                          */
5225                         mc->mc_ki[mc->mc_top] = 0;
5226                         if (exactp)
5227                                 *exactp = 1;
5228                         goto set1;
5229                 }
5230                 if (rc > 0) {
5231                         unsigned int i;
5232                         unsigned int nkeys = NUMKEYS(mp);
5233                         if (nkeys > 1) {
5234                                 if (mp->mp_flags & P_LEAF2) {
5235                                         nodekey.mv_data = LEAF2KEY(mp,
5236                                                  nkeys-1, nodekey.mv_size);
5237                                 } else {
5238                                         leaf = NODEPTR(mp, nkeys-1);
5239                                         MDB_GET_KEY2(leaf, nodekey);
5240                                 }
5241                                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5242                                 if (rc == 0) {
5243                                         /* last node was the one we wanted */
5244                                         mc->mc_ki[mc->mc_top] = nkeys-1;
5245                                         if (exactp)
5246                                                 *exactp = 1;
5247                                         goto set1;
5248                                 }
5249                                 if (rc < 0) {
5250                                         if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5251                                                 /* This is definitely the right page, skip search_page */
5252                                                 if (mp->mp_flags & P_LEAF2) {
5253                                                         nodekey.mv_data = LEAF2KEY(mp,
5254                                                                  mc->mc_ki[mc->mc_top], nodekey.mv_size);
5255                                                 } else {
5256                                                         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5257                                                         MDB_GET_KEY2(leaf, nodekey);
5258                                                 }
5259                                                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5260                                                 if (rc == 0) {
5261                                                         /* current node was the one we wanted */
5262                                                         if (exactp)
5263                                                                 *exactp = 1;
5264                                                         goto set1;
5265                                                 }
5266                                         }
5267                                         rc = 0;
5268                                         goto set2;
5269                                 }
5270                         }
5271                         /* If any parents have right-sibs, search.
5272                          * Otherwise, there's nothing further.
5273                          */
5274                         for (i=0; i<mc->mc_top; i++)
5275                                 if (mc->mc_ki[i] <
5276                                         NUMKEYS(mc->mc_pg[i])-1)
5277                                         break;
5278                         if (i == mc->mc_top) {
5279                                 /* There are no other pages */
5280                                 mc->mc_ki[mc->mc_top] = nkeys;
5281                                 return MDB_NOTFOUND;
5282                         }
5283                 }
5284                 if (!mc->mc_top) {
5285                         /* There are no other pages */
5286                         mc->mc_ki[mc->mc_top] = 0;
5287                         if (op == MDB_SET_RANGE) {
5288                                 rc = 0;
5289                                 goto set1;
5290                         } else
5291                                 return MDB_NOTFOUND;
5292                 }
5293         }
5294
5295         rc = mdb_page_search(mc, key, 0);
5296         if (rc != MDB_SUCCESS)
5297                 return rc;
5298
5299         mp = mc->mc_pg[mc->mc_top];
5300         assert(IS_LEAF(mp));
5301
5302 set2:
5303         leaf = mdb_node_search(mc, key, exactp);
5304         if (exactp != NULL && !*exactp) {
5305                 /* MDB_SET specified and not an exact match. */
5306                 return MDB_NOTFOUND;
5307         }
5308
5309         if (leaf == NULL) {
5310                 DPUTS("===> inexact leaf not found, goto sibling");
5311                 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5312                         return rc;              /* no entries matched */
5313                 mp = mc->mc_pg[mc->mc_top];
5314                 assert(IS_LEAF(mp));
5315                 leaf = NODEPTR(mp, 0);
5316         }
5317
5318 set1:
5319         mc->mc_flags |= C_INITIALIZED;
5320         mc->mc_flags &= ~C_EOF;
5321
5322         if (IS_LEAF2(mp)) {
5323                 key->mv_size = mc->mc_db->md_pad;
5324                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5325                 return MDB_SUCCESS;
5326         }
5327
5328         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5329                 mdb_xcursor_init1(mc, leaf);
5330         }
5331         if (data) {
5332                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5333                         if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5334                                 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5335                         } else {
5336                                 int ex2, *ex2p;
5337                                 if (op == MDB_GET_BOTH) {
5338                                         ex2p = &ex2;
5339                                         ex2 = 0;
5340                                 } else {
5341                                         ex2p = NULL;
5342                                 }
5343                                 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5344                                 if (rc != MDB_SUCCESS)
5345                                         return rc;
5346                         }
5347                 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5348                         MDB_val d2;
5349                         if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5350                                 return rc;
5351                         rc = mc->mc_dbx->md_dcmp(data, &d2);
5352                         if (rc) {
5353                                 if (op == MDB_GET_BOTH || rc > 0)
5354                                         return MDB_NOTFOUND;
5355                                 rc = 0;
5356                         }
5357
5358                 } else {
5359                         if (mc->mc_xcursor)
5360                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5361                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5362                                 return rc;
5363                 }
5364         }
5365
5366         /* The key already matches in all other cases */
5367         if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5368                 MDB_GET_KEY(leaf, key);
5369         DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5370
5371         return rc;
5372 }
5373
5374 /** Move the cursor to the first item in the database. */
5375 static int
5376 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5377 {
5378         int              rc;
5379         MDB_node        *leaf;
5380
5381         if (mc->mc_xcursor)
5382                 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5383
5384         if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5385                 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5386                 if (rc != MDB_SUCCESS)
5387                         return rc;
5388         }
5389         assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5390
5391         leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5392         mc->mc_flags |= C_INITIALIZED;
5393         mc->mc_flags &= ~C_EOF;
5394
5395         mc->mc_ki[mc->mc_top] = 0;
5396
5397         if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5398                 key->mv_size = mc->mc_db->md_pad;
5399                 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5400                 return MDB_SUCCESS;
5401         }
5402
5403         if (data) {
5404                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5405                         mdb_xcursor_init1(mc, leaf);
5406                         rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5407                         if (rc)
5408                                 return rc;
5409                 } else {
5410                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5411                                 return rc;
5412                 }
5413         }
5414         MDB_GET_KEY(leaf, key);
5415         return MDB_SUCCESS;
5416 }
5417
5418 /** Move the cursor to the last item in the database. */
5419 static int
5420 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5421 {
5422         int              rc;
5423         MDB_node        *leaf;
5424
5425         if (mc->mc_xcursor)
5426                 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5427
5428         if (!(mc->mc_flags & C_EOF)) {
5429
5430                 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5431                         rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5432                         if (rc != MDB_SUCCESS)
5433                                 return rc;
5434                 }
5435                 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5436
5437         }
5438         mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5439         mc->mc_flags |= C_INITIALIZED|C_EOF;
5440         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5441
5442         if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5443                 key->mv_size = mc->mc_db->md_pad;
5444                 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5445                 return MDB_SUCCESS;
5446         }
5447
5448         if (data) {
5449                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5450                         mdb_xcursor_init1(mc, leaf);
5451                         rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5452                         if (rc)
5453                                 return rc;
5454                 } else {
5455                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5456                                 return rc;
5457                 }
5458         }
5459
5460         MDB_GET_KEY(leaf, key);
5461         return MDB_SUCCESS;
5462 }
5463
5464 int
5465 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5466     MDB_cursor_op op)
5467 {
5468         int              rc;
5469         int              exact = 0;
5470         int              (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5471
5472         assert(mc);
5473
5474         if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5475                 return MDB_BAD_TXN;
5476
5477         switch (op) {
5478         case MDB_GET_CURRENT:
5479                 if (!(mc->mc_flags & C_INITIALIZED)) {
5480                         rc = EINVAL;
5481                 } else {
5482                         MDB_page *mp = mc->mc_pg[mc->mc_top];
5483                         int nkeys = NUMKEYS(mp);
5484                         if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5485                                 mc->mc_ki[mc->mc_top] = nkeys;
5486                                 rc = MDB_NOTFOUND;
5487                                 break;
5488                         }
5489                         rc = MDB_SUCCESS;
5490                         if (IS_LEAF2(mp)) {
5491                                 key->mv_size = mc->mc_db->md_pad;
5492                                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5493                         } else {
5494                                 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5495                                 MDB_GET_KEY(leaf, key);
5496                                 if (data) {
5497                                         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5498                                                 if (mc->mc_flags & C_DEL)
5499                                                         mdb_xcursor_init1(mc, leaf);
5500                                                 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5501                                         } else {
5502                                                 rc = mdb_node_read(mc->mc_txn, leaf, data);
5503                                         }
5504                                 }
5505                         }
5506                 }
5507                 break;
5508         case MDB_GET_BOTH:
5509         case MDB_GET_BOTH_RANGE:
5510                 if (data == NULL) {
5511                         rc = EINVAL;
5512                         break;
5513                 }
5514                 if (mc->mc_xcursor == NULL) {
5515                         rc = MDB_INCOMPATIBLE;
5516                         break;
5517                 }
5518                 /* FALLTHRU */
5519         case MDB_SET:
5520         case MDB_SET_KEY:
5521         case MDB_SET_RANGE:
5522                 if (key == NULL) {
5523                         rc = EINVAL;
5524                 } else if (key->mv_size > MDB_MAXKEYSIZE) {
5525                         rc = MDB_BAD_VALSIZE;
5526                 } else if (op == MDB_SET_RANGE)
5527                         rc = mdb_cursor_set(mc, key, data, op, NULL);
5528                 else
5529                         rc = mdb_cursor_set(mc, key, data, op, &exact);
5530                 break;
5531         case MDB_GET_MULTIPLE:
5532                 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5533                         rc = EINVAL;
5534                         break;
5535                 }
5536                 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5537                         rc = MDB_INCOMPATIBLE;
5538                         break;
5539                 }
5540                 rc = MDB_SUCCESS;
5541                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5542                         (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5543                         break;
5544                 goto fetchm;
5545         case MDB_NEXT_MULTIPLE:
5546                 if (data == NULL) {
5547                         rc = EINVAL;
5548                         break;
5549                 }
5550                 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5551                         rc = MDB_INCOMPATIBLE;
5552                         break;
5553                 }
5554                 if (!(mc->mc_flags & C_INITIALIZED))
5555                         rc = mdb_cursor_first(mc, key, data);
5556                 else
5557                         rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5558                 if (rc == MDB_SUCCESS) {
5559                         if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5560                                 MDB_cursor *mx;
5561 fetchm:
5562                                 mx = &mc->mc_xcursor->mx_cursor;
5563                                 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5564                                         mx->mc_db->md_pad;
5565                                 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5566                                 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5567                         } else {
5568                                 rc = MDB_NOTFOUND;
5569                         }
5570                 }
5571                 break;
5572         case MDB_NEXT:
5573         case MDB_NEXT_DUP:
5574         case MDB_NEXT_NODUP:
5575                 if (!(mc->mc_flags & C_INITIALIZED))
5576                         rc = mdb_cursor_first(mc, key, data);
5577                 else
5578                         rc = mdb_cursor_next(mc, key, data, op);
5579                 break;
5580         case MDB_PREV:
5581         case MDB_PREV_DUP:
5582         case MDB_PREV_NODUP:
5583                 if (!(mc->mc_flags & C_INITIALIZED)) {
5584                         rc = mdb_cursor_last(mc, key, data);
5585                         if (rc)
5586                                 break;
5587                         mc->mc_flags |= C_INITIALIZED;
5588                         mc->mc_ki[mc->mc_top]++;
5589                 }
5590                 rc = mdb_cursor_prev(mc, key, data, op);
5591                 break;
5592         case MDB_FIRST:
5593                 rc = mdb_cursor_first(mc, key, data);
5594                 break;
5595         case MDB_FIRST_DUP:
5596                 mfunc = mdb_cursor_first;
5597         mmove:
5598                 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5599                         rc = EINVAL;
5600                         break;
5601                 }
5602                 if (mc->mc_xcursor == NULL) {
5603                         rc = MDB_INCOMPATIBLE;
5604                         break;
5605                 }
5606                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5607                         rc = EINVAL;
5608                         break;
5609                 }
5610                 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
5611                 break;
5612         case MDB_LAST:
5613                 rc = mdb_cursor_last(mc, key, data);
5614                 break;
5615         case MDB_LAST_DUP:
5616                 mfunc = mdb_cursor_last;
5617                 goto mmove;
5618         default:
5619                 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
5620                 rc = EINVAL;
5621                 break;
5622         }
5623
5624         if (mc->mc_flags & C_DEL)
5625                 mc->mc_flags ^= C_DEL;
5626
5627         return rc;
5628 }
5629
5630 /** Touch all the pages in the cursor stack. Set mc_top.
5631  *      Makes sure all the pages are writable, before attempting a write operation.
5632  * @param[in] mc The cursor to operate on.
5633  */
5634 static int
5635 mdb_cursor_touch(MDB_cursor *mc)
5636 {
5637         int rc = MDB_SUCCESS;
5638
5639         if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5640                 MDB_cursor mc2;
5641                 MDB_xcursor mcx;
5642                 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5643                 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5644                 if (rc)
5645                          return rc;
5646                 *mc->mc_dbflag |= DB_DIRTY;
5647         }
5648         mc->mc_top = 0;
5649         if (mc->mc_snum) {
5650                 do {
5651                         rc = mdb_page_touch(mc);
5652                 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
5653                 mc->mc_top = mc->mc_snum-1;
5654         }
5655         return rc;
5656 }
5657
5658 /** Do not spill pages to disk if txn is getting full, may fail instead */
5659 #define MDB_NOSPILL     0x8000
5660
5661 int
5662 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5663     unsigned int flags)
5664 {
5665         enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5666         MDB_env         *env = mc->mc_txn->mt_env;
5667         MDB_node        *leaf = NULL;
5668         MDB_val xdata, *rdata, dkey;
5669         MDB_db dummy;
5670         int do_sub = 0, insert = 0;
5671         unsigned int mcount = 0, dcount = 0, nospill;
5672         size_t nsize;
5673         int rc, rc2;
5674         char dbuf[MDB_MAXKEYSIZE+1];
5675         unsigned int nflags;
5676         DKBUF;
5677
5678         /* Check this first so counter will always be zero on any
5679          * early failures.
5680          */
5681         if (flags & MDB_MULTIPLE) {
5682                 dcount = data[1].mv_size;
5683                 data[1].mv_size = 0;
5684                 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5685                         return MDB_INCOMPATIBLE;
5686         }
5687
5688         nospill = flags & MDB_NOSPILL;
5689         flags &= ~MDB_NOSPILL;
5690
5691         if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
5692                 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
5693
5694         if (flags != MDB_CURRENT && (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE))
5695                 return MDB_BAD_VALSIZE;
5696
5697         if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT) && data->mv_size > MDB_MAXKEYSIZE)
5698                 return MDB_BAD_VALSIZE;
5699
5700 #if SIZE_MAX > MAXDATASIZE
5701         if (data->mv_size > MAXDATASIZE)
5702                 return MDB_BAD_VALSIZE;
5703 #endif
5704
5705         DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
5706                 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
5707
5708         dkey.mv_size = 0;
5709
5710         if (flags == MDB_CURRENT) {
5711                 if (!(mc->mc_flags & C_INITIALIZED))
5712                         return EINVAL;
5713                 rc = MDB_SUCCESS;
5714         } else if (mc->mc_db->md_root == P_INVALID) {
5715                 /* new database, cursor has nothing to point to */
5716                 mc->mc_snum = 0;
5717                 mc->mc_top = 0;
5718                 mc->mc_flags &= ~C_INITIALIZED;
5719                 rc = MDB_NO_ROOT;
5720         } else {
5721                 int exact = 0;
5722                 MDB_val d2;
5723                 if (flags & MDB_APPEND) {
5724                         MDB_val k2;
5725                         rc = mdb_cursor_last(mc, &k2, &d2);
5726                         if (rc == 0) {
5727                                 rc = mc->mc_dbx->md_cmp(key, &k2);
5728                                 if (rc > 0) {
5729                                         rc = MDB_NOTFOUND;
5730                                         mc->mc_ki[mc->mc_top]++;
5731                                 } else {
5732                                         /* new key is <= last key */
5733                                         rc = MDB_KEYEXIST;
5734                                 }
5735                         }
5736                 } else {
5737                         rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5738                 }
5739                 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5740                         DPRINTF(("duplicate key [%s]", DKEY(key)));
5741                         *data = d2;
5742                         return MDB_KEYEXIST;
5743                 }
5744                 if (rc && rc != MDB_NOTFOUND)
5745                         return rc;
5746         }
5747
5748         if (mc->mc_flags & C_DEL)
5749                 mc->mc_flags ^= C_DEL;
5750
5751         /* Cursor is positioned, check for room in the dirty list */
5752         if (!nospill) {
5753                 if (flags & MDB_MULTIPLE) {
5754                         rdata = &xdata;
5755                         xdata.mv_size = data->mv_size * dcount;
5756                 } else {
5757                         rdata = data;
5758                 }
5759                 if ((rc2 = mdb_page_spill(mc, key, rdata)))
5760                         return rc2;
5761         }
5762
5763         if (rc == MDB_NO_ROOT) {
5764                 MDB_page *np;
5765                 /* new database, write a root leaf page */
5766                 DPUTS("allocating new root leaf page");
5767                 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
5768                         return rc2;
5769                 }
5770                 mdb_cursor_push(mc, np);
5771                 mc->mc_db->md_root = np->mp_pgno;
5772                 mc->mc_db->md_depth++;
5773                 *mc->mc_dbflag |= DB_DIRTY;
5774                 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5775                         == MDB_DUPFIXED)
5776                         np->mp_flags |= P_LEAF2;
5777                 mc->mc_flags |= C_INITIALIZED;
5778         } else {
5779                 /* make sure all cursor pages are writable */
5780                 rc2 = mdb_cursor_touch(mc);
5781                 if (rc2)
5782                         return rc2;
5783         }
5784
5785         /* The key already exists */
5786         if (rc == MDB_SUCCESS) {
5787                 MDB_page        *fp, *mp;
5788                 MDB_val         olddata;
5789
5790                 /* there's only a key anyway, so this is a no-op */
5791                 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5792                         unsigned int ksize = mc->mc_db->md_pad;
5793                         if (key->mv_size != ksize)
5794                                 return MDB_BAD_VALSIZE;
5795                         if (flags == MDB_CURRENT) {
5796                                 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5797                                 memcpy(ptr, key->mv_data, ksize);
5798                         }
5799                         return MDB_SUCCESS;
5800                 }
5801
5802 more:
5803                 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5804                 olddata.mv_size = NODEDSZ(leaf);
5805                 olddata.mv_data = NODEDATA(leaf);
5806
5807                 /* DB has dups? */
5808                 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
5809                         mp = fp = xdata.mv_data = env->me_pbuf;
5810                         mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5811
5812                         /* Was a single item before, must convert now */
5813                         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5814                                 /* Just overwrite the current item */
5815                                 if (flags == MDB_CURRENT)
5816                                         goto current;
5817
5818                                 dkey = olddata;
5819 #if UINT_MAX < SIZE_MAX
5820                                 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
5821 #ifdef MISALIGNED_OK
5822                                         mc->mc_dbx->md_dcmp = mdb_cmp_long;
5823 #else
5824                                         mc->mc_dbx->md_dcmp = mdb_cmp_cint;
5825 #endif
5826 #endif
5827                                 /* if data matches, skip it */
5828                                 if (!mc->mc_dbx->md_dcmp(data, &dkey)) {
5829                                         if (flags & MDB_NODUPDATA)
5830                                                 rc = MDB_KEYEXIST;
5831                                         else if (flags & MDB_MULTIPLE)
5832                                                 goto next_mult;
5833                                         else
5834                                                 rc = MDB_SUCCESS;
5835                                         return rc;
5836                                 }
5837
5838                                 /* create a fake page for the dup items */
5839                                 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
5840                                 dkey.mv_data = dbuf;
5841                                 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5842                                 fp->mp_lower = PAGEHDRSZ;
5843                                 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5844                                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5845                                         fp->mp_flags |= P_LEAF2;
5846                                         fp->mp_pad = data->mv_size;
5847                                         xdata.mv_size += 2 * data->mv_size;     /* leave space for 2 more */
5848                                 } else {
5849                                         xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
5850                                                 (dkey.mv_size & 1) + (data->mv_size & 1);
5851                                 }
5852                                 fp->mp_upper = xdata.mv_size;
5853                         } else if (leaf->mn_flags & F_SUBDATA) {
5854                                 /* Data is on sub-DB, just store it */
5855                                 flags |= F_DUPDATA|F_SUBDATA;
5856                                 goto put_sub;
5857                         } else {
5858                                 /* See if we need to convert from fake page to subDB */
5859                                 unsigned int offset;
5860                                 unsigned int i;
5861                                 uint16_t fp_flags;
5862
5863                                 fp = olddata.mv_data;
5864                                 switch (flags) {
5865                                 default:
5866                                         if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5867                                                 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
5868                                                 offset += offset & 1;
5869                                                 break;
5870                                         }
5871                                         offset = fp->mp_pad;
5872                                         if (SIZELEFT(fp) < offset) {
5873                                                 offset *= 4; /* space for 4 more */
5874                                                 break;
5875                                         }
5876                                         /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
5877                                 case MDB_CURRENT:
5878                                         fp->mp_flags |= P_DIRTY;
5879                                         COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
5880                                         mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
5881                                         flags |= F_DUPDATA;
5882                                         goto put_sub;
5883                                 }
5884                                 fp_flags = fp->mp_flags;
5885                                 xdata.mv_size = olddata.mv_size + offset;
5886                                 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + xdata.mv_size
5887                                         >= env->me_nodemax) {
5888                                         /* yes, convert it */
5889                                         if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5890                                                 dummy.md_pad = fp->mp_pad;
5891                                                 dummy.md_flags = MDB_DUPFIXED;
5892                                                 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5893                                                         dummy.md_flags |= MDB_INTEGERKEY;
5894                                         } else {
5895                                                 dummy.md_pad = 0;
5896                                                 dummy.md_flags = 0;
5897                                         }
5898                                         dummy.md_depth = 1;
5899                                         dummy.md_branch_pages = 0;
5900                                         dummy.md_leaf_pages = 1;
5901                                         dummy.md_overflow_pages = 0;
5902                                         dummy.md_entries = NUMKEYS(fp);
5903                                         xdata.mv_size = sizeof(MDB_db);
5904                                         xdata.mv_data = &dummy;
5905                                         if ((rc = mdb_page_alloc(mc, 1, &mp)))
5906                                                 return rc;
5907                                         offset = env->me_psize - olddata.mv_size;
5908                                         flags |= F_DUPDATA|F_SUBDATA;
5909                                         dummy.md_root = mp->mp_pgno;
5910                                         fp_flags &= ~P_SUBP;
5911                                 }
5912                                 mp->mp_flags = fp_flags | P_DIRTY;
5913                                 mp->mp_pad   = fp->mp_pad;
5914                                 mp->mp_lower = fp->mp_lower;
5915                                 mp->mp_upper = fp->mp_upper + offset;
5916                                 if (IS_LEAF2(fp)) {
5917                                         memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
5918                                 } else {
5919                                         memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper,
5920                                                 olddata.mv_size - fp->mp_upper);
5921                                         for (i=0; i<NUMKEYS(fp); i++)
5922                                                 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
5923                                 }
5924                         }
5925
5926                         rdata = &xdata;
5927                         flags |= F_DUPDATA;
5928                         do_sub = 1;
5929                         mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5930                         goto new_sub;
5931                 }
5932 current:
5933                 /* overflow page overwrites need special handling */
5934                 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5935                         MDB_page *omp;
5936                         pgno_t pg;
5937                         int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
5938
5939                         memcpy(&pg, olddata.mv_data, sizeof(pg));
5940                         if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
5941                                 return rc2;
5942                         ovpages = omp->mp_pages;
5943
5944                         /* Is the ov page large enough? */
5945                         if (ovpages >= dpages) {
5946                           if (!(omp->mp_flags & P_DIRTY) &&
5947                                   (level || (env->me_flags & MDB_WRITEMAP)))
5948                           {
5949                                 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
5950                                 if (rc)
5951                                         return rc;
5952                                 level = 0;              /* dirty in this txn or clean */
5953                           }
5954                           /* Is it dirty? */
5955                           if (omp->mp_flags & P_DIRTY) {
5956                                 /* yes, overwrite it. Note in this case we don't
5957                                  * bother to try shrinking the page if the new data
5958                                  * is smaller than the overflow threshold.
5959                                  */
5960                                 if (level > 1) {
5961                                         /* It is writable only in a parent txn */
5962                                         size_t sz = (size_t) env->me_psize * ovpages, off;
5963                                         MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
5964                                         MDB_ID2 id2;
5965                                         if (!np)
5966                                                 return ENOMEM;
5967                                         id2.mid = pg;
5968                                         id2.mptr = np;
5969                                         mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
5970                                         if (!(flags & MDB_RESERVE)) {
5971                                                 /* Copy end of page, adjusting alignment so
5972                                                  * compiler may copy words instead of bytes.
5973                                                  */
5974                                                 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
5975                                                 memcpy((size_t *)((char *)np + off),
5976                                                         (size_t *)((char *)omp + off), sz - off);
5977                                                 sz = PAGEHDRSZ;
5978                                         }
5979                                         memcpy(np, omp, sz); /* Copy beginning of page */
5980                                         omp = np;
5981                                 }
5982                                 SETDSZ(leaf, data->mv_size);
5983                                 if (F_ISSET(flags, MDB_RESERVE))
5984                                         data->mv_data = METADATA(omp);
5985                                 else
5986                                         memcpy(METADATA(omp), data->mv_data, data->mv_size);
5987                                 goto done;
5988                           }
5989                         }
5990                         if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
5991                                 return rc2;
5992                 } else if (data->mv_size == olddata.mv_size) {
5993                         /* same size, just replace it. Note that we could
5994                          * also reuse this node if the new data is smaller,
5995                          * but instead we opt to shrink the node in that case.
5996                          */
5997                         if (F_ISSET(flags, MDB_RESERVE))
5998                                 data->mv_data = olddata.mv_data;
5999                         else if (data->mv_size)
6000                                 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6001                         else
6002                                 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6003                         goto done;
6004                 }
6005                 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6006                 mc->mc_db->md_entries--;
6007         } else {
6008                 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6009                 insert = 1;
6010         }
6011
6012         rdata = data;
6013
6014 new_sub:
6015         nflags = flags & NODE_ADD_FLAGS;
6016         nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6017         if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6018                 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6019                         nflags &= ~MDB_APPEND;
6020                 if (!insert)
6021                         nflags |= MDB_SPLIT_REPLACE;
6022                 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6023         } else {
6024                 /* There is room already in this leaf page. */
6025                 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6026                 if (rc == 0 && !do_sub && insert) {
6027                         /* Adjust other cursors pointing to mp */
6028                         MDB_cursor *m2, *m3;
6029                         MDB_dbi dbi = mc->mc_dbi;
6030                         unsigned i = mc->mc_top;
6031                         MDB_page *mp = mc->mc_pg[i];
6032
6033                         for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6034                                 if (mc->mc_flags & C_SUB)
6035                                         m3 = &m2->mc_xcursor->mx_cursor;
6036                                 else
6037                                         m3 = m2;
6038                                 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6039                                 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6040                                         m3->mc_ki[i]++;
6041                                 }
6042                         }
6043                 }
6044         }
6045
6046         if (rc != MDB_SUCCESS)
6047                 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6048         else {
6049                 /* Now store the actual data in the child DB. Note that we're
6050                  * storing the user data in the keys field, so there are strict
6051                  * size limits on dupdata. The actual data fields of the child
6052                  * DB are all zero size.
6053                  */
6054                 if (do_sub) {
6055                         int xflags;
6056 put_sub:
6057                         xdata.mv_size = 0;
6058                         xdata.mv_data = "";
6059                         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6060                         if (flags & MDB_CURRENT) {
6061                                 xflags = MDB_CURRENT|MDB_NOSPILL;
6062                         } else {
6063                                 mdb_xcursor_init1(mc, leaf);
6064                                 xflags = (flags & MDB_NODUPDATA) ?
6065                                         MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6066                         }
6067                         /* converted, write the original data first */
6068                         if (dkey.mv_size) {
6069                                 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6070                                 if (rc)
6071                                         return rc;
6072                                 {
6073                                         /* Adjust other cursors pointing to mp */
6074                                         MDB_cursor *m2;
6075                                         unsigned i = mc->mc_top;
6076                                         MDB_page *mp = mc->mc_pg[i];
6077
6078                                         for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6079                                                 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6080                                                 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6081                                                 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6082                                                         mdb_xcursor_init1(m2, leaf);
6083                                                 }
6084                                         }
6085                                 }
6086                                 /* we've done our job */
6087                                 dkey.mv_size = 0;
6088                         }
6089                         if (flags & MDB_APPENDDUP)
6090                                 xflags |= MDB_APPEND;
6091                         rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6092                         if (flags & F_SUBDATA) {
6093                                 void *db = NODEDATA(leaf);
6094                                 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6095                         }
6096                 }
6097                 /* sub-writes might have failed so check rc again.
6098                  * Don't increment count if we just replaced an existing item.
6099                  */
6100                 if (!rc && !(flags & MDB_CURRENT))
6101                         mc->mc_db->md_entries++;
6102                 if (flags & MDB_MULTIPLE) {
6103                         if (!rc) {
6104 next_mult:
6105                                 mcount++;
6106                                 /* let caller know how many succeeded, if any */
6107                                 data[1].mv_size = mcount;
6108                                 if (mcount < dcount) {
6109                                         data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6110                                         goto more;
6111                                 }
6112                         }
6113                 }
6114         }
6115 done:
6116         /* If we succeeded and the key didn't exist before, make sure
6117          * the cursor is marked valid.
6118          */
6119         if (!rc && insert)
6120                 mc->mc_flags |= C_INITIALIZED;
6121         return rc;
6122 }
6123
6124 int
6125 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6126 {
6127         MDB_node        *leaf;
6128         MDB_page        *mp;
6129         int rc;
6130
6131         if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6132                 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6133
6134         if (!(mc->mc_flags & C_INITIALIZED))
6135                 return EINVAL;
6136
6137         if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6138                 return MDB_NOTFOUND;
6139
6140         if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6141                 return rc;
6142
6143         rc = mdb_cursor_touch(mc);
6144         if (rc)
6145                 return rc;
6146
6147         mp = mc->mc_pg[mc->mc_top];
6148         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6149
6150         if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6151                 if (!(flags & MDB_NODUPDATA)) {
6152                         if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6153                                 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6154                         }
6155                         rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6156                         /* If sub-DB still has entries, we're done */
6157                         if (mc->mc_xcursor->mx_db.md_entries) {
6158                                 if (leaf->mn_flags & F_SUBDATA) {
6159                                         /* update subDB info */
6160                                         void *db = NODEDATA(leaf);
6161                                         memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6162                                 } else {
6163                                         MDB_cursor *m2;
6164                                         /* shrink fake page */
6165                                         mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6166                                         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6167                                         mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6168                                         /* fix other sub-DB cursors pointed at this fake page */
6169                                         for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6170                                                 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6171                                                 if (m2->mc_pg[mc->mc_top] == mp &&
6172                                                         m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6173                                                         m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6174                                         }
6175                                 }
6176                                 mc->mc_db->md_entries--;
6177                                 mc->mc_flags |= C_DEL;
6178                                 return rc;
6179                         }
6180                         /* otherwise fall thru and delete the sub-DB */
6181                 }
6182
6183                 if (leaf->mn_flags & F_SUBDATA) {
6184                         /* add all the child DB's pages to the free list */
6185                         rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6186                         if (rc == MDB_SUCCESS) {
6187                                 mc->mc_db->md_entries -=
6188                                         mc->mc_xcursor->mx_db.md_entries;
6189                         }
6190                 }
6191         }
6192
6193         return mdb_cursor_del0(mc, leaf);
6194 }
6195
6196 /** Allocate and initialize new pages for a database.
6197  * @param[in] mc a cursor on the database being added to.
6198  * @param[in] flags flags defining what type of page is being allocated.
6199  * @param[in] num the number of pages to allocate. This is usually 1,
6200  * unless allocating overflow pages for a large record.
6201  * @param[out] mp Address of a page, or NULL on failure.
6202  * @return 0 on success, non-zero on failure.
6203  */
6204 static int
6205 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6206 {
6207         MDB_page        *np;
6208         int rc;
6209
6210         if ((rc = mdb_page_alloc(mc, num, &np)))
6211                 return rc;
6212         DPRINTF(("allocated new mpage %"Z"u, page size %u",
6213             np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6214         np->mp_flags = flags | P_DIRTY;
6215         np->mp_lower = PAGEHDRSZ;
6216         np->mp_upper = mc->mc_txn->mt_env->me_psize;
6217
6218         if (IS_BRANCH(np))
6219                 mc->mc_db->md_branch_pages++;
6220         else if (IS_LEAF(np))
6221                 mc->mc_db->md_leaf_pages++;
6222         else if (IS_OVERFLOW(np)) {
6223                 mc->mc_db->md_overflow_pages += num;
6224                 np->mp_pages = num;
6225         }
6226         *mp = np;
6227
6228         return 0;
6229 }
6230
6231 /** Calculate the size of a leaf node.
6232  * The size depends on the environment's page size; if a data item
6233  * is too large it will be put onto an overflow page and the node
6234  * size will only include the key and not the data. Sizes are always
6235  * rounded up to an even number of bytes, to guarantee 2-byte alignment
6236  * of the #MDB_node headers.
6237  * @param[in] env The environment handle.
6238  * @param[in] key The key for the node.
6239  * @param[in] data The data for the node.
6240  * @return The number of bytes needed to store the node.
6241  */
6242 static size_t
6243 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6244 {
6245         size_t           sz;
6246
6247         sz = LEAFSIZE(key, data);
6248         if (sz >= env->me_nodemax) {
6249                 /* put on overflow page */
6250                 sz -= data->mv_size - sizeof(pgno_t);
6251         }
6252         sz += sz & 1;
6253
6254         return sz + sizeof(indx_t);
6255 }
6256
6257 /** Calculate the size of a branch node.
6258  * The size should depend on the environment's page size but since
6259  * we currently don't support spilling large keys onto overflow
6260  * pages, it's simply the size of the #MDB_node header plus the
6261  * size of the key. Sizes are always rounded up to an even number
6262  * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6263  * @param[in] env The environment handle.
6264  * @param[in] key The key for the node.
6265  * @return The number of bytes needed to store the node.
6266  */
6267 static size_t
6268 mdb_branch_size(MDB_env *env, MDB_val *key)
6269 {
6270         size_t           sz;
6271
6272         sz = INDXSIZE(key);
6273         if (sz >= env->me_nodemax) {
6274                 /* put on overflow page */
6275                 /* not implemented */
6276                 /* sz -= key->size - sizeof(pgno_t); */
6277         }
6278
6279         return sz + sizeof(indx_t);
6280 }
6281
6282 /** Add a node to the page pointed to by the cursor.
6283  * @param[in] mc The cursor for this operation.
6284  * @param[in] indx The index on the page where the new node should be added.
6285  * @param[in] key The key for the new node.
6286  * @param[in] data The data for the new node, if any.
6287  * @param[in] pgno The page number, if adding a branch node.
6288  * @param[in] flags Flags for the node.
6289  * @return 0 on success, non-zero on failure. Possible errors are:
6290  * <ul>
6291  *      <li>ENOMEM - failed to allocate overflow pages for the node.
6292  *      <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6293  *      should never happen since all callers already calculate the
6294  *      page's free space before calling this function.
6295  * </ul>
6296  */
6297 static int
6298 mdb_node_add(MDB_cursor *mc, indx_t indx,
6299     MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6300 {
6301         unsigned int     i;
6302         size_t           node_size = NODESIZE;
6303         ssize_t          room;
6304         indx_t           ofs;
6305         MDB_node        *node;
6306         MDB_page        *mp = mc->mc_pg[mc->mc_top];
6307         MDB_page        *ofp = NULL;            /* overflow page */
6308         DKBUF;
6309
6310         assert(mp->mp_upper >= mp->mp_lower);
6311
6312         DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6313             IS_LEAF(mp) ? "leaf" : "branch",
6314                 IS_SUBP(mp) ? "sub-" : "",
6315             mp->mp_pgno, indx, data ? data->mv_size : 0,
6316                 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6317
6318         if (IS_LEAF2(mp)) {
6319                 /* Move higher keys up one slot. */
6320                 int ksize = mc->mc_db->md_pad, dif;
6321                 char *ptr = LEAF2KEY(mp, indx, ksize);
6322                 dif = NUMKEYS(mp) - indx;
6323                 if (dif > 0)
6324                         memmove(ptr+ksize, ptr, dif*ksize);
6325                 /* insert new key */
6326                 memcpy(ptr, key->mv_data, ksize);
6327
6328                 /* Just using these for counting */
6329                 mp->mp_lower += sizeof(indx_t);
6330                 mp->mp_upper -= ksize - sizeof(indx_t);
6331                 return MDB_SUCCESS;
6332         }
6333
6334         room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6335         if (key != NULL)
6336                 node_size += key->mv_size;
6337         if (IS_LEAF(mp)) {
6338                 assert(data);
6339                 if (F_ISSET(flags, F_BIGDATA)) {
6340                         /* Data already on overflow page. */
6341                         node_size += sizeof(pgno_t);
6342                 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_nodemax) {
6343                         int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6344                         int rc;
6345                         /* Put data on overflow page. */
6346                         DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6347                             data->mv_size, node_size+data->mv_size));
6348                         node_size += sizeof(pgno_t) + (node_size & 1);
6349                         if ((ssize_t)node_size > room)
6350                                 goto full;
6351                         if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6352                                 return rc;
6353                         DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6354                         flags |= F_BIGDATA;
6355                         goto update;
6356                 } else {
6357                         node_size += data->mv_size;
6358                 }
6359         }
6360         node_size += node_size & 1;
6361         if ((ssize_t)node_size > room)
6362                 goto full;
6363
6364 update:
6365         /* Move higher pointers up one slot. */
6366         for (i = NUMKEYS(mp); i > indx; i--)
6367                 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6368
6369         /* Adjust free space offsets. */
6370         ofs = mp->mp_upper - node_size;
6371         assert(ofs >= mp->mp_lower + sizeof(indx_t));
6372         mp->mp_ptrs[indx] = ofs;
6373         mp->mp_upper = ofs;
6374         mp->mp_lower += sizeof(indx_t);
6375
6376         /* Write the node data. */
6377         node = NODEPTR(mp, indx);
6378         node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6379         node->mn_flags = flags;
6380         if (IS_LEAF(mp))
6381                 SETDSZ(node,data->mv_size);
6382         else
6383                 SETPGNO(node,pgno);
6384
6385         if (key)
6386                 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6387
6388         if (IS_LEAF(mp)) {
6389                 assert(key);
6390                 if (ofp == NULL) {
6391                         if (F_ISSET(flags, F_BIGDATA))
6392                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
6393                                     sizeof(pgno_t));
6394                         else if (F_ISSET(flags, MDB_RESERVE))
6395                                 data->mv_data = node->mn_data + key->mv_size;
6396                         else
6397                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
6398                                     data->mv_size);
6399                 } else {
6400                         memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6401                             sizeof(pgno_t));
6402                         if (F_ISSET(flags, MDB_RESERVE))
6403                                 data->mv_data = METADATA(ofp);
6404                         else
6405                                 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6406                 }
6407         }
6408
6409         return MDB_SUCCESS;
6410
6411 full:
6412         DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6413                 mp->mp_pgno, NUMKEYS(mp)));
6414         DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6415         DPRINTF(("node size = %"Z"u", node_size));
6416         return MDB_PAGE_FULL;
6417 }
6418
6419 /** Delete the specified node from a page.
6420  * @param[in] mp The page to operate on.
6421  * @param[in] indx The index of the node to delete.
6422  * @param[in] ksize The size of a node. Only used if the page is
6423  * part of a #MDB_DUPFIXED database.
6424  */
6425 static void
6426 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
6427 {
6428         unsigned int     sz;
6429         indx_t           i, j, numkeys, ptr;
6430         MDB_node        *node;
6431         char            *base;
6432
6433 #if MDB_DEBUG
6434         {
6435         pgno_t pgno;
6436         COPY_PGNO(pgno, mp->mp_pgno);
6437         DPRINTF(("delete node %u on %s page %"Z"u", indx,
6438             IS_LEAF(mp) ? "leaf" : "branch", pgno));
6439         }
6440 #endif
6441         assert(indx < NUMKEYS(mp));
6442
6443         if (IS_LEAF2(mp)) {
6444                 int x = NUMKEYS(mp) - 1 - indx;
6445                 base = LEAF2KEY(mp, indx, ksize);
6446                 if (x)
6447                         memmove(base, base + ksize, x * ksize);
6448                 mp->mp_lower -= sizeof(indx_t);
6449                 mp->mp_upper += ksize - sizeof(indx_t);
6450                 return;
6451         }
6452
6453         node = NODEPTR(mp, indx);
6454         sz = NODESIZE + node->mn_ksize;
6455         if (IS_LEAF(mp)) {
6456                 if (F_ISSET(node->mn_flags, F_BIGDATA))
6457                         sz += sizeof(pgno_t);
6458                 else
6459                         sz += NODEDSZ(node);
6460         }
6461         sz += sz & 1;
6462
6463         ptr = mp->mp_ptrs[indx];
6464         numkeys = NUMKEYS(mp);
6465         for (i = j = 0; i < numkeys; i++) {
6466                 if (i != indx) {
6467                         mp->mp_ptrs[j] = mp->mp_ptrs[i];
6468                         if (mp->mp_ptrs[i] < ptr)
6469                                 mp->mp_ptrs[j] += sz;
6470                         j++;
6471                 }
6472         }
6473
6474         base = (char *)mp + mp->mp_upper;
6475         memmove(base + sz, base, ptr - mp->mp_upper);
6476
6477         mp->mp_lower -= sizeof(indx_t);
6478         mp->mp_upper += sz;
6479 }
6480
6481 /** Compact the main page after deleting a node on a subpage.
6482  * @param[in] mp The main page to operate on.
6483  * @param[in] indx The index of the subpage on the main page.
6484  */
6485 static void
6486 mdb_node_shrink(MDB_page *mp, indx_t indx)
6487 {
6488         MDB_node *node;
6489         MDB_page *sp, *xp;
6490         char *base;
6491         int osize, nsize;
6492         int delta;
6493         indx_t           i, numkeys, ptr;
6494
6495         node = NODEPTR(mp, indx);
6496         sp = (MDB_page *)NODEDATA(node);
6497         osize = NODEDSZ(node);
6498
6499         delta = sp->mp_upper - sp->mp_lower;
6500         SETDSZ(node, osize - delta);
6501         xp = (MDB_page *)((char *)sp + delta);
6502
6503         /* shift subpage upward */
6504         if (IS_LEAF2(sp)) {
6505                 nsize = NUMKEYS(sp) * sp->mp_pad;
6506                 memmove(METADATA(xp), METADATA(sp), nsize);
6507         } else {
6508                 int i;
6509                 nsize = osize - sp->mp_upper;
6510                 numkeys = NUMKEYS(sp);
6511                 for (i=numkeys-1; i>=0; i--)
6512                         xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6513         }
6514         xp->mp_upper = sp->mp_lower;
6515         xp->mp_lower = sp->mp_lower;
6516         xp->mp_flags = sp->mp_flags;
6517         xp->mp_pad = sp->mp_pad;
6518         COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6519
6520         /* shift lower nodes upward */
6521         ptr = mp->mp_ptrs[indx];
6522         numkeys = NUMKEYS(mp);
6523         for (i = 0; i < numkeys; i++) {
6524                 if (mp->mp_ptrs[i] <= ptr)
6525                         mp->mp_ptrs[i] += delta;
6526         }
6527
6528         base = (char *)mp + mp->mp_upper;
6529         memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6530         mp->mp_upper += delta;
6531 }
6532
6533 /** Initial setup of a sorted-dups cursor.
6534  * Sorted duplicates are implemented as a sub-database for the given key.
6535  * The duplicate data items are actually keys of the sub-database.
6536  * Operations on the duplicate data items are performed using a sub-cursor
6537  * initialized when the sub-database is first accessed. This function does
6538  * the preliminary setup of the sub-cursor, filling in the fields that
6539  * depend only on the parent DB.
6540  * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6541  */
6542 static void
6543 mdb_xcursor_init0(MDB_cursor *mc)
6544 {
6545         MDB_xcursor *mx = mc->mc_xcursor;
6546
6547         mx->mx_cursor.mc_xcursor = NULL;
6548         mx->mx_cursor.mc_txn = mc->mc_txn;
6549         mx->mx_cursor.mc_db = &mx->mx_db;
6550         mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6551         mx->mx_cursor.mc_dbi = mc->mc_dbi;
6552         mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6553         mx->mx_cursor.mc_snum = 0;
6554         mx->mx_cursor.mc_top = 0;
6555         mx->mx_cursor.mc_flags = C_SUB;
6556         mx->mx_dbx.md_name.mv_size = 0;
6557         mx->mx_dbx.md_name.mv_data = NULL;
6558         mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6559         mx->mx_dbx.md_dcmp = NULL;
6560         mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6561 }
6562
6563 /** Final setup of a sorted-dups cursor.
6564  *      Sets up the fields that depend on the data from the main cursor.
6565  * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6566  * @param[in] node The data containing the #MDB_db record for the
6567  * sorted-dup database.
6568  */
6569 static void
6570 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6571 {
6572         MDB_xcursor *mx = mc->mc_xcursor;
6573
6574         if (node->mn_flags & F_SUBDATA) {
6575                 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6576                 mx->mx_cursor.mc_pg[0] = 0;
6577                 mx->mx_cursor.mc_snum = 0;
6578                 mx->mx_cursor.mc_top = 0;
6579                 mx->mx_cursor.mc_flags = C_SUB;
6580         } else {
6581                 MDB_page *fp = NODEDATA(node);
6582                 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6583                 mx->mx_db.md_flags = 0;
6584                 mx->mx_db.md_depth = 1;
6585                 mx->mx_db.md_branch_pages = 0;
6586                 mx->mx_db.md_leaf_pages = 1;
6587                 mx->mx_db.md_overflow_pages = 0;
6588                 mx->mx_db.md_entries = NUMKEYS(fp);
6589                 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6590                 mx->mx_cursor.mc_snum = 1;
6591                 mx->mx_cursor.mc_top = 0;
6592                 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6593                 mx->mx_cursor.mc_pg[0] = fp;
6594                 mx->mx_cursor.mc_ki[0] = 0;
6595                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6596                         mx->mx_db.md_flags = MDB_DUPFIXED;
6597                         mx->mx_db.md_pad = fp->mp_pad;
6598                         if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6599                                 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6600                 }
6601         }
6602         DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
6603                 mx->mx_db.md_root));
6604         mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
6605 #if UINT_MAX < SIZE_MAX
6606         if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6607 #ifdef MISALIGNED_OK
6608                 mx->mx_dbx.md_cmp = mdb_cmp_long;
6609 #else
6610                 mx->mx_dbx.md_cmp = mdb_cmp_cint;
6611 #endif
6612 #endif
6613 }
6614
6615 /** Initialize a cursor for a given transaction and database. */
6616 static void
6617 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6618 {
6619         mc->mc_next = NULL;
6620         mc->mc_backup = NULL;
6621         mc->mc_dbi = dbi;
6622         mc->mc_txn = txn;
6623         mc->mc_db = &txn->mt_dbs[dbi];
6624         mc->mc_dbx = &txn->mt_dbxs[dbi];
6625         mc->mc_dbflag = &txn->mt_dbflags[dbi];
6626         mc->mc_snum = 0;
6627         mc->mc_top = 0;
6628         mc->mc_pg[0] = 0;
6629         mc->mc_flags = 0;
6630         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6631                 assert(mx != NULL);
6632                 mc->mc_xcursor = mx;
6633                 mdb_xcursor_init0(mc);
6634         } else {
6635                 mc->mc_xcursor = NULL;
6636         }
6637         if (*mc->mc_dbflag & DB_STALE) {
6638                 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6639         }
6640 }
6641
6642 int
6643 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6644 {
6645         MDB_cursor      *mc;
6646         size_t size = sizeof(MDB_cursor);
6647
6648         if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
6649                 return EINVAL;
6650
6651         if (txn->mt_flags & MDB_TXN_ERROR)
6652                 return MDB_BAD_TXN;
6653
6654         /* Allow read access to the freelist */
6655         if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6656                 return EINVAL;
6657
6658         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6659                 size += sizeof(MDB_xcursor);
6660
6661         if ((mc = malloc(size)) != NULL) {
6662                 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6663                 if (txn->mt_cursors) {
6664                         mc->mc_next = txn->mt_cursors[dbi];
6665                         txn->mt_cursors[dbi] = mc;
6666                         mc->mc_flags |= C_UNTRACK;
6667                 }
6668         } else {
6669                 return ENOMEM;
6670         }
6671
6672         *ret = mc;
6673
6674         return MDB_SUCCESS;
6675 }
6676
6677 int
6678 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6679 {
6680         if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
6681                 return EINVAL;
6682
6683         if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6684                 return EINVAL;
6685
6686         mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6687         return MDB_SUCCESS;
6688 }
6689
6690 /* Return the count of duplicate data items for the current key */
6691 int
6692 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6693 {
6694         MDB_node        *leaf;
6695
6696         if (mc == NULL || countp == NULL)
6697                 return EINVAL;
6698
6699         if (mc->mc_xcursor == NULL)
6700                 return MDB_INCOMPATIBLE;
6701
6702         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6703         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6704                 *countp = 1;
6705         } else {
6706                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
6707                         return EINVAL;
6708
6709                 *countp = mc->mc_xcursor->mx_db.md_entries;
6710         }
6711         return MDB_SUCCESS;
6712 }
6713
6714 void
6715 mdb_cursor_close(MDB_cursor *mc)
6716 {
6717         if (mc && !mc->mc_backup) {
6718                 /* remove from txn, if tracked */
6719                 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
6720                         MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
6721                         while (*prev && *prev != mc) prev = &(*prev)->mc_next;
6722                         if (*prev == mc)
6723                                 *prev = mc->mc_next;
6724                 }
6725                 free(mc);
6726         }
6727 }
6728
6729 MDB_txn *
6730 mdb_cursor_txn(MDB_cursor *mc)
6731 {
6732         if (!mc) return NULL;
6733         return mc->mc_txn;
6734 }
6735
6736 MDB_dbi
6737 mdb_cursor_dbi(MDB_cursor *mc)
6738 {
6739         assert(mc != NULL);
6740         return mc->mc_dbi;
6741 }
6742
6743 /** Replace the key for a node with a new key.
6744  * @param[in] mc Cursor pointing to the node to operate on.
6745  * @param[in] key The new key to use.
6746  * @return 0 on success, non-zero on failure.
6747  */
6748 static int
6749 mdb_update_key(MDB_cursor *mc, MDB_val *key)
6750 {
6751         MDB_page                *mp;
6752         MDB_node                *node;
6753         char                    *base;
6754         size_t                   len;
6755         int                      delta, delta0;
6756         indx_t                   ptr, i, numkeys, indx;
6757         DKBUF;
6758
6759         indx = mc->mc_ki[mc->mc_top];
6760         mp = mc->mc_pg[mc->mc_top];
6761         node = NODEPTR(mp, indx);
6762         ptr = mp->mp_ptrs[indx];
6763 #if MDB_DEBUG
6764         {
6765                 MDB_val k2;
6766                 char kbuf2[(MDB_MAXKEYSIZE*2+1)];
6767                 k2.mv_data = NODEKEY(node);
6768                 k2.mv_size = node->mn_ksize;
6769                 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
6770                         indx, ptr,
6771                         mdb_dkey(&k2, kbuf2),
6772                         DKEY(key),
6773                         mp->mp_pgno));
6774         }
6775 #endif
6776
6777         delta0 = delta = key->mv_size - node->mn_ksize;
6778
6779         /* Must be 2-byte aligned. If new key is
6780          * shorter by 1, the shift will be skipped.
6781          */
6782         delta += (delta & 1);
6783         if (delta) {
6784                 if (delta > 0 && SIZELEFT(mp) < delta) {
6785                         pgno_t pgno;
6786                         /* not enough space left, do a delete and split */
6787                         DPRINTF(("Not enough room, delta = %d, splitting...", delta));
6788                         pgno = NODEPGNO(node);
6789                         mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6790                         return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
6791                 }
6792
6793                 numkeys = NUMKEYS(mp);
6794                 for (i = 0; i < numkeys; i++) {
6795                         if (mp->mp_ptrs[i] <= ptr)
6796                                 mp->mp_ptrs[i] -= delta;
6797                 }
6798
6799                 base = (char *)mp + mp->mp_upper;
6800                 len = ptr - mp->mp_upper + NODESIZE;
6801                 memmove(base - delta, base, len);
6802                 mp->mp_upper -= delta;
6803
6804                 node = NODEPTR(mp, indx);
6805         }
6806
6807         /* But even if no shift was needed, update ksize */
6808         if (delta0)
6809                 node->mn_ksize = key->mv_size;
6810
6811         if (key->mv_size)
6812                 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6813
6814         return MDB_SUCCESS;
6815 }
6816
6817 static void
6818 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
6819
6820 /** Move a node from csrc to cdst.
6821  */
6822 static int
6823 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
6824 {
6825         MDB_node                *srcnode;
6826         MDB_val          key, data;
6827         pgno_t  srcpg;
6828         MDB_cursor mn;
6829         int                      rc;
6830         unsigned short flags;
6831
6832         DKBUF;
6833
6834         /* Mark src and dst as dirty. */
6835         if ((rc = mdb_page_touch(csrc)) ||
6836             (rc = mdb_page_touch(cdst)))
6837                 return rc;
6838
6839         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6840                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);        /* fake */
6841                 key.mv_size = csrc->mc_db->md_pad;
6842                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6843                 data.mv_size = 0;
6844                 data.mv_data = NULL;
6845                 srcpg = 0;
6846                 flags = 0;
6847         } else {
6848                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
6849                 assert(!((size_t)srcnode&1));
6850                 srcpg = NODEPGNO(srcnode);
6851                 flags = srcnode->mn_flags;
6852                 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6853                         unsigned int snum = csrc->mc_snum;
6854                         MDB_node *s2;
6855                         /* must find the lowest key below src */
6856                         mdb_page_search_lowest(csrc);
6857                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6858                                 key.mv_size = csrc->mc_db->md_pad;
6859                                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6860                         } else {
6861                                 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6862                                 key.mv_size = NODEKSZ(s2);
6863                                 key.mv_data = NODEKEY(s2);
6864                         }
6865                         csrc->mc_snum = snum--;
6866                         csrc->mc_top = snum;
6867                 } else {
6868                         key.mv_size = NODEKSZ(srcnode);
6869                         key.mv_data = NODEKEY(srcnode);
6870                 }
6871                 data.mv_size = NODEDSZ(srcnode);
6872                 data.mv_data = NODEDATA(srcnode);
6873         }
6874         if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
6875                 unsigned int snum = cdst->mc_snum;
6876                 MDB_node *s2;
6877                 MDB_val bkey;
6878                 /* must find the lowest key below dst */
6879                 mdb_page_search_lowest(cdst);
6880                 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
6881                         bkey.mv_size = cdst->mc_db->md_pad;
6882                         bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
6883                 } else {
6884                         s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6885                         bkey.mv_size = NODEKSZ(s2);
6886                         bkey.mv_data = NODEKEY(s2);
6887                 }
6888                 cdst->mc_snum = snum--;
6889                 cdst->mc_top = snum;
6890                 mdb_cursor_copy(cdst, &mn);
6891                 mn.mc_ki[snum] = 0;
6892                 rc = mdb_update_key(&mn, &bkey);
6893                 if (rc)
6894                         return rc;
6895         }
6896
6897         DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
6898             IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
6899             csrc->mc_ki[csrc->mc_top],
6900                 DKEY(&key),
6901             csrc->mc_pg[csrc->mc_top]->mp_pgno,
6902             cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
6903
6904         /* Add the node to the destination page.
6905          */
6906         rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
6907         if (rc != MDB_SUCCESS)
6908                 return rc;
6909
6910         /* Delete the node from the source page.
6911          */
6912         mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6913
6914         {
6915                 /* Adjust other cursors pointing to mp */
6916                 MDB_cursor *m2, *m3;
6917                 MDB_dbi dbi = csrc->mc_dbi;
6918                 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
6919
6920                 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6921                         if (csrc->mc_flags & C_SUB)
6922                                 m3 = &m2->mc_xcursor->mx_cursor;
6923                         else
6924                                 m3 = m2;
6925                         if (m3 == csrc) continue;
6926                         if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
6927                                 csrc->mc_ki[csrc->mc_top]) {
6928                                 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
6929                                 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
6930                         }
6931                 }
6932         }
6933
6934         /* Update the parent separators.
6935          */
6936         if (csrc->mc_ki[csrc->mc_top] == 0) {
6937                 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
6938                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6939                                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6940                         } else {
6941                                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6942                                 key.mv_size = NODEKSZ(srcnode);
6943                                 key.mv_data = NODEKEY(srcnode);
6944                         }
6945                         DPRINTF(("update separator for source page %"Z"u to [%s]",
6946                                 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
6947                         mdb_cursor_copy(csrc, &mn);
6948                         mn.mc_snum--;
6949                         mn.mc_top--;
6950                         if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6951                                 return rc;
6952                 }
6953                 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6954                         MDB_val  nullkey;
6955                         indx_t  ix = csrc->mc_ki[csrc->mc_top];
6956                         nullkey.mv_size = 0;
6957                         csrc->mc_ki[csrc->mc_top] = 0;
6958                         rc = mdb_update_key(csrc, &nullkey);
6959                         csrc->mc_ki[csrc->mc_top] = ix;
6960                         assert(rc == MDB_SUCCESS);
6961                 }
6962         }
6963
6964         if (cdst->mc_ki[cdst->mc_top] == 0) {
6965                 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
6966                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6967                                 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
6968                         } else {
6969                                 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6970                                 key.mv_size = NODEKSZ(srcnode);
6971                                 key.mv_data = NODEKEY(srcnode);
6972                         }
6973                         DPRINTF(("update separator for destination page %"Z"u to [%s]",
6974                                 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
6975                         mdb_cursor_copy(cdst, &mn);
6976                         mn.mc_snum--;
6977                         mn.mc_top--;
6978                         if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6979                                 return rc;
6980                 }
6981                 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
6982                         MDB_val  nullkey;
6983                         indx_t  ix = cdst->mc_ki[cdst->mc_top];
6984                         nullkey.mv_size = 0;
6985                         cdst->mc_ki[cdst->mc_top] = 0;
6986                         rc = mdb_update_key(cdst, &nullkey);
6987                         cdst->mc_ki[cdst->mc_top] = ix;
6988                         assert(rc == MDB_SUCCESS);
6989                 }
6990         }
6991
6992         return MDB_SUCCESS;
6993 }
6994
6995 /** Merge one page into another.
6996  *  The nodes from the page pointed to by \b csrc will
6997  *      be copied to the page pointed to by \b cdst and then
6998  *      the \b csrc page will be freed.
6999  * @param[in] csrc Cursor pointing to the source page.
7000  * @param[in] cdst Cursor pointing to the destination page.
7001  */
7002 static int
7003 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7004 {
7005         int                      rc;
7006         indx_t                   i, j;
7007         MDB_node                *srcnode;
7008         MDB_val          key, data;
7009         unsigned        nkeys;
7010
7011         DPRINTF(("merging page %"Z"u into %"Z"u", csrc->mc_pg[csrc->mc_top]->mp_pgno,
7012                 cdst->mc_pg[cdst->mc_top]->mp_pgno));
7013
7014         assert(csrc->mc_snum > 1);      /* can't merge root page */
7015         assert(cdst->mc_snum > 1);
7016
7017         /* Mark dst as dirty. */
7018         if ((rc = mdb_page_touch(cdst)))
7019                 return rc;
7020
7021         /* Move all nodes from src to dst.
7022          */
7023         j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
7024         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7025                 key.mv_size = csrc->mc_db->md_pad;
7026                 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
7027                 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
7028                         rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7029                         if (rc != MDB_SUCCESS)
7030                                 return rc;
7031                         key.mv_data = (char *)key.mv_data + key.mv_size;
7032                 }
7033         } else {
7034                 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
7035                         srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
7036                         if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7037                                 unsigned int snum = csrc->mc_snum;
7038                                 MDB_node *s2;
7039                                 /* must find the lowest key below src */
7040                                 mdb_page_search_lowest(csrc);
7041                                 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7042                                         key.mv_size = csrc->mc_db->md_pad;
7043                                         key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7044                                 } else {
7045                                         s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7046                                         key.mv_size = NODEKSZ(s2);
7047                                         key.mv_data = NODEKEY(s2);
7048                                 }
7049                                 csrc->mc_snum = snum--;
7050                                 csrc->mc_top = snum;
7051                         } else {
7052                                 key.mv_size = srcnode->mn_ksize;
7053                                 key.mv_data = NODEKEY(srcnode);
7054                         }
7055
7056                         data.mv_size = NODEDSZ(srcnode);
7057                         data.mv_data = NODEDATA(srcnode);
7058                         rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7059                         if (rc != MDB_SUCCESS)
7060                                 return rc;
7061                 }
7062         }
7063
7064         DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7065             cdst->mc_pg[cdst->mc_top]->mp_pgno, NUMKEYS(cdst->mc_pg[cdst->mc_top]),
7066                 (float)PAGEFILL(cdst->mc_txn->mt_env, cdst->mc_pg[cdst->mc_top]) / 10));
7067
7068         /* Unlink the src page from parent and add to free list.
7069          */
7070         mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
7071         if (csrc->mc_ki[csrc->mc_top-1] == 0) {
7072                 key.mv_size = 0;
7073                 csrc->mc_top--;
7074                 rc = mdb_update_key(csrc, &key);
7075                 csrc->mc_top++;
7076                 if (rc)
7077                         return rc;
7078         }
7079
7080         rc = mdb_midl_append(&csrc->mc_txn->mt_free_pgs,
7081                 csrc->mc_pg[csrc->mc_top]->mp_pgno);
7082         if (rc)
7083                 return rc;
7084         if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
7085                 csrc->mc_db->md_leaf_pages--;
7086         else
7087                 csrc->mc_db->md_branch_pages--;
7088         {
7089                 /* Adjust other cursors pointing to mp */
7090                 MDB_cursor *m2, *m3;
7091                 MDB_dbi dbi = csrc->mc_dbi;
7092                 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
7093
7094                 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7095                         if (csrc->mc_flags & C_SUB)
7096                                 m3 = &m2->mc_xcursor->mx_cursor;
7097                         else
7098                                 m3 = m2;
7099                         if (m3 == csrc) continue;
7100                         if (m3->mc_snum < csrc->mc_snum) continue;
7101                         if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
7102                                 m3->mc_pg[csrc->mc_top] = mp;
7103                                 m3->mc_ki[csrc->mc_top] += nkeys;
7104                         }
7105                 }
7106         }
7107         mdb_cursor_pop(csrc);
7108
7109         return mdb_rebalance(csrc);
7110 }
7111
7112 /** Copy the contents of a cursor.
7113  * @param[in] csrc The cursor to copy from.
7114  * @param[out] cdst The cursor to copy to.
7115  */
7116 static void
7117 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7118 {
7119         unsigned int i;
7120
7121         cdst->mc_txn = csrc->mc_txn;
7122         cdst->mc_dbi = csrc->mc_dbi;
7123         cdst->mc_db  = csrc->mc_db;
7124         cdst->mc_dbx = csrc->mc_dbx;
7125         cdst->mc_snum = csrc->mc_snum;
7126         cdst->mc_top = csrc->mc_top;
7127         cdst->mc_flags = csrc->mc_flags;
7128
7129         for (i=0; i<csrc->mc_snum; i++) {
7130                 cdst->mc_pg[i] = csrc->mc_pg[i];
7131                 cdst->mc_ki[i] = csrc->mc_ki[i];
7132         }
7133 }
7134
7135 /** Rebalance the tree after a delete operation.
7136  * @param[in] mc Cursor pointing to the page where rebalancing
7137  * should begin.
7138  * @return 0 on success, non-zero on failure.
7139  */
7140 static int
7141 mdb_rebalance(MDB_cursor *mc)
7142 {
7143         MDB_node        *node;
7144         int rc;
7145         unsigned int ptop, minkeys;
7146         MDB_cursor      mn;
7147
7148         minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7149 #if MDB_DEBUG
7150         {
7151         pgno_t pgno;
7152         COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
7153         DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7154             IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7155             pgno, NUMKEYS(mc->mc_pg[mc->mc_top]),
7156                 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7157         }
7158 #endif
7159
7160         if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7161                 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7162 #if MDB_DEBUG
7163                 pgno_t pgno;
7164                 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
7165                 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7166                     pgno));
7167 #endif
7168                 return MDB_SUCCESS;
7169         }
7170
7171         if (mc->mc_snum < 2) {
7172                 MDB_page *mp = mc->mc_pg[0];
7173                 if (IS_SUBP(mp)) {
7174                         DPUTS("Can't rebalance a subpage, ignoring");
7175                         return MDB_SUCCESS;
7176                 }
7177                 if (NUMKEYS(mp) == 0) {
7178                         DPUTS("tree is completely empty");
7179                         mc->mc_db->md_root = P_INVALID;
7180                         mc->mc_db->md_depth = 0;
7181                         mc->mc_db->md_leaf_pages = 0;
7182                         rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7183                         if (rc)
7184                                 return rc;
7185                         /* Adjust cursors pointing to mp */
7186                         mc->mc_snum = 0;
7187                         mc->mc_top = 0;
7188                         mc->mc_flags &= ~C_INITIALIZED;
7189                         {
7190                                 MDB_cursor *m2, *m3;
7191                                 MDB_dbi dbi = mc->mc_dbi;
7192
7193                                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7194                                         if (mc->mc_flags & C_SUB)
7195                                                 m3 = &m2->mc_xcursor->mx_cursor;
7196                                         else
7197                                                 m3 = m2;
7198                                         if (m3->mc_snum < mc->mc_snum) continue;
7199                                         if (m3->mc_pg[0] == mp) {
7200                                                 m3->mc_snum = 0;
7201                                                 m3->mc_top = 0;
7202                                                 m3->mc_flags &= ~C_INITIALIZED;
7203                                         }
7204                                 }
7205                         }
7206                 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7207                         DPUTS("collapsing root page!");
7208                         rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7209                         if (rc)
7210                                 return rc;
7211                         mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7212                         rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7213                         if (rc)
7214                                 return rc;
7215                         mc->mc_db->md_depth--;
7216                         mc->mc_db->md_branch_pages--;
7217                         mc->mc_ki[0] = mc->mc_ki[1];
7218                         {
7219                                 /* Adjust other cursors pointing to mp */
7220                                 MDB_cursor *m2, *m3;
7221                                 MDB_dbi dbi = mc->mc_dbi;
7222
7223                                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7224                                         if (mc->mc_flags & C_SUB)
7225                                                 m3 = &m2->mc_xcursor->mx_cursor;
7226                                         else
7227                                                 m3 = m2;
7228                                         if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7229                                         if (m3->mc_pg[0] == mp) {
7230                                                 int i;
7231                                                 m3->mc_snum--;
7232                                                 m3->mc_top--;
7233                                                 for (i=0; i<m3->mc_snum; i++) {
7234                                                         m3->mc_pg[i] = m3->mc_pg[i+1];
7235                                                         m3->mc_ki[i] = m3->mc_ki[i+1];
7236                                                 }
7237                                         }
7238                                 }
7239                         }
7240                 } else
7241                         DPUTS("root page doesn't need rebalancing");
7242                 return MDB_SUCCESS;
7243         }
7244
7245         /* The parent (branch page) must have at least 2 pointers,
7246          * otherwise the tree is invalid.
7247          */
7248         ptop = mc->mc_top-1;
7249         assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
7250
7251         /* Leaf page fill factor is below the threshold.
7252          * Try to move keys from left or right neighbor, or
7253          * merge with a neighbor page.
7254          */
7255
7256         /* Find neighbors.
7257          */
7258         mdb_cursor_copy(mc, &mn);
7259         mn.mc_xcursor = NULL;
7260
7261         if (mc->mc_ki[ptop] == 0) {
7262                 /* We're the leftmost leaf in our parent.
7263                  */
7264                 DPUTS("reading right neighbor");
7265                 mn.mc_ki[ptop]++;
7266                 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7267                 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7268                 if (rc)
7269                         return rc;
7270                 mn.mc_ki[mn.mc_top] = 0;
7271                 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7272         } else {
7273                 /* There is at least one neighbor to the left.
7274                  */
7275                 DPUTS("reading left neighbor");
7276                 mn.mc_ki[ptop]--;
7277                 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7278                 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7279                 if (rc)
7280                         return rc;
7281                 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7282                 mc->mc_ki[mc->mc_top] = 0;
7283         }
7284
7285         DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7286             mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7287                 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7288
7289         /* If the neighbor page is above threshold and has enough keys,
7290          * move one key from it. Otherwise we should try to merge them.
7291          * (A branch page must never have less than 2 keys.)
7292          */
7293         minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7294         if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys)
7295                 return mdb_node_move(&mn, mc);
7296         else {
7297                 if (mc->mc_ki[ptop] == 0)
7298                         rc = mdb_page_merge(&mn, mc);
7299                 else {
7300                         mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7301                         rc = mdb_page_merge(mc, &mn);
7302                         mdb_cursor_copy(&mn, mc);
7303                 }
7304                 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
7305         }
7306         return rc;
7307 }
7308
7309 /** Complete a delete operation started by #mdb_cursor_del(). */
7310 static int
7311 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
7312 {
7313         int rc;
7314         MDB_page *mp;
7315         indx_t ki;
7316         unsigned int nkeys;
7317
7318         mp = mc->mc_pg[mc->mc_top];
7319         ki = mc->mc_ki[mc->mc_top];
7320
7321         /* add overflow pages to free list */
7322         if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7323                 MDB_page *omp;
7324                 pgno_t pg;
7325
7326                 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7327                 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
7328                         (rc = mdb_ovpage_free(mc, omp)))
7329                         return rc;
7330         }
7331         mdb_node_del(mp, ki, mc->mc_db->md_pad);
7332         mc->mc_db->md_entries--;
7333         rc = mdb_rebalance(mc);
7334         if (rc != MDB_SUCCESS)
7335                 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7336         else {
7337                 MDB_cursor *m2;
7338                 MDB_dbi dbi = mc->mc_dbi;
7339
7340                 mp = mc->mc_pg[mc->mc_top];
7341                 nkeys = NUMKEYS(mp);
7342
7343                 /* if mc points past last node in page, find next sibling */
7344                 if (mc->mc_ki[mc->mc_top] >= nkeys)
7345                         mdb_cursor_sibling(mc, 1);
7346
7347                 /* Adjust other cursors pointing to mp */
7348                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7349                         if (m2 == mc || m2->mc_snum < mc->mc_snum)
7350                                 continue;
7351                         if (!(m2->mc_flags & C_INITIALIZED))
7352                                 continue;
7353                         if (m2->mc_pg[mc->mc_top] == mp) {
7354                                 if (m2->mc_ki[mc->mc_top] >= ki) {
7355                                         m2->mc_flags |= C_DEL;
7356                                         if (m2->mc_ki[mc->mc_top] > ki)
7357                                                 m2->mc_ki[mc->mc_top]--;
7358                                 }
7359                                 if (m2->mc_ki[mc->mc_top] >= nkeys)
7360                                         mdb_cursor_sibling(m2, 1);
7361                         }
7362                 }
7363                 mc->mc_flags |= C_DEL;
7364         }
7365
7366         return rc;
7367 }
7368
7369 int
7370 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7371     MDB_val *key, MDB_val *data)
7372 {
7373         MDB_cursor mc;
7374         MDB_xcursor mx;
7375         MDB_cursor_op op;
7376         MDB_val rdata, *xdata;
7377         int              rc, exact;
7378         DKBUF;
7379
7380         assert(key != NULL);
7381
7382         DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7383
7384         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7385                 return EINVAL;
7386
7387         if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7388                 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7389
7390         if (key->mv_size > MDB_MAXKEYSIZE) {
7391                 return MDB_BAD_VALSIZE;
7392         }
7393
7394         mdb_cursor_init(&mc, txn, dbi, &mx);
7395
7396         exact = 0;
7397         if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7398                 /* must ignore any data */
7399                 data = NULL;
7400         }
7401         if (data) {
7402                 op = MDB_GET_BOTH;
7403                 rdata = *data;
7404                 xdata = &rdata;
7405         } else {
7406                 op = MDB_SET;
7407                 xdata = NULL;
7408         }
7409         rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7410         if (rc == 0) {
7411                 /* let mdb_page_split know about this cursor if needed:
7412                  * delete will trigger a rebalance; if it needs to move
7413                  * a node from one page to another, it will have to
7414                  * update the parent's separator key(s). If the new sepkey
7415                  * is larger than the current one, the parent page may
7416                  * run out of space, triggering a split. We need this
7417                  * cursor to be consistent until the end of the rebalance.
7418                  */
7419                 mc.mc_flags |= C_UNTRACK;
7420                 mc.mc_next = txn->mt_cursors[dbi];
7421                 txn->mt_cursors[dbi] = &mc;
7422                 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
7423                 txn->mt_cursors[dbi] = mc.mc_next;
7424         }
7425         return rc;
7426 }
7427
7428 /** Split a page and insert a new node.
7429  * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7430  * The cursor will be updated to point to the actual page and index where
7431  * the node got inserted after the split.
7432  * @param[in] newkey The key for the newly inserted node.
7433  * @param[in] newdata The data for the newly inserted node.
7434  * @param[in] newpgno The page number, if the new node is a branch node.
7435  * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7436  * @return 0 on success, non-zero on failure.
7437  */
7438 static int
7439 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7440         unsigned int nflags)
7441 {
7442         unsigned int flags;
7443         int              rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7444         indx_t           newindx;
7445         pgno_t           pgno = 0;
7446         int      i, j, split_indx, nkeys, pmax;
7447         MDB_env         *env = mc->mc_txn->mt_env;
7448         MDB_node        *node;
7449         MDB_val  sepkey, rkey, xdata, *rdata = &xdata;
7450         MDB_page        *copy = NULL;
7451         MDB_page        *mp, *rp, *pp;
7452         int ptop;
7453         MDB_cursor      mn;
7454         DKBUF;
7455
7456         mp = mc->mc_pg[mc->mc_top];
7457         newindx = mc->mc_ki[mc->mc_top];
7458         nkeys = NUMKEYS(mp);
7459
7460         DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
7461             IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7462             DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
7463
7464         /* Create a right sibling. */
7465         if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7466                 return rc;
7467         DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7468
7469         if (mc->mc_snum < 2) {
7470                 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7471                         return rc;
7472                 /* shift current top to make room for new parent */
7473                 mc->mc_pg[1] = mc->mc_pg[0];
7474                 mc->mc_ki[1] = mc->mc_ki[0];
7475                 mc->mc_pg[0] = pp;
7476                 mc->mc_ki[0] = 0;
7477                 mc->mc_db->md_root = pp->mp_pgno;
7478                 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7479                 mc->mc_db->md_depth++;
7480                 new_root = 1;
7481
7482                 /* Add left (implicit) pointer. */
7483                 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7484                         /* undo the pre-push */
7485                         mc->mc_pg[0] = mc->mc_pg[1];
7486                         mc->mc_ki[0] = mc->mc_ki[1];
7487                         mc->mc_db->md_root = mp->mp_pgno;
7488                         mc->mc_db->md_depth--;
7489                         return rc;
7490                 }
7491                 mc->mc_snum = 2;
7492                 mc->mc_top = 1;
7493                 ptop = 0;
7494         } else {
7495                 ptop = mc->mc_top-1;
7496                 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7497         }
7498
7499         mc->mc_flags |= C_SPLITTING;
7500         mdb_cursor_copy(mc, &mn);
7501         mn.mc_pg[mn.mc_top] = rp;
7502         mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7503
7504         if (nflags & MDB_APPEND) {
7505                 mn.mc_ki[mn.mc_top] = 0;
7506                 sepkey = *newkey;
7507                 split_indx = newindx;
7508                 nkeys = 0;
7509         } else {
7510
7511                 split_indx = (nkeys+1) / 2;
7512
7513                 if (IS_LEAF2(rp)) {
7514                         char *split, *ins;
7515                         int x;
7516                         unsigned int lsize, rsize, ksize;
7517                         /* Move half of the keys to the right sibling */
7518                         copy = NULL;
7519                         x = mc->mc_ki[mc->mc_top] - split_indx;
7520                         ksize = mc->mc_db->md_pad;
7521                         split = LEAF2KEY(mp, split_indx, ksize);
7522                         rsize = (nkeys - split_indx) * ksize;
7523                         lsize = (nkeys - split_indx) * sizeof(indx_t);
7524                         mp->mp_lower -= lsize;
7525                         rp->mp_lower += lsize;
7526                         mp->mp_upper += rsize - lsize;
7527                         rp->mp_upper -= rsize - lsize;
7528                         sepkey.mv_size = ksize;
7529                         if (newindx == split_indx) {
7530                                 sepkey.mv_data = newkey->mv_data;
7531                         } else {
7532                                 sepkey.mv_data = split;
7533                         }
7534                         if (x<0) {
7535                                 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7536                                 memcpy(rp->mp_ptrs, split, rsize);
7537                                 sepkey.mv_data = rp->mp_ptrs;
7538                                 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7539                                 memcpy(ins, newkey->mv_data, ksize);
7540                                 mp->mp_lower += sizeof(indx_t);
7541                                 mp->mp_upper -= ksize - sizeof(indx_t);
7542                         } else {
7543                                 if (x)
7544                                         memcpy(rp->mp_ptrs, split, x * ksize);
7545                                 ins = LEAF2KEY(rp, x, ksize);
7546                                 memcpy(ins, newkey->mv_data, ksize);
7547                                 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7548                                 rp->mp_lower += sizeof(indx_t);
7549                                 rp->mp_upper -= ksize - sizeof(indx_t);
7550                                 mc->mc_ki[mc->mc_top] = x;
7551                                 mc->mc_pg[mc->mc_top] = rp;
7552                         }
7553                 } else {
7554                         int psize, nsize, k;
7555                         /* Maximum free space in an empty page */
7556                         pmax = env->me_psize - PAGEHDRSZ;
7557                         if (IS_LEAF(mp))
7558                                 nsize = mdb_leaf_size(env, newkey, newdata);
7559                         else
7560                                 nsize = mdb_branch_size(env, newkey);
7561                         nsize += nsize & 1;
7562
7563                         /* grab a page to hold a temporary copy */
7564                         copy = mdb_page_malloc(mc->mc_txn, 1);
7565                         if (copy == NULL)
7566                                 return ENOMEM;
7567                         copy->mp_pgno  = mp->mp_pgno;
7568                         copy->mp_flags = mp->mp_flags;
7569                         copy->mp_lower = PAGEHDRSZ;
7570                         copy->mp_upper = env->me_psize;
7571
7572                         /* prepare to insert */
7573                         for (i=0, j=0; i<nkeys; i++) {
7574                                 if (i == newindx) {
7575                                         copy->mp_ptrs[j++] = 0;
7576                                 }
7577                                 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
7578                         }
7579
7580                         /* When items are relatively large the split point needs
7581                          * to be checked, because being off-by-one will make the
7582                          * difference between success or failure in mdb_node_add.
7583                          *
7584                          * It's also relevant if a page happens to be laid out
7585                          * such that one half of its nodes are all "small" and
7586                          * the other half of its nodes are "large." If the new
7587                          * item is also "large" and falls on the half with
7588                          * "large" nodes, it also may not fit.
7589                          *
7590                          * As a final tweak, if the new item goes on the last
7591                          * spot on the page (and thus, onto the new page), bias
7592                          * the split so the new page is emptier than the old page.
7593                          * This yields better packing during sequential inserts.
7594                          */
7595                         if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
7596                                 /* Find split point */
7597                                 psize = 0;
7598                                 if (newindx <= split_indx || newindx >= nkeys) {
7599                                         i = 0; j = 1;
7600                                         k = newindx >= nkeys ? nkeys : split_indx+2;
7601                                 } else {
7602                                         i = nkeys; j = -1;
7603                                         k = split_indx-1;
7604                                 }
7605                                 for (; i!=k; i+=j) {
7606                                         if (i == newindx) {
7607                                                 psize += nsize;
7608                                                 node = NULL;
7609                                         } else {
7610                                                 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7611                                                 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7612                                                 if (IS_LEAF(mp)) {
7613                                                         if (F_ISSET(node->mn_flags, F_BIGDATA))
7614                                                                 psize += sizeof(pgno_t);
7615                                                         else
7616                                                                 psize += NODEDSZ(node);
7617                                                 }
7618                                                 psize += psize & 1;
7619                                         }
7620                                         if (psize > pmax || i == k-j) {
7621                                                 split_indx = i + (j<0);
7622                                                 break;
7623                                         }
7624                                 }
7625                         }
7626                         if (split_indx == newindx) {
7627                                 sepkey.mv_size = newkey->mv_size;
7628                                 sepkey.mv_data = newkey->mv_data;
7629                         } else {
7630                                 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx]);
7631                                 sepkey.mv_size = node->mn_ksize;
7632                                 sepkey.mv_data = NODEKEY(node);
7633                         }
7634                 }
7635         }
7636
7637         DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
7638
7639         /* Copy separator key to the parent.
7640          */
7641         if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
7642                 mn.mc_snum--;
7643                 mn.mc_top--;
7644                 did_split = 1;
7645                 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7646
7647                 /* root split? */
7648                 if (mn.mc_snum == mc->mc_snum) {
7649                         mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7650                         mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7651                         mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7652                         mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7653                         mc->mc_snum++;
7654                         mc->mc_top++;
7655                         ptop++;
7656                 }
7657                 /* Right page might now have changed parent.
7658                  * Check if left page also changed parent.
7659                  */
7660                 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7661                     mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7662                         for (i=0; i<ptop; i++) {
7663                                 mc->mc_pg[i] = mn.mc_pg[i];
7664                                 mc->mc_ki[i] = mn.mc_ki[i];
7665                         }
7666                         mc->mc_pg[ptop] = mn.mc_pg[ptop];
7667                         mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7668                 }
7669         } else {
7670                 mn.mc_top--;
7671                 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7672                 mn.mc_top++;
7673         }
7674         mc->mc_flags ^= C_SPLITTING;
7675         if (rc != MDB_SUCCESS) {
7676                 return rc;
7677         }
7678         if (nflags & MDB_APPEND) {
7679                 mc->mc_pg[mc->mc_top] = rp;
7680                 mc->mc_ki[mc->mc_top] = 0;
7681                 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
7682                 if (rc)
7683                         return rc;
7684                 for (i=0; i<mc->mc_top; i++)
7685                         mc->mc_ki[i] = mn.mc_ki[i];
7686         } else if (!IS_LEAF2(mp)) {
7687                 /* Move nodes */
7688                 mc->mc_pg[mc->mc_top] = rp;
7689                 i = split_indx;
7690                 j = 0;
7691                 do {
7692                         if (i == newindx) {
7693                                 rkey.mv_data = newkey->mv_data;
7694                                 rkey.mv_size = newkey->mv_size;
7695                                 if (IS_LEAF(mp)) {
7696                                         rdata = newdata;
7697                                 } else
7698                                         pgno = newpgno;
7699                                 flags = nflags;
7700                                 /* Update index for the new key. */
7701                                 mc->mc_ki[mc->mc_top] = j;
7702                         } else {
7703                                 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7704                                 rkey.mv_data = NODEKEY(node);
7705                                 rkey.mv_size = node->mn_ksize;
7706                                 if (IS_LEAF(mp)) {
7707                                         xdata.mv_data = NODEDATA(node);
7708                                         xdata.mv_size = NODEDSZ(node);
7709                                         rdata = &xdata;
7710                                 } else
7711                                         pgno = NODEPGNO(node);
7712                                 flags = node->mn_flags;
7713                         }
7714
7715                         if (!IS_LEAF(mp) && j == 0) {
7716                                 /* First branch index doesn't need key data. */
7717                                 rkey.mv_size = 0;
7718                         }
7719
7720                         rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
7721                         if (rc) {
7722                                 /* return tmp page to freelist */
7723                                 mdb_page_free(env, copy);
7724                                 return rc;
7725                         }
7726                         if (i == nkeys) {
7727                                 i = 0;
7728                                 j = 0;
7729                                 mc->mc_pg[mc->mc_top] = copy;
7730                         } else {
7731                                 i++;
7732                                 j++;
7733                         }
7734                 } while (i != split_indx);
7735
7736                 nkeys = NUMKEYS(copy);
7737                 for (i=0; i<nkeys; i++)
7738                         mp->mp_ptrs[i] = copy->mp_ptrs[i];
7739                 mp->mp_lower = copy->mp_lower;
7740                 mp->mp_upper = copy->mp_upper;
7741                 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
7742                         env->me_psize - copy->mp_upper);
7743
7744                 /* reset back to original page */
7745                 if (newindx < split_indx) {
7746                         mc->mc_pg[mc->mc_top] = mp;
7747                         if (nflags & MDB_RESERVE) {
7748                                 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7749                                 if (!(node->mn_flags & F_BIGDATA))
7750                                         newdata->mv_data = NODEDATA(node);
7751                         }
7752                 } else {
7753                         mc->mc_pg[mc->mc_top] = rp;
7754                         mc->mc_ki[ptop]++;
7755                         /* Make sure mc_ki is still valid.
7756                          */
7757                         if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7758                                 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7759                                 for (i=0; i<ptop; i++) {
7760                                         mc->mc_pg[i] = mn.mc_pg[i];
7761                                         mc->mc_ki[i] = mn.mc_ki[i];
7762                                 }
7763                                 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7764                                 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7765                         }
7766                 }
7767                 /* return tmp page to freelist */
7768                 mdb_page_free(env, copy);
7769         }
7770
7771         {
7772                 /* Adjust other cursors pointing to mp */
7773                 MDB_cursor *m2, *m3;
7774                 MDB_dbi dbi = mc->mc_dbi;
7775                 int fixup = NUMKEYS(mp);
7776
7777                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7778                         if (mc->mc_flags & C_SUB)
7779                                 m3 = &m2->mc_xcursor->mx_cursor;
7780                         else
7781                                 m3 = m2;
7782                         if (m3 == mc)
7783                                 continue;
7784                         if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7785                                 continue;
7786                         if (m3->mc_flags & C_SPLITTING)
7787                                 continue;
7788                         if (new_root) {
7789                                 int k;
7790                                 /* root split */
7791                                 for (k=m3->mc_top; k>=0; k--) {
7792                                         m3->mc_ki[k+1] = m3->mc_ki[k];
7793                                         m3->mc_pg[k+1] = m3->mc_pg[k];
7794                                 }
7795                                 if (m3->mc_ki[0] >= split_indx) {
7796                                         m3->mc_ki[0] = 1;
7797                                 } else {
7798                                         m3->mc_ki[0] = 0;
7799                                 }
7800                                 m3->mc_pg[0] = mc->mc_pg[0];
7801                                 m3->mc_snum++;
7802                                 m3->mc_top++;
7803                         }
7804                         if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
7805                                 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
7806                                         m3->mc_ki[mc->mc_top]++;
7807                                 if (m3->mc_ki[mc->mc_top] >= fixup) {
7808                                         m3->mc_pg[mc->mc_top] = rp;
7809                                         m3->mc_ki[mc->mc_top] -= fixup;
7810                                         m3->mc_ki[ptop] = mn.mc_ki[ptop];
7811                                 }
7812                         } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
7813                                 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
7814                                 m3->mc_ki[ptop]++;
7815                         }
7816                 }
7817         }
7818         DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
7819         return rc;
7820 }
7821
7822 int
7823 mdb_put(MDB_txn *txn, MDB_dbi dbi,
7824     MDB_val *key, MDB_val *data, unsigned int flags)
7825 {
7826         MDB_cursor mc;
7827         MDB_xcursor mx;
7828
7829         assert(key != NULL);
7830         assert(data != NULL);
7831
7832         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7833                 return EINVAL;
7834
7835         if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
7836                 return EINVAL;
7837
7838         mdb_cursor_init(&mc, txn, dbi, &mx);
7839         return mdb_cursor_put(&mc, key, data, flags);
7840 }
7841
7842 int
7843 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
7844 {
7845         if ((flag & CHANGEABLE) != flag)
7846                 return EINVAL;
7847         if (onoff)
7848                 env->me_flags |= flag;
7849         else
7850                 env->me_flags &= ~flag;
7851         return MDB_SUCCESS;
7852 }
7853
7854 int
7855 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
7856 {
7857         if (!env || !arg)
7858                 return EINVAL;
7859
7860         *arg = env->me_flags;
7861         return MDB_SUCCESS;
7862 }
7863
7864 int
7865 mdb_env_get_path(MDB_env *env, const char **arg)
7866 {
7867         if (!env || !arg)
7868                 return EINVAL;
7869
7870         *arg = env->me_path;
7871         return MDB_SUCCESS;
7872 }
7873
7874 int
7875 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
7876 {
7877         if (!env || !arg)
7878                 return EINVAL;
7879
7880         *arg = env->me_fd;
7881         return MDB_SUCCESS;
7882 }
7883
7884 /** Common code for #mdb_stat() and #mdb_env_stat().
7885  * @param[in] env the environment to operate in.
7886  * @param[in] db the #MDB_db record containing the stats to return.
7887  * @param[out] arg the address of an #MDB_stat structure to receive the stats.
7888  * @return 0, this function always succeeds.
7889  */
7890 static int
7891 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
7892 {
7893         arg->ms_psize = env->me_psize;
7894         arg->ms_depth = db->md_depth;
7895         arg->ms_branch_pages = db->md_branch_pages;
7896         arg->ms_leaf_pages = db->md_leaf_pages;
7897         arg->ms_overflow_pages = db->md_overflow_pages;
7898         arg->ms_entries = db->md_entries;
7899
7900         return MDB_SUCCESS;
7901 }
7902 int
7903 mdb_env_stat(MDB_env *env, MDB_stat *arg)
7904 {
7905         int toggle;
7906
7907         if (env == NULL || arg == NULL)
7908                 return EINVAL;
7909
7910         toggle = mdb_env_pick_meta(env);
7911
7912         return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
7913 }
7914
7915 int
7916 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
7917 {
7918         int toggle;
7919
7920         if (env == NULL || arg == NULL)
7921                 return EINVAL;
7922
7923         toggle = mdb_env_pick_meta(env);
7924         arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
7925         arg->me_mapsize = env->me_mapsize;
7926         arg->me_maxreaders = env->me_maxreaders;
7927
7928         /* me_numreaders may be zero if this process never used any readers. Use
7929          * the shared numreader count if it exists.
7930          */
7931         arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
7932
7933         arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
7934         arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
7935         return MDB_SUCCESS;
7936 }
7937
7938 /** Set the default comparison functions for a database.
7939  * Called immediately after a database is opened to set the defaults.
7940  * The user can then override them with #mdb_set_compare() or
7941  * #mdb_set_dupsort().
7942  * @param[in] txn A transaction handle returned by #mdb_txn_begin()
7943  * @param[in] dbi A database handle returned by #mdb_dbi_open()
7944  */
7945 static void
7946 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
7947 {
7948         uint16_t f = txn->mt_dbs[dbi].md_flags;
7949
7950         txn->mt_dbxs[dbi].md_cmp =
7951                 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
7952                 (f & MDB_INTEGERKEY) ? mdb_cmp_cint  : mdb_cmp_memn;
7953
7954         txn->mt_dbxs[dbi].md_dcmp =
7955                 !(f & MDB_DUPSORT) ? 0 :
7956                 ((f & MDB_INTEGERDUP)
7957                  ? ((f & MDB_DUPFIXED)   ? mdb_cmp_int   : mdb_cmp_cint)
7958                  : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
7959 }
7960
7961 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
7962 {
7963         MDB_val key, data;
7964         MDB_dbi i;
7965         MDB_cursor mc;
7966         int rc, dbflag, exact;
7967         unsigned int unused = 0;
7968         size_t len;
7969
7970         if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
7971                 mdb_default_cmp(txn, FREE_DBI);
7972         }
7973
7974         if ((flags & VALID_FLAGS) != flags)
7975                 return EINVAL;
7976         if (txn->mt_flags & MDB_TXN_ERROR)
7977                 return MDB_BAD_TXN;
7978
7979         /* main DB? */
7980         if (!name) {
7981                 *dbi = MAIN_DBI;
7982                 if (flags & PERSISTENT_FLAGS) {
7983                         uint16_t f2 = flags & PERSISTENT_FLAGS;
7984                         /* make sure flag changes get committed */
7985                         if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
7986                                 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
7987                                 txn->mt_flags |= MDB_TXN_DIRTY;
7988                         }
7989                 }
7990                 mdb_default_cmp(txn, MAIN_DBI);
7991                 return MDB_SUCCESS;
7992         }
7993
7994         if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
7995                 mdb_default_cmp(txn, MAIN_DBI);
7996         }
7997
7998         /* Is the DB already open? */
7999         len = strlen(name);
8000         for (i=2; i<txn->mt_numdbs; i++) {
8001                 if (!txn->mt_dbxs[i].md_name.mv_size) {
8002                         /* Remember this free slot */
8003                         if (!unused) unused = i;
8004                         continue;
8005                 }
8006                 if (len == txn->mt_dbxs[i].md_name.mv_size &&
8007                         !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
8008                         *dbi = i;
8009                         return MDB_SUCCESS;
8010                 }
8011         }
8012
8013         /* If no free slot and max hit, fail */
8014         if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
8015                 return MDB_DBS_FULL;
8016
8017         /* Cannot mix named databases with some mainDB flags */
8018         if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
8019                 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
8020
8021         /* Find the DB info */
8022         dbflag = DB_NEW|DB_VALID;
8023         exact = 0;
8024         key.mv_size = len;
8025         key.mv_data = (void *)name;
8026         mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
8027         rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
8028         if (rc == MDB_SUCCESS) {
8029                 /* make sure this is actually a DB */
8030                 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
8031                 if (!(node->mn_flags & F_SUBDATA))
8032                         return MDB_INCOMPATIBLE;
8033         } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
8034                 /* Create if requested */
8035                 MDB_db dummy;
8036                 data.mv_size = sizeof(MDB_db);
8037                 data.mv_data = &dummy;
8038                 memset(&dummy, 0, sizeof(dummy));
8039                 dummy.md_root = P_INVALID;
8040                 dummy.md_flags = flags & PERSISTENT_FLAGS;
8041                 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
8042                 dbflag |= DB_DIRTY;
8043         }
8044
8045         /* OK, got info, add to table */
8046         if (rc == MDB_SUCCESS) {
8047                 unsigned int slot = unused ? unused : txn->mt_numdbs;
8048                 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
8049                 txn->mt_dbxs[slot].md_name.mv_size = len;
8050                 txn->mt_dbxs[slot].md_rel = NULL;
8051                 txn->mt_dbflags[slot] = dbflag;
8052                 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
8053                 *dbi = slot;
8054                 mdb_default_cmp(txn, slot);
8055                 if (!unused) {
8056                         txn->mt_numdbs++;
8057                 }
8058         }
8059
8060         return rc;
8061 }
8062
8063 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
8064 {
8065         if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
8066                 return EINVAL;
8067
8068         if (txn->mt_dbflags[dbi] & DB_STALE) {
8069                 MDB_cursor mc;
8070                 MDB_xcursor mx;
8071                 /* Stale, must read the DB's root. cursor_init does it for us. */
8072                 mdb_cursor_init(&mc, txn, dbi, &mx);
8073         }
8074         return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
8075 }
8076
8077 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
8078 {
8079         char *ptr;
8080         if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
8081                 return;
8082         ptr = env->me_dbxs[dbi].md_name.mv_data;
8083         env->me_dbxs[dbi].md_name.mv_data = NULL;
8084         env->me_dbxs[dbi].md_name.mv_size = 0;
8085         env->me_dbflags[dbi] = 0;
8086         free(ptr);
8087 }
8088
8089 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
8090 {
8091         /* We could return the flags for the FREE_DBI too but what's the point? */
8092         if (txn == NULL || dbi < MAIN_DBI || dbi >= txn->mt_numdbs)
8093                 return EINVAL;
8094         *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
8095         return MDB_SUCCESS;
8096 }
8097
8098 /** Add all the DB's pages to the free list.
8099  * @param[in] mc Cursor on the DB to free.
8100  * @param[in] subs non-Zero to check for sub-DBs in this DB.
8101  * @return 0 on success, non-zero on failure.
8102  */
8103 static int
8104 mdb_drop0(MDB_cursor *mc, int subs)
8105 {
8106         int rc;
8107
8108         rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
8109         if (rc == MDB_SUCCESS) {
8110                 MDB_txn *txn = mc->mc_txn;
8111                 MDB_node *ni;
8112                 MDB_cursor mx;
8113                 unsigned int i;
8114
8115                 /* LEAF2 pages have no nodes, cannot have sub-DBs */
8116                 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
8117                         mdb_cursor_pop(mc);
8118
8119                 mdb_cursor_copy(mc, &mx);
8120                 while (mc->mc_snum > 0) {
8121                         MDB_page *mp = mc->mc_pg[mc->mc_top];
8122                         unsigned n = NUMKEYS(mp);
8123                         if (IS_LEAF(mp)) {
8124                                 for (i=0; i<n; i++) {
8125                                         ni = NODEPTR(mp, i);
8126                                         if (ni->mn_flags & F_BIGDATA) {
8127                                                 MDB_page *omp;
8128                                                 pgno_t pg;
8129                                                 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8130                                                 rc = mdb_page_get(txn, pg, &omp, NULL);
8131                                                 if (rc != 0)
8132                                                         return rc;
8133                                                 assert(IS_OVERFLOW(omp));
8134                                                 rc = mdb_midl_append_range(&txn->mt_free_pgs,
8135                                                         pg, omp->mp_pages);
8136                                                 if (rc)
8137                                                         return rc;
8138                                         } else if (subs && (ni->mn_flags & F_SUBDATA)) {
8139                                                 mdb_xcursor_init1(mc, ni);
8140                                                 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
8141                                                 if (rc)
8142                                                         return rc;
8143                                         }
8144                                 }
8145                         } else {
8146                                 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
8147                                         return rc;
8148                                 for (i=0; i<n; i++) {
8149                                         pgno_t pg;
8150                                         ni = NODEPTR(mp, i);
8151                                         pg = NODEPGNO(ni);
8152                                         /* free it */
8153                                         mdb_midl_xappend(txn->mt_free_pgs, pg);
8154                                 }
8155                         }
8156                         if (!mc->mc_top)
8157                                 break;
8158                         mc->mc_ki[mc->mc_top] = i;
8159                         rc = mdb_cursor_sibling(mc, 1);
8160                         if (rc) {
8161                                 /* no more siblings, go back to beginning
8162                                  * of previous level.
8163                                  */
8164                                 mdb_cursor_pop(mc);
8165                                 mc->mc_ki[0] = 0;
8166                                 for (i=1; i<mc->mc_snum; i++) {
8167                                         mc->mc_ki[i] = 0;
8168                                         mc->mc_pg[i] = mx.mc_pg[i];
8169                                 }
8170                         }
8171                 }
8172                 /* free it */
8173                 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
8174         } else if (rc == MDB_NOTFOUND) {
8175                 rc = MDB_SUCCESS;
8176         }
8177         return rc;
8178 }
8179
8180 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
8181 {
8182         MDB_cursor *mc, *m2;
8183         int rc;
8184
8185         if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1 || !(txn->mt_dbflags[dbi] & DB_VALID))
8186                 return EINVAL;
8187
8188         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8189                 return EACCES;
8190
8191         rc = mdb_cursor_open(txn, dbi, &mc);
8192         if (rc)
8193                 return rc;
8194
8195         rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
8196         /* Invalidate the dropped DB's cursors */
8197         for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
8198                 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
8199         if (rc)
8200                 goto leave;
8201
8202         /* Can't delete the main DB */
8203         if (del && dbi > MAIN_DBI) {
8204                 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
8205                 if (!rc) {
8206                         txn->mt_dbflags[dbi] = DB_STALE;
8207                         mdb_dbi_close(txn->mt_env, dbi);
8208                 }
8209         } else {
8210                 /* reset the DB record, mark it dirty */
8211                 txn->mt_dbflags[dbi] |= DB_DIRTY;
8212                 txn->mt_dbs[dbi].md_depth = 0;
8213                 txn->mt_dbs[dbi].md_branch_pages = 0;
8214                 txn->mt_dbs[dbi].md_leaf_pages = 0;
8215                 txn->mt_dbs[dbi].md_overflow_pages = 0;
8216                 txn->mt_dbs[dbi].md_entries = 0;
8217                 txn->mt_dbs[dbi].md_root = P_INVALID;
8218
8219                 txn->mt_flags |= MDB_TXN_DIRTY;
8220         }
8221 leave:
8222         mdb_cursor_close(mc);
8223         return rc;
8224 }
8225
8226 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8227 {
8228         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8229                 return EINVAL;
8230
8231         txn->mt_dbxs[dbi].md_cmp = cmp;
8232         return MDB_SUCCESS;
8233 }
8234
8235 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8236 {
8237         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8238                 return EINVAL;
8239
8240         txn->mt_dbxs[dbi].md_dcmp = cmp;
8241         return MDB_SUCCESS;
8242 }
8243
8244 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
8245 {
8246         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8247                 return EINVAL;
8248
8249         txn->mt_dbxs[dbi].md_rel = rel;
8250         return MDB_SUCCESS;
8251 }
8252
8253 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
8254 {
8255         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8256                 return EINVAL;
8257
8258         txn->mt_dbxs[dbi].md_relctx = ctx;
8259         return MDB_SUCCESS;
8260 }
8261
8262 int mdb_env_get_maxkeysize(MDB_env *env)
8263 {
8264         return MDB_MAXKEYSIZE;
8265 }
8266
8267 int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
8268 {
8269         unsigned int i, rdrs;
8270         MDB_reader *mr;
8271         char buf[64];
8272         int first = 1;
8273
8274         if (!env || !func)
8275                 return -1;
8276         if (!env->me_txns) {
8277                 return func("(no reader locks)\n", ctx);
8278         }
8279         rdrs = env->me_txns->mti_numreaders;
8280         mr = env->me_txns->mti_readers;
8281         for (i=0; i<rdrs; i++) {
8282                 if (mr[i].mr_pid) {
8283                         size_t tid;
8284                         int rc;
8285                         tid = mr[i].mr_tid;
8286                         if (mr[i].mr_txnid == (txnid_t)-1) {
8287                                 sprintf(buf, "%10d %"Z"x -\n", mr[i].mr_pid, tid);
8288                         } else {
8289                                 sprintf(buf, "%10d %"Z"x %"Z"u\n", mr[i].mr_pid, tid, mr[i].mr_txnid);
8290                         }
8291                         if (first) {
8292                                 first = 0;
8293                                 func("    pid     thread     txnid\n", ctx);
8294                         }
8295                         rc = func(buf, ctx);
8296                         if (rc < 0)
8297                                 return rc;
8298                 }
8299         }
8300         if (first) {
8301                 func("(no active readers)\n", ctx);
8302         }
8303         return 0;
8304 }
8305
8306 /** Insert pid into list if not already present.
8307  * return -1 if already present.
8308  */
8309 static int mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
8310 {
8311         /* binary search of pid in list */
8312         unsigned base = 0;
8313         unsigned cursor = 1;
8314         int val = 0;
8315         unsigned n = ids[0];
8316
8317         while( 0 < n ) {
8318                 unsigned pivot = n >> 1;
8319                 cursor = base + pivot + 1;
8320                 val = pid - ids[cursor];
8321
8322                 if( val < 0 ) {
8323                         n = pivot;
8324
8325                 } else if ( val > 0 ) {
8326                         base = cursor;
8327                         n -= pivot + 1;
8328
8329                 } else {
8330                         /* found, so it's a duplicate */
8331                         return -1;
8332                 }
8333         }
8334
8335         if( val > 0 ) {
8336                 ++cursor;
8337         }
8338         ids[0]++;
8339         for (n = ids[0]; n > cursor; n--)
8340                 ids[n] = ids[n-1];
8341         ids[n] = pid;
8342         return 0;
8343 }
8344
8345 int mdb_reader_check(MDB_env *env, int *dead)
8346 {
8347         unsigned int i, j, rdrs;
8348         MDB_reader *mr;
8349         MDB_PID_T *pids, pid;
8350         int count = 0;
8351
8352         if (!env)
8353                 return EINVAL;
8354         if (dead)
8355                 *dead = 0;
8356         if (!env->me_txns)
8357                 return MDB_SUCCESS;
8358         rdrs = env->me_txns->mti_numreaders;
8359         pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
8360         if (!pids)
8361                 return ENOMEM;
8362         pids[0] = 0;
8363         mr = env->me_txns->mti_readers;
8364         j = 0;
8365         for (i=0; i<rdrs; i++) {
8366                 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
8367                         pid = mr[i].mr_pid;
8368                         if (mdb_pid_insert(pids, pid) == 0) {
8369                                 if (!mdb_reader_pid(env, Pidcheck, pid)) {
8370                                         LOCK_MUTEX_R(env);
8371                                         /* Recheck, a new process may have reused pid */
8372                                         if (!mdb_reader_pid(env, Pidcheck, pid)) {
8373                                                 for (j=i; j<rdrs; j++)
8374                                                         if (mr[j].mr_pid == pid) {
8375                                                                 DPRINTF(("clear stale reader pid %u txn %"Z"d",
8376                                                                         (unsigned) pid, mr[j].mr_txnid));
8377                                                                 mr[j].mr_pid = 0;
8378                                                                 count++;
8379                                                         }
8380                                         }
8381                                         UNLOCK_MUTEX_R(env);
8382                                 }
8383                         }
8384                 }
8385         }
8386         free(pids);
8387         if (dead)
8388                 *dead = count;
8389         return MDB_SUCCESS;
8390 }
8391 /** @} */