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