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