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