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