]> git.sur5r.net Git - openldap/blob - libraries/libmdb/mdb.c
ITS#7229 more mdb_page_split tweaks
[openldap] / libraries / libmdb / 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-2012 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 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <sys/param.h>
38 #ifdef _WIN32
39 #include <windows.h>
40 #else
41 #include <sys/uio.h>
42 #include <sys/mman.h>
43 #ifdef HAVE_SYS_FILE_H
44 #include <sys/file.h>
45 #endif
46 #include <fcntl.h>
47 #endif
48
49 #include <assert.h>
50 #include <errno.h>
51 #include <limits.h>
52 #include <stddef.h>
53 #include <inttypes.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <time.h>
58 #include <unistd.h>
59
60 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
61 #include <resolv.h>     /* defines BYTE_ORDER on HPUX and Solaris */
62 #endif
63
64 #ifndef _WIN32
65 #include <pthread.h>
66 #ifdef __APPLE__
67 #include <semaphore.h>
68 #endif
69 #endif
70
71 #ifdef USE_VALGRIND
72 #include <valgrind/memcheck.h>
73 #define VGMEMP_CREATE(h,r,z)    VALGRIND_CREATE_MEMPOOL(h,r,z)
74 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
75 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
76 #define VGMEMP_DESTROY(h)       VALGRIND_DESTROY_MEMPOOL(h)
77 #define VGMEMP_DEFINED(a,s)     VALGRIND_MAKE_MEM_DEFINED(a,s)
78 #else
79 #define VGMEMP_CREATE(h,r,z)
80 #define VGMEMP_ALLOC(h,a,s)
81 #define VGMEMP_FREE(h,a)
82 #define VGMEMP_DESTROY(h)
83 #define VGMEMP_DEFINED(a,s)
84 #endif
85
86 #ifndef BYTE_ORDER
87 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
88 /* Solaris just defines one or the other */
89 #  define LITTLE_ENDIAN 1234
90 #  define BIG_ENDIAN    4321
91 #  ifdef _LITTLE_ENDIAN
92 #   define BYTE_ORDER  LITTLE_ENDIAN
93 #  else
94 #   define BYTE_ORDER  BIG_ENDIAN
95 #  endif
96 # else
97 #  define BYTE_ORDER   __BYTE_ORDER
98 # endif
99 #endif
100
101 #ifndef LITTLE_ENDIAN
102 #define LITTLE_ENDIAN   __LITTLE_ENDIAN
103 #endif
104 #ifndef BIG_ENDIAN
105 #define BIG_ENDIAN      __BIG_ENDIAN
106 #endif
107
108 #if defined(__i386) || defined(__x86_64)
109 #define MISALIGNED_OK   1
110 #endif
111
112 #include "mdb.h"
113 #include "midl.h"
114
115 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
116 # error "Unknown or unsupported endianness (BYTE_ORDER)"
117 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
118 # error "Two's complement, reasonably sized integer types, please"
119 #endif
120
121 /** @defgroup internal  MDB Internals
122  *      @{
123  */
124 /** @defgroup compat    Windows Compatibility Macros
125  *      A bunch of macros to minimize the amount of platform-specific ifdefs
126  *      needed throughout the rest of the code. When the features this library
127  *      needs are similar enough to POSIX to be hidden in a one-or-two line
128  *      replacement, this macro approach is used.
129  *      @{
130  */
131 #ifdef _WIN32
132 #define pthread_t       DWORD
133 #define pthread_mutex_t HANDLE
134 #define pthread_key_t   DWORD
135 #define pthread_self()  GetCurrentThreadId()
136 #define pthread_key_create(x,y) (*(x) = TlsAlloc())
137 #define pthread_key_delete(x)   TlsFree(x)
138 #define pthread_getspecific(x)  TlsGetValue(x)
139 #define pthread_setspecific(x,y)        TlsSetValue(x,y)
140 #define pthread_mutex_unlock(x) ReleaseMutex(x)
141 #define pthread_mutex_lock(x)   WaitForSingleObject(x, INFINITE)
142 #define LOCK_MUTEX_R(env)       pthread_mutex_lock((env)->me_rmutex)
143 #define UNLOCK_MUTEX_R(env)     pthread_mutex_unlock((env)->me_rmutex)
144 #define LOCK_MUTEX_W(env)       pthread_mutex_lock((env)->me_wmutex)
145 #define UNLOCK_MUTEX_W(env)     pthread_mutex_unlock((env)->me_wmutex)
146 #define getpid()        GetCurrentProcessId()
147 #define fdatasync(fd)   (!FlushFileBuffers(fd))
148 #define ErrCode()       GetLastError()
149 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
150 #define close(fd)       CloseHandle(fd)
151 #define munmap(ptr,len) UnmapViewOfFile(ptr)
152 #else
153 #ifdef __APPLE__
154 #define LOCK_MUTEX_R(env)       sem_wait((env)->me_rmutex)
155 #define UNLOCK_MUTEX_R(env)     sem_post((env)->me_rmutex)
156 #define LOCK_MUTEX_W(env)       sem_wait((env)->me_wmutex)
157 #define UNLOCK_MUTEX_W(env)     sem_post((env)->me_wmutex)
158 #define fdatasync(fd)   fsync(fd)
159 #else
160 #ifdef ANDROID
161 #define fdatasync(fd)   fsync(fd)
162 #endif
163         /** Lock the reader mutex.
164          */
165 #define LOCK_MUTEX_R(env)       pthread_mutex_lock(&(env)->me_txns->mti_mutex)
166         /** Unlock the reader mutex.
167          */
168 #define UNLOCK_MUTEX_R(env)     pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
169
170         /** Lock the writer mutex.
171          *      Only a single write transaction is allowed at a time. Other writers
172          *      will block waiting for this mutex.
173          */
174 #define LOCK_MUTEX_W(env)       pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
175         /** Unlock the writer mutex.
176          */
177 #define UNLOCK_MUTEX_W(env)     pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
178 #endif  /* __APPLE__ */
179
180         /** Get the error code for the last failed system function.
181          */
182 #define ErrCode()       errno
183
184         /** An abstraction for a file handle.
185          *      On POSIX systems file handles are small integers. On Windows
186          *      they're opaque pointers.
187          */
188 #define HANDLE  int
189
190         /**     A value for an invalid file handle.
191          *      Mainly used to initialize file variables and signify that they are
192          *      unused.
193          */
194 #define INVALID_HANDLE_VALUE    (-1)
195
196         /** Get the size of a memory page for the system.
197          *      This is the basic size that the platform's memory manager uses, and is
198          *      fundamental to the use of memory-mapped files.
199          */
200 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
201 #endif
202
203 #if defined(_WIN32) || defined(__APPLE__)
204 #define MNAME_LEN       32
205 #else
206 #define MNAME_LEN       (sizeof(pthread_mutex_t))
207 #endif
208
209 /** @} */
210
211 #ifndef _WIN32
212 /**     A flag for opening a file and requesting synchronous data writes.
213  *      This is only used when writing a meta page. It's not strictly needed;
214  *      we could just do a normal write and then immediately perform a flush.
215  *      But if this flag is available it saves us an extra system call.
216  *
217  *      @note If O_DSYNC is undefined but exists in /usr/include,
218  * preferably set some compiler flag to get the definition.
219  * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
220  */
221 #ifndef MDB_DSYNC
222 # define MDB_DSYNC      O_DSYNC
223 #endif
224 #endif
225
226 /** Function for flushing the data of a file. Define this to fsync
227  *      if fdatasync() is not supported.
228  */
229 #ifndef MDB_FDATASYNC
230 # define MDB_FDATASYNC  fdatasync
231 #endif
232
233         /** A page number in the database.
234          *      Note that 64 bit page numbers are overkill, since pages themselves
235          *      already represent 12-13 bits of addressable memory, and the OS will
236          *      always limit applications to a maximum of 63 bits of address space.
237          *
238          *      @note In the #MDB_node structure, we only store 48 bits of this value,
239          *      which thus limits us to only 60 bits of addressable data.
240          */
241 typedef ID      pgno_t;
242
243         /** A transaction ID.
244          *      See struct MDB_txn.mt_txnid for details.
245          */
246 typedef ID      txnid_t;
247
248 /** @defgroup debug     Debug Macros
249  *      @{
250  */
251 #ifndef MDB_DEBUG
252         /**     Enable debug output.
253          *      Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
254          *      read from and written to the database (used for free space management).
255          */
256 #define MDB_DEBUG 0
257 #endif
258
259 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
260 # define DPRINTF        (void)  /* Vararg macros may be unsupported */
261 #elif MDB_DEBUG
262 static int mdb_debug;
263 static int mdb_debug_start;
264
265         /**     Print a debug message with printf formatting. */
266 # define DPRINTF(fmt, ...)      /**< Requires 2 or more args */ \
267         if (mdb_debug) fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)
268 #else
269 # define DPRINTF(fmt, ...)      ((void) 0)
270 #endif
271         /**     Print a debug string.
272          *      The string is printed literally, with no format processing.
273          */
274 #define DPUTS(arg)      DPRINTF("%s", arg)
275 /** @} */
276
277         /** A default memory page size.
278          *      The actual size is platform-dependent, but we use this for
279          *      boot-strapping. We probably should not be using this any more.
280          *      The #GET_PAGESIZE() macro is used to get the actual size.
281          *
282          *      Note that we don't currently support Huge pages. On Linux,
283          *      regular data files cannot use Huge pages, and in general
284          *      Huge pages aren't actually pageable. We rely on the OS
285          *      demand-pager to read our data and page it out when memory
286          *      pressure from other processes is high. So until OSs have
287          *      actual paging support for Huge pages, they're not viable.
288          */
289 #define MDB_PAGESIZE     4096
290
291         /** The minimum number of keys required in a database page.
292          *      Setting this to a larger value will place a smaller bound on the
293          *      maximum size of a data item. Data items larger than this size will
294          *      be pushed into overflow pages instead of being stored directly in
295          *      the B-tree node. This value used to default to 4. With a page size
296          *      of 4096 bytes that meant that any item larger than 1024 bytes would
297          *      go into an overflow page. That also meant that on average 2-3KB of
298          *      each overflow page was wasted space. The value cannot be lower than
299          *      2 because then there would no longer be a tree structure. With this
300          *      value, items larger than 2KB will go into overflow pages, and on
301          *      average only 1KB will be wasted.
302          */
303 #define MDB_MINKEYS      2
304
305         /**     A stamp that identifies a file as an MDB file.
306          *      There's nothing special about this value other than that it is easily
307          *      recognizable, and it will reflect any byte order mismatches.
308          */
309 #define MDB_MAGIC        0xBEEFC0DE
310
311         /**     The version number for a database's file format. */
312 #define MDB_VERSION      1
313
314         /**     The maximum size of a key in the database.
315          *      While data items have essentially unbounded size, we require that
316          *      keys all fit onto a regular page. This limit could be raised a bit
317          *      further if needed; to something just under #MDB_PAGESIZE / #MDB_MINKEYS.
318          */
319 #define MAXKEYSIZE       511
320
321 #if MDB_DEBUG
322         /**     A key buffer.
323          *      @ingroup debug
324          *      This is used for printing a hex dump of a key's contents.
325          */
326 #define DKBUF   char kbuf[(MAXKEYSIZE*2+1)]
327         /**     Display a key in hex.
328          *      @ingroup debug
329          *      Invoke a function to display a key in hex.
330          */
331 #define DKEY(x) mdb_dkey(x, kbuf)
332 #else
333 #define DKBUF   typedef int dummy_kbuf  /* so we can put ';' after */
334 #define DKEY(x) 0
335 #endif
336
337 /**     @defgroup lazylock      Lazy Locking
338  *      Macros for locks that aren't actually needed.
339  *      The DB view is always consistent because all writes are wrapped in
340  *      the wmutex. Finer-grained locks aren't necessary.
341  *      @{
342  */
343 #ifndef LAZY_LOCKS
344         /**     Use lazy locking. I.e., don't lock these accesses at all. */
345 #define LAZY_LOCKS      1
346 #endif
347 #if     LAZY_LOCKS
348         /** Grab the reader lock */
349 #define LAZY_MUTEX_LOCK(x)
350         /** Release the reader lock */
351 #define LAZY_MUTEX_UNLOCK(x)
352         /** Release the DB table reader/writer lock */
353 #define LAZY_RWLOCK_UNLOCK(x)
354         /** Grab the DB table write lock */
355 #define LAZY_RWLOCK_WRLOCK(x)
356         /** Grab the DB table read lock */
357 #define LAZY_RWLOCK_RDLOCK(x)
358         /** Declare the DB table rwlock.  Should not be followed by ';'. */
359 #define LAZY_RWLOCK_DEF(x)
360         /** Initialize the DB table rwlock */
361 #define LAZY_RWLOCK_INIT(x,y)
362         /**     Destroy the DB table rwlock */
363 #define LAZY_RWLOCK_DESTROY(x)
364 #else
365 #define LAZY_MUTEX_LOCK(x)              pthread_mutex_lock(x)
366 #define LAZY_MUTEX_UNLOCK(x)    pthread_mutex_unlock(x)
367 #define LAZY_RWLOCK_UNLOCK(x)   pthread_rwlock_unlock(x)
368 #define LAZY_RWLOCK_WRLOCK(x)   pthread_rwlock_wrlock(x)
369 #define LAZY_RWLOCK_RDLOCK(x)   pthread_rwlock_rdlock(x)
370 #define LAZY_RWLOCK_DEF(x)              pthread_rwlock_t        x;
371 #define LAZY_RWLOCK_INIT(x,y)   pthread_rwlock_init(x,y)
372 #define LAZY_RWLOCK_DESTROY(x)  pthread_rwlock_destroy(x)
373 #endif
374 /** @} */
375
376         /** An invalid page number.
377          *      Mainly used to denote an empty tree.
378          */
379 #define P_INVALID        (~0UL)
380
381         /** Test if a flag \b f is set in a flag word \b w. */
382 #define F_ISSET(w, f)    (((w) & (f)) == (f))
383
384         /**     Used for offsets within a single page.
385          *      Since memory pages are typically 4 or 8KB in size, 12-13 bits,
386          *      this is plenty.
387          */
388 typedef uint16_t         indx_t;
389
390         /**     Default size of memory map.
391          *      This is certainly too small for any actual applications. Apps should always set
392          *      the size explicitly using #mdb_env_set_mapsize().
393          */
394 #define DEFAULT_MAPSIZE 1048576
395
396 /**     @defgroup readers       Reader Lock Table
397  *      Readers don't acquire any locks for their data access. Instead, they
398  *      simply record their transaction ID in the reader table. The reader
399  *      mutex is needed just to find an empty slot in the reader table. The
400  *      slot's address is saved in thread-specific data so that subsequent read
401  *      transactions started by the same thread need no further locking to proceed.
402  *
403  *      Since the database uses multi-version concurrency control, readers don't
404  *      actually need any locking. This table is used to keep track of which
405  *      readers are using data from which old transactions, so that we'll know
406  *      when a particular old transaction is no longer in use. Old transactions
407  *      that have discarded any data pages can then have those pages reclaimed
408  *      for use by a later write transaction.
409  *
410  *      The lock table is constructed such that reader slots are aligned with the
411  *      processor's cache line size. Any slot is only ever used by one thread.
412  *      This alignment guarantees that there will be no contention or cache
413  *      thrashing as threads update their own slot info, and also eliminates
414  *      any need for locking when accessing a slot.
415  *
416  *      A writer thread will scan every slot in the table to determine the oldest
417  *      outstanding reader transaction. Any freed pages older than this will be
418  *      reclaimed by the writer. The writer doesn't use any locks when scanning
419  *      this table. This means that there's no guarantee that the writer will
420  *      see the most up-to-date reader info, but that's not required for correct
421  *      operation - all we need is to know the upper bound on the oldest reader,
422  *      we don't care at all about the newest reader. So the only consequence of
423  *      reading stale information here is that old pages might hang around a
424  *      while longer before being reclaimed. That's actually good anyway, because
425  *      the longer we delay reclaiming old pages, the more likely it is that a
426  *      string of contiguous pages can be found after coalescing old pages from
427  *      many old transactions together.
428  *
429  *      @todo We don't actually do such coalescing yet, we grab pages from one
430  *      old transaction at a time.
431  *      @{
432  */
433         /**     Number of slots in the reader table.
434          *      This value was chosen somewhat arbitrarily. 126 readers plus a
435          *      couple mutexes fit exactly into 8KB on my development machine.
436          *      Applications should set the table size using #mdb_env_set_maxreaders().
437          */
438 #define DEFAULT_READERS 126
439
440         /**     The size of a CPU cache line in bytes. We want our lock structures
441          *      aligned to this size to avoid false cache line sharing in the
442          *      lock table.
443          *      This value works for most CPUs. For Itanium this should be 128.
444          */
445 #ifndef CACHELINE
446 #define CACHELINE       64
447 #endif
448
449         /**     The information we store in a single slot of the reader table.
450          *      In addition to a transaction ID, we also record the process and
451          *      thread ID that owns a slot, so that we can detect stale information,
452          *      e.g. threads or processes that went away without cleaning up.
453          *      @note We currently don't check for stale records. We simply re-init
454          *      the table when we know that we're the only process opening the
455          *      lock file.
456          */
457 typedef struct MDB_rxbody {
458         /**     The current Transaction ID when this transaction began.
459          *      Multiple readers that start at the same time will probably have the
460          *      same ID here. Again, it's not important to exclude them from
461          *      anything; all we need to know is which version of the DB they
462          *      started from so we can avoid overwriting any data used in that
463          *      particular version.
464          */
465         txnid_t         mrb_txnid;
466         /** The process ID of the process owning this reader txn. */
467         pid_t           mrb_pid;
468         /** The thread ID of the thread owning this txn. */
469         pthread_t       mrb_tid;
470 } MDB_rxbody;
471
472         /** The actual reader record, with cacheline padding. */
473 typedef struct MDB_reader {
474         union {
475                 MDB_rxbody mrx;
476                 /** shorthand for mrb_txnid */
477 #define mr_txnid        mru.mrx.mrb_txnid
478 #define mr_pid  mru.mrx.mrb_pid
479 #define mr_tid  mru.mrx.mrb_tid
480                 /** cache line alignment */
481                 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
482         } mru;
483 } MDB_reader;
484
485         /** The header for the reader table.
486          *      The table resides in a memory-mapped file. (This is a different file
487          *      than is used for the main database.)
488          *
489          *      For POSIX the actual mutexes reside in the shared memory of this
490          *      mapped file. On Windows, mutexes are named objects allocated by the
491          *      kernel; we store the mutex names in this mapped file so that other
492          *      processes can grab them. This same approach is also used on
493          *      MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
494          *      process-shared POSIX mutexes. For these cases where a named object
495          *      is used, the object name is derived from a 64 bit FNV hash of the
496          *      environment pathname. As such, naming collisions are extremely
497          *      unlikely. If a collision occurs, the results are unpredictable.
498          */
499 typedef struct MDB_txbody {
500                 /** Stamp identifying this as an MDB file. It must be set
501                  *      to #MDB_MAGIC. */
502         uint32_t        mtb_magic;
503                 /** Version number of this lock file. Must be set to #MDB_VERSION. */
504         uint32_t        mtb_version;
505 #if defined(_WIN32) || defined(__APPLE__)
506         char    mtb_rmname[MNAME_LEN];
507 #else
508                 /** Mutex protecting access to this table.
509                  *      This is the reader lock that #LOCK_MUTEX_R acquires.
510                  */
511         pthread_mutex_t mtb_mutex;
512 #endif
513                 /**     The ID of the last transaction committed to the database.
514                  *      This is recorded here only for convenience; the value can always
515                  *      be determined by reading the main database meta pages.
516                  */
517         txnid_t         mtb_txnid;
518                 /** The number of slots that have been used in the reader table.
519                  *      This always records the maximum count, it is not decremented
520                  *      when readers release their slots.
521                  */
522         unsigned        mtb_numreaders;
523                 /**     The ID of the most recent meta page in the database.
524                  *      This is recorded here only for convenience; the value can always
525                  *      be determined by reading the main database meta pages.
526                  */
527         uint32_t        mtb_me_toggle;
528 } MDB_txbody;
529
530         /** The actual reader table definition. */
531 typedef struct MDB_txninfo {
532         union {
533                 MDB_txbody mtb;
534 #define mti_magic       mt1.mtb.mtb_magic
535 #define mti_version     mt1.mtb.mtb_version
536 #define mti_mutex       mt1.mtb.mtb_mutex
537 #define mti_rmname      mt1.mtb.mtb_rmname
538 #define mti_txnid       mt1.mtb.mtb_txnid
539 #define mti_numreaders  mt1.mtb.mtb_numreaders
540 #define mti_me_toggle   mt1.mtb.mtb_me_toggle
541                 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
542         } mt1;
543         union {
544 #if defined(_WIN32) || defined(__APPLE__)
545                 char mt2_wmname[MNAME_LEN];
546 #define mti_wmname      mt2.mt2_wmname
547 #else
548                 pthread_mutex_t mt2_wmutex;
549 #define mti_wmutex      mt2.mt2_wmutex
550 #endif
551                 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
552         } mt2;
553         MDB_reader      mti_readers[1];
554 } MDB_txninfo;
555 /** @} */
556
557 /** Common header for all page types.
558  * Overflow records occupy a number of contiguous pages with no
559  * headers on any page after the first.
560  */
561 typedef struct MDB_page {
562 #define mp_pgno mp_p.p_pgno
563 #define mp_next mp_p.p_next
564         union {
565                 pgno_t          p_pgno; /**< page number */
566                 void *          p_next; /**< for in-memory list of freed structs */
567         } mp_p;
568         uint16_t        mp_pad;
569 /**     @defgroup mdb_page      Page Flags
570  *      @ingroup internal
571  *      Flags for the page headers.
572  *      @{
573  */
574 #define P_BRANCH         0x01           /**< branch page */
575 #define P_LEAF           0x02           /**< leaf page */
576 #define P_OVERFLOW       0x04           /**< overflow page */
577 #define P_META           0x08           /**< meta page */
578 #define P_DIRTY          0x10           /**< dirty page */
579 #define P_LEAF2          0x20           /**< for #MDB_DUPFIXED records */
580 #define P_SUBP           0x40           /**< for #MDB_DUPSORT sub-pages */
581 /** @} */
582         uint16_t        mp_flags;               /**< @ref mdb_page */
583 #define mp_lower        mp_pb.pb.pb_lower
584 #define mp_upper        mp_pb.pb.pb_upper
585 #define mp_pages        mp_pb.pb_pages
586         union {
587                 struct {
588                         indx_t          pb_lower;               /**< lower bound of free space */
589                         indx_t          pb_upper;               /**< upper bound of free space */
590                 } pb;
591                 uint32_t        pb_pages;       /**< number of overflow pages */
592         } mp_pb;
593         indx_t          mp_ptrs[1];             /**< dynamic size */
594 } MDB_page;
595
596         /** Size of the page header, excluding dynamic data at the end */
597 #define PAGEHDRSZ        ((unsigned) offsetof(MDB_page, mp_ptrs))
598
599         /** Address of first usable data byte in a page, after the header */
600 #define METADATA(p)      ((void *)((char *)(p) + PAGEHDRSZ))
601
602         /** Number of nodes on a page */
603 #define NUMKEYS(p)       (((p)->mp_lower - PAGEHDRSZ) >> 1)
604
605         /** The amount of space remaining in the page */
606 #define SIZELEFT(p)      (indx_t)((p)->mp_upper - (p)->mp_lower)
607
608         /** The percentage of space used in the page, in tenths of a percent. */
609 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
610                                 ((env)->me_psize - PAGEHDRSZ))
611         /** The minimum page fill factor, in tenths of a percent.
612          *      Pages emptier than this are candidates for merging.
613          */
614 #define FILL_THRESHOLD   250
615
616         /** Test if a page is a leaf page */
617 #define IS_LEAF(p)       F_ISSET((p)->mp_flags, P_LEAF)
618         /** Test if a page is a LEAF2 page */
619 #define IS_LEAF2(p)      F_ISSET((p)->mp_flags, P_LEAF2)
620         /** Test if a page is a branch page */
621 #define IS_BRANCH(p)     F_ISSET((p)->mp_flags, P_BRANCH)
622         /** Test if a page is an overflow page */
623 #define IS_OVERFLOW(p)   F_ISSET((p)->mp_flags, P_OVERFLOW)
624         /** Test if a page is a sub page */
625 #define IS_SUBP(p)       F_ISSET((p)->mp_flags, P_SUBP)
626
627         /** The number of overflow pages needed to store the given size. */
628 #define OVPAGES(size, psize)    ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
629
630         /** Header for a single key/data pair within a page.
631          * We guarantee 2-byte alignment for nodes.
632          */
633 typedef struct MDB_node {
634         /** lo and hi are used for data size on leaf nodes and for
635          * child pgno on branch nodes. On 64 bit platforms, flags
636          * is also used for pgno. (Branch nodes have no flags).
637          * They are in host byte order in case that lets some
638          * accesses be optimized into a 32-bit word access.
639          */
640 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
641 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
642         unsigned short  mn_offset[2];   /**< storage for #mn_lo and #mn_hi */
643 /** @defgroup mdb_node Node Flags
644  *      @ingroup internal
645  *      Flags for node headers.
646  *      @{
647  */
648 #define F_BIGDATA        0x01                   /**< data put on overflow page */
649 #define F_SUBDATA        0x02                   /**< data is a sub-database */
650 #define F_DUPDATA        0x04                   /**< data has duplicates */
651
652 /** valid flags for #mdb_node_add() */
653 #define NODE_ADD_FLAGS  (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
654
655 /** @} */
656         unsigned short  mn_flags;               /**< @ref mdb_node */
657         unsigned short  mn_ksize;               /**< key size */
658         char            mn_data[1];                     /**< key and data are appended here */
659 } MDB_node;
660
661         /** Size of the node header, excluding dynamic data at the end */
662 #define NODESIZE         offsetof(MDB_node, mn_data)
663
664         /** Bit position of top word in page number, for shifting mn_flags */
665 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
666
667         /** Size of a node in a branch page with a given key.
668          *      This is just the node header plus the key, there is no data.
669          */
670 #define INDXSIZE(k)      (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
671
672         /** Size of a node in a leaf page with a given key and data.
673          *      This is node header plus key plus data size.
674          */
675 #define LEAFSIZE(k, d)   (NODESIZE + (k)->mv_size + (d)->mv_size)
676
677         /** Address of node \b i in page \b p */
678 #define NODEPTR(p, i)    ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
679
680         /** Address of the key for the node */
681 #define NODEKEY(node)    (void *)((node)->mn_data)
682
683         /** Address of the data for a node */
684 #define NODEDATA(node)   (void *)((char *)(node)->mn_data + (node)->mn_ksize)
685
686         /** Get the page number pointed to by a branch node */
687 #define NODEPGNO(node) \
688         ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
689          (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
690         /** Set the page number in a branch node */
691 #define SETPGNO(node,pgno)      do { \
692         (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
693         if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
694
695         /** Get the size of the data in a leaf node */
696 #define NODEDSZ(node)    ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
697         /** Set the size of the data for a leaf node */
698 #define SETDSZ(node,size)       do { \
699         (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
700         /** The size of a key in a node */
701 #define NODEKSZ(node)    ((node)->mn_ksize)
702
703         /** Copy a page number from src to dst */
704 #ifdef MISALIGNED_OK
705 #define COPY_PGNO(dst,src)      dst = src
706 #else
707 #if SIZE_MAX > 4294967295UL
708 #define COPY_PGNO(dst,src)      do { \
709         unsigned short *s, *d;  \
710         s = (unsigned short *)&(src);   \
711         d = (unsigned short *)&(dst);   \
712         *d++ = *s++;    \
713         *d++ = *s++;    \
714         *d++ = *s++;    \
715         *d = *s;        \
716 } while (0)
717 #else
718 #define COPY_PGNO(dst,src)      do { \
719         unsigned short *s, *d;  \
720         s = (unsigned short *)&(src);   \
721         d = (unsigned short *)&(dst);   \
722         *d++ = *s++;    \
723         *d = *s;        \
724 } while (0)
725 #endif
726 #endif
727         /** The address of a key in a LEAF2 page.
728          *      LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
729          *      There are no node headers, keys are stored contiguously.
730          */
731 #define LEAF2KEY(p, i, ks)      ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
732
733         /** Set the \b node's key into \b key, if requested. */
734 #define MDB_SET_KEY(node, key)  { if ((key) != NULL) { \
735         (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
736
737         /** Information about a single database in the environment. */
738 typedef struct MDB_db {
739         uint32_t        md_pad;         /**< also ksize for LEAF2 pages */
740         uint16_t        md_flags;       /**< @ref mdb_open */
741         uint16_t        md_depth;       /**< depth of this tree */
742         pgno_t          md_branch_pages;        /**< number of internal pages */
743         pgno_t          md_leaf_pages;          /**< number of leaf pages */
744         pgno_t          md_overflow_pages;      /**< number of overflow pages */
745         size_t          md_entries;             /**< number of data items */
746         pgno_t          md_root;                /**< the root page of this tree */
747 } MDB_db;
748
749         /** Handle for the DB used to track free pages. */
750 #define FREE_DBI        0
751         /** Handle for the default DB. */
752 #define MAIN_DBI        1
753
754         /** Meta page content. */
755 typedef struct MDB_meta {
756                 /** Stamp identifying this as an MDB file. It must be set
757                  *      to #MDB_MAGIC. */
758         uint32_t        mm_magic;
759                 /** Version number of this lock file. Must be set to #MDB_VERSION. */
760         uint32_t        mm_version;
761         void            *mm_address;            /**< address for fixed mapping */
762         size_t          mm_mapsize;                     /**< size of mmap region */
763         MDB_db          mm_dbs[2];                      /**< first is free space, 2nd is main db */
764         /** The size of pages used in this DB */
765 #define mm_psize        mm_dbs[0].md_pad
766         /** Any persistent environment flags. @ref mdb_env */
767 #define mm_flags        mm_dbs[0].md_flags
768         pgno_t          mm_last_pg;                     /**< last used page in file */
769         txnid_t         mm_txnid;                       /**< txnid that committed this page */
770 } MDB_meta;
771
772         /** Buffer for a stack-allocated dirty page.
773          *      The members define size and alignment, and silence type
774          *      aliasing warnings.  They are not used directly; that could
775          *      mean incorrectly using several union members in parallel.
776          */
777 typedef union MDB_pagebuf {
778         char            mb_raw[MDB_PAGESIZE];
779         MDB_page        mb_page;
780         struct {
781                 char            mm_pad[PAGEHDRSZ];
782                 MDB_meta        mm_meta;
783         } mb_metabuf;
784 } MDB_pagebuf;
785
786         /** Auxiliary DB info.
787          *      The information here is mostly static/read-only. There is
788          *      only a single copy of this record in the environment.
789          */
790 typedef struct MDB_dbx {
791         MDB_val         md_name;                /**< name of the database */
792         MDB_cmp_func    *md_cmp;        /**< function for comparing keys */
793         MDB_cmp_func    *md_dcmp;       /**< function for comparing data items */
794         MDB_rel_func    *md_rel;        /**< user relocate function */
795         void            *md_relctx;             /**< user-provided context for md_rel */
796 } MDB_dbx;
797
798         /** A database transaction.
799          *      Every operation requires a transaction handle.
800          */
801 struct MDB_txn {
802         MDB_txn         *mt_parent;             /**< parent of a nested txn */
803         MDB_txn         *mt_child;              /**< nested txn under this txn */
804         pgno_t          mt_next_pgno;   /**< next unallocated page */
805         /** The ID of this transaction. IDs are integers incrementing from 1.
806          *      Only committed write transactions increment the ID. If a transaction
807          *      aborts, the ID may be re-used by the next writer.
808          */
809         txnid_t         mt_txnid;
810         MDB_env         *mt_env;                /**< the DB environment */
811         /** The list of pages that became unused during this transaction.
812          */
813         IDL                     mt_free_pgs;
814         union {
815                 ID2L    dirty_list;     /**< modified pages */
816                 MDB_reader      *reader;        /**< this thread's slot in the reader table */
817         } mt_u;
818         /** Array of records for each DB known in the environment. */
819         MDB_dbx         *mt_dbxs;
820         /** Array of MDB_db records for each known DB */
821         MDB_db          *mt_dbs;
822 /** @defgroup mt_dbflag Transaction DB Flags
823  *      @ingroup internal
824  * @{
825  */
826 #define DB_DIRTY        0x01            /**< DB was written in this txn */
827 #define DB_STALE        0x02            /**< DB record is older than txnID */
828 /** @} */
829         /** Array of cursors for each DB */
830         MDB_cursor      **mt_cursors;
831         /** Array of flags for each DB */
832         unsigned char   *mt_dbflags;
833         /**     Number of DB records in use. This number only ever increments;
834          *      we don't decrement it when individual DB handles are closed.
835          */
836         MDB_dbi         mt_numdbs;
837
838 /** @defgroup mdb_txn   Transaction Flags
839  *      @ingroup internal
840  *      @{
841  */
842 #define MDB_TXN_RDONLY          0x01            /**< read-only transaction */
843 #define MDB_TXN_ERROR           0x02            /**< an error has occurred */
844 /** @} */
845         unsigned int    mt_flags;               /**< @ref mdb_txn */
846         /** Tracks which of the two meta pages was used at the start
847          *      of this transaction.
848          */
849         unsigned int    mt_toggle;
850 };
851
852 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
853  * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
854  * raise this on a 64 bit machine.
855  */
856 #define CURSOR_STACK             32
857
858 struct MDB_xcursor;
859
860         /** Cursors are used for all DB operations */
861 struct MDB_cursor {
862         /** Next cursor on this DB in this txn */
863         MDB_cursor      *mc_next;
864         /** Original cursor if this is a shadow */
865         MDB_cursor      *mc_orig;
866         /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
867         struct MDB_xcursor      *mc_xcursor;
868         /** The transaction that owns this cursor */
869         MDB_txn         *mc_txn;
870         /** The database handle this cursor operates on */
871         MDB_dbi         mc_dbi;
872         /** The database record for this cursor */
873         MDB_db          *mc_db;
874         /** The database auxiliary record for this cursor */
875         MDB_dbx         *mc_dbx;
876         /** The @ref mt_dbflag for this database */
877         unsigned char   *mc_dbflag;
878         unsigned short  mc_snum;        /**< number of pushed pages */
879         unsigned short  mc_top;         /**< index of top page, normally mc_snum-1 */
880 /** @defgroup mdb_cursor        Cursor Flags
881  *      @ingroup internal
882  *      Cursor state flags.
883  *      @{
884  */
885 #define C_INITIALIZED   0x01    /**< cursor has been initialized and is valid */
886 #define C_EOF   0x02                    /**< No more data */
887 #define C_SUB   0x04                    /**< Cursor is a sub-cursor */
888 #define C_SHADOW        0x08            /**< Cursor is a dup from a parent txn */
889 #define C_ALLOCD        0x10            /**< Cursor was malloc'd */
890 /** @} */
891         unsigned int    mc_flags;       /**< @ref mdb_cursor */
892         MDB_page        *mc_pg[CURSOR_STACK];   /**< stack of pushed pages */
893         indx_t          mc_ki[CURSOR_STACK];    /**< stack of page indices */
894 };
895
896         /** Context for sorted-dup records.
897          *      We could have gone to a fully recursive design, with arbitrarily
898          *      deep nesting of sub-databases. But for now we only handle these
899          *      levels - main DB, optional sub-DB, sorted-duplicate DB.
900          */
901 typedef struct MDB_xcursor {
902         /** A sub-cursor for traversing the Dup DB */
903         MDB_cursor mx_cursor;
904         /** The database record for this Dup DB */
905         MDB_db  mx_db;
906         /**     The auxiliary DB record for this Dup DB */
907         MDB_dbx mx_dbx;
908         /** The @ref mt_dbflag for this Dup DB */
909         unsigned char mx_dbflag;
910 } MDB_xcursor;
911
912         /** A set of pages freed by an earlier transaction. */
913 typedef struct MDB_oldpages {
914         /** Usually we only read one record from the FREEDB at a time, but
915          *      in case we read more, this will chain them together.
916          */
917         struct MDB_oldpages *mo_next;
918         /**     The ID of the transaction in which these pages were freed. */
919         txnid_t         mo_txnid;
920         /** An #IDL of the pages */
921         pgno_t          mo_pages[1];    /* dynamic */
922 } MDB_oldpages;
923
924         /** The database environment. */
925 struct MDB_env {
926         HANDLE          me_fd;          /**< The main data file */
927         HANDLE          me_lfd;         /**< The lock file */
928         HANDLE          me_mfd;                 /**< just for writing the meta pages */
929         /** Failed to update the meta page. Probably an I/O error. */
930 #define MDB_FATAL_ERROR 0x80000000U
931         uint32_t        me_flags;               /**< @ref mdb_env */
932         uint32_t        me_extrapad;    /**< unused for now */
933         unsigned int    me_maxreaders;  /**< size of the reader table */
934         MDB_dbi         me_numdbs;              /**< number of DBs opened */
935         MDB_dbi         me_maxdbs;              /**< size of the DB table */
936         char            *me_path;               /**< path to the DB files */
937         char            *me_map;                /**< the memory map of the data file */
938         MDB_txninfo     *me_txns;               /**< the memory map of the lock file */
939         MDB_meta        *me_metas[2];   /**< pointers to the two meta pages */
940         MDB_txn         *me_txn;                /**< current write transaction */
941         size_t          me_mapsize;             /**< size of the data memory map */
942         off_t           me_size;                /**< current file size */
943         pgno_t          me_maxpg;               /**< me_mapsize / me_psize */
944         unsigned int    me_psize;       /**< size of a page, from #GET_PAGESIZE */
945         unsigned int    me_db_toggle;   /**< which DB table is current */
946         txnid_t         me_wtxnid;              /**< ID of last txn we committed */
947         txnid_t         me_pgfirst;             /**< ID of first old page record we used */
948         txnid_t         me_pglast;              /**< ID of last old page record we used */
949         MDB_dbx         *me_dbxs;               /**< array of static DB info */
950         MDB_db          *me_dbs[2];             /**< two arrays of MDB_db info */
951         MDB_oldpages *me_pghead;        /**< list of old page records */
952         pthread_key_t   me_txkey;       /**< thread-key for readers */
953         MDB_page        *me_dpages;             /**< list of malloc'd blocks for re-use */
954         /** IDL of pages that became unused in a write txn */
955         IDL                     me_free_pgs;
956         /** ID2L of pages that were written during a write txn */
957         ID2                     me_dirty_list[MDB_IDL_UM_SIZE];
958         /** rwlock for the DB tables, if #LAZY_LOCKS is false */
959         LAZY_RWLOCK_DEF(me_dblock)
960 #ifdef _WIN32
961         HANDLE          me_rmutex;              /* Windows mutexes don't reside in shared mem */
962         HANDLE          me_wmutex;
963 #endif
964 #ifdef __APPLE__
965         sem_t           *me_rmutex;             /* Apple doesn't support shared mutexes */
966         sem_t           *me_wmutex;
967 #endif
968 };
969         /** max number of pages to commit in one writev() call */
970 #define MDB_COMMIT_PAGES         64
971 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
972 #undef MDB_COMMIT_PAGES
973 #define MDB_COMMIT_PAGES        IOV_MAX
974 #endif
975
976 static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
977 static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
978 static int              mdb_page_touch(MDB_cursor *mc);
979
980 static int  mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
981 static int  mdb_page_search_root(MDB_cursor *mc,
982                             MDB_val *key, int modify);
983 static int  mdb_page_search(MDB_cursor *mc,
984                             MDB_val *key, int modify);
985 static int      mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
986 static int      mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
987                                 pgno_t newpgno, unsigned int nflags);
988
989 static int  mdb_env_read_header(MDB_env *env, MDB_meta *meta);
990 static int  mdb_env_read_meta(MDB_env *env, int *which);
991 static int  mdb_env_write_meta(MDB_txn *txn);
992
993 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
994 static int  mdb_node_add(MDB_cursor *mc, indx_t indx,
995                             MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
996 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
997 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
998 static int      mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
999 static int  mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1000 static size_t   mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1001 static size_t   mdb_branch_size(MDB_env *env, MDB_val *key);
1002
1003 static int      mdb_rebalance(MDB_cursor *mc);
1004 static int      mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
1005
1006 static void     mdb_cursor_pop(MDB_cursor *mc);
1007 static int      mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1008
1009 static int      mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1010 static int      mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1011 static int      mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1012 static int      mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1013 static int      mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1014                                 int *exactp);
1015 static int      mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1016 static int      mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1017
1018 static void     mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1019 static void     mdb_xcursor_init0(MDB_cursor *mc);
1020 static void     mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1021
1022 static int      mdb_drop0(MDB_cursor *mc, int subs);
1023 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1024
1025 /** @cond */
1026 static MDB_cmp_func     mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1027 /** @endcond */
1028
1029 #ifdef _WIN32
1030 static SECURITY_DESCRIPTOR mdb_null_sd;
1031 static SECURITY_ATTRIBUTES mdb_all_sa;
1032 static int mdb_sec_inited;
1033 #endif
1034
1035 /** Return the library version info. */
1036 char *
1037 mdb_version(int *major, int *minor, int *patch)
1038 {
1039         if (major) *major = MDB_VERSION_MAJOR;
1040         if (minor) *minor = MDB_VERSION_MINOR;
1041         if (patch) *patch = MDB_VERSION_PATCH;
1042         return MDB_VERSION_STRING;
1043 }
1044
1045 /** Table of descriptions for MDB @ref errors */
1046 static char *const mdb_errstr[] = {
1047         "MDB_KEYEXIST: Key/data pair already exists",
1048         "MDB_NOTFOUND: No matching key/data pair found",
1049         "MDB_PAGE_NOTFOUND: Requested page not found",
1050         "MDB_CORRUPTED: Located page was wrong type",
1051         "MDB_PANIC: Update of meta page failed",
1052         "MDB_VERSION_MISMATCH: Database environment version mismatch"
1053 };
1054
1055 char *
1056 mdb_strerror(int err)
1057 {
1058         if (!err)
1059                 return ("Successful return: 0");
1060
1061         if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
1062                 return mdb_errstr[err - MDB_KEYEXIST];
1063
1064         return strerror(err);
1065 }
1066
1067 #if MDB_DEBUG
1068 /** Display a key in hexadecimal and return the address of the result.
1069  * @param[in] key the key to display
1070  * @param[in] buf the buffer to write into. Should always be #DKBUF.
1071  * @return The key in hexadecimal form.
1072  */
1073 char *
1074 mdb_dkey(MDB_val *key, char *buf)
1075 {
1076         char *ptr = buf;
1077         unsigned char *c = key->mv_data;
1078         unsigned int i;
1079         if (key->mv_size > MAXKEYSIZE)
1080                 return "MAXKEYSIZE";
1081         /* may want to make this a dynamic check: if the key is mostly
1082          * printable characters, print it as-is instead of converting to hex.
1083          */
1084 #if 1
1085         buf[0] = '\0';
1086         for (i=0; i<key->mv_size; i++)
1087                 ptr += sprintf(ptr, "%02x", *c++);
1088 #else
1089         sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1090 #endif
1091         return buf;
1092 }
1093
1094 /** Display all the keys in the page. */
1095 static void
1096 mdb_page_keys(MDB_page *mp)
1097 {
1098         MDB_node *node;
1099         unsigned int i, nkeys;
1100         MDB_val key;
1101         DKBUF;
1102
1103         nkeys = NUMKEYS(mp);
1104         DPRINTF("numkeys %d", nkeys);
1105         for (i=0; i<nkeys; i++) {
1106                 node = NODEPTR(mp, i);
1107                 key.mv_size = node->mn_ksize;
1108                 key.mv_data = node->mn_data;
1109                 DPRINTF("key %d: %s", i, DKEY(&key));
1110         }
1111 }
1112 #endif
1113
1114 #if MDB_DEBUG > 2
1115 /** Count all the pages in each DB and in the freelist
1116  *  and make sure it matches the actual number of pages
1117  *  being used.
1118  */
1119 static void mdb_audit(MDB_txn *txn)
1120 {
1121         MDB_cursor mc;
1122         MDB_val key, data;
1123         int rc, i;
1124         ID freecount, count;
1125
1126         freecount = 0;
1127         mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1128         while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1129                 freecount += *(ID *)data.mv_data;
1130         freecount += txn->mt_dbs[0].md_branch_pages + txn->mt_dbs[0].md_leaf_pages +
1131                 txn->mt_dbs[0].md_overflow_pages;
1132
1133         count = 0;
1134         for (i = 0; i<txn->mt_numdbs; i++) {
1135                 count += txn->mt_dbs[i].md_branch_pages +
1136                         txn->mt_dbs[i].md_leaf_pages +
1137                         txn->mt_dbs[i].md_overflow_pages;
1138                 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1139                         MDB_xcursor mx;
1140                         mdb_cursor_init(&mc, txn, i, &mx);
1141                         mdb_page_search(&mc, NULL, 0);
1142                         do {
1143                                 int j;
1144                                 MDB_page *mp;
1145                                 mp = mc.mc_pg[mc.mc_top];
1146                                 for (j=0; j<NUMKEYS(mp); j++) {
1147                                         MDB_node *leaf = NODEPTR(mp, j);
1148                                         if (leaf->mn_flags & F_SUBDATA) {
1149                                                 MDB_db db;
1150                                                 memcpy(&db, NODEDATA(leaf), sizeof(db));
1151                                                 count += db.md_branch_pages + db.md_leaf_pages +
1152                                                         db.md_overflow_pages;
1153                                         }
1154                                 }
1155                         }
1156                         while (mdb_cursor_sibling(&mc, 1) == 0);
1157                 }
1158         }
1159         assert(freecount + count + 2 >= txn->mt_next_pgno - 1);
1160 }
1161 #endif
1162
1163 int
1164 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1165 {
1166         return txn->mt_dbxs[dbi].md_cmp(a, b);
1167 }
1168
1169 int
1170 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1171 {
1172         if (txn->mt_dbxs[dbi].md_dcmp)
1173                 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1174         else
1175                 return EINVAL;  /* too bad you can't distinguish this from a valid result */
1176 }
1177
1178 /** Allocate a single page.
1179  * Re-use old malloc'd pages first, otherwise just malloc.
1180  */
1181 static MDB_page *
1182 mdb_page_malloc(MDB_cursor *mc) {
1183         MDB_page *ret;
1184         size_t sz = mc->mc_txn->mt_env->me_psize;
1185         if ((ret = mc->mc_txn->mt_env->me_dpages) != NULL) {
1186                 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1187                 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1188                 mc->mc_txn->mt_env->me_dpages = ret->mp_next;
1189         } else if ((ret = malloc(sz)) != NULL) {
1190                 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1191         }
1192         return ret;
1193 }
1194
1195 /** Allocate pages for writing.
1196  * If there are free pages available from older transactions, they
1197  * will be re-used first. Otherwise a new page will be allocated.
1198  * @param[in] mc cursor A cursor handle identifying the transaction and
1199  *      database for which we are allocating.
1200  * @param[in] num the number of pages to allocate.
1201  * @return Address of the allocated page(s). Requests for multiple pages
1202  *  will always be satisfied by a single contiguous chunk of memory.
1203  */
1204 static MDB_page *
1205 mdb_page_alloc(MDB_cursor *mc, int num)
1206 {
1207         MDB_txn *txn = mc->mc_txn;
1208         MDB_page *np;
1209         pgno_t pgno = P_INVALID;
1210         ID2 mid;
1211
1212         if (txn->mt_txnid > 2) {
1213
1214                 if (!txn->mt_env->me_pghead &&
1215                         txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1216                         /* See if there's anything in the free DB */
1217                         MDB_cursor m2;
1218                         MDB_node *leaf;
1219                         MDB_val data;
1220                         txnid_t *kptr, oldest, last;
1221
1222                         mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1223                         if (!txn->mt_env->me_pgfirst) {
1224                                 mdb_page_search(&m2, NULL, 0);
1225                                 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1226                                 kptr = (txnid_t *)NODEKEY(leaf);
1227                                 last = *kptr;
1228                         } else {
1229                                 MDB_val key;
1230                                 int rc, exact;
1231 again:
1232                                 exact = 0;
1233                                 last = txn->mt_env->me_pglast + 1;
1234                                 leaf = NULL;
1235                                 key.mv_data = &last;
1236                                 key.mv_size = sizeof(last);
1237                                 rc = mdb_cursor_set(&m2, &key, &data, MDB_SET, &exact);
1238                                 if (rc)
1239                                         goto none;
1240                                 last = *(txnid_t *)key.mv_data;
1241                         }
1242
1243                         {
1244                                 unsigned int i;
1245                                 oldest = txn->mt_txnid - 1;
1246                                 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
1247                                         txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
1248                                         if (mr && mr < oldest)
1249                                                 oldest = mr;
1250                                 }
1251                         }
1252
1253                         if (oldest > last) {
1254                                 /* It's usable, grab it.
1255                                  */
1256                                 MDB_oldpages *mop;
1257                                 pgno_t *idl;
1258
1259                                 if (!txn->mt_env->me_pgfirst) {
1260                                         mdb_node_read(txn, leaf, &data);
1261                                 }
1262                                 txn->mt_env->me_pglast = last;
1263                                 if (!txn->mt_env->me_pgfirst)
1264                                         txn->mt_env->me_pgfirst = last;
1265                                 idl = (ID *) data.mv_data;
1266                                 /* We might have a zero-length IDL due to freelist growth
1267                                  * during a prior commit
1268                                  */
1269                                 if (!idl[0]) goto again;
1270                                 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1271                                 mop->mo_next = txn->mt_env->me_pghead;
1272                                 mop->mo_txnid = last;
1273                                 txn->mt_env->me_pghead = mop;
1274                                 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1275
1276 #if MDB_DEBUG > 1
1277                                 {
1278                                         unsigned int i;
1279                                         DPRINTF("IDL read txn %zu root %zu num %zu",
1280                                                 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1281                                         for (i=0; i<idl[0]; i++) {
1282                                                 DPRINTF("IDL %zu", idl[i+1]);
1283                                         }
1284                                 }
1285 #endif
1286                         }
1287                 }
1288 none:
1289                 if (txn->mt_env->me_pghead) {
1290                         MDB_oldpages *mop = txn->mt_env->me_pghead;
1291                         if (num > 1) {
1292                                 /* FIXME: For now, always use fresh pages. We
1293                                  * really ought to search the free list for a
1294                                  * contiguous range.
1295                                  */
1296                                 ;
1297                         } else {
1298                                 /* peel pages off tail, so we only have to truncate the list */
1299                                 pgno = MDB_IDL_LAST(mop->mo_pages);
1300                                 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1301                                         mop->mo_pages[2]++;
1302                                         if (mop->mo_pages[2] > mop->mo_pages[1])
1303                                                 mop->mo_pages[0] = 0;
1304                                 } else {
1305                                         mop->mo_pages[0]--;
1306                                 }
1307                                 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1308                                         txn->mt_env->me_pghead = mop->mo_next;
1309                                         free(mop);
1310                                 }
1311                         }
1312                 }
1313         }
1314
1315         if (pgno == P_INVALID) {
1316                 /* DB size is maxed out */
1317                 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1318                         DPUTS("DB size maxed out");
1319                         return NULL;
1320                 }
1321         }
1322         if (txn->mt_env->me_dpages && num == 1) {
1323                 np = txn->mt_env->me_dpages;
1324                 VGMEMP_ALLOC(txn->mt_env, np, txn->mt_env->me_psize);
1325                 VGMEMP_DEFINED(np, sizeof(np->mp_next));
1326                 txn->mt_env->me_dpages = np->mp_next;
1327         } else {
1328                 size_t sz = txn->mt_env->me_psize * num;
1329                 if ((np = malloc(sz)) == NULL)
1330                         return NULL;
1331                 VGMEMP_ALLOC(txn->mt_env, np, sz);
1332         }
1333         if (pgno == P_INVALID) {
1334                 np->mp_pgno = txn->mt_next_pgno;
1335                 txn->mt_next_pgno += num;
1336         } else {
1337                 np->mp_pgno = pgno;
1338         }
1339         mid.mid = np->mp_pgno;
1340         mid.mptr = np;
1341         mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1342
1343         return np;
1344 }
1345
1346 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1347  * @param[in] mc cursor pointing to the page to be touched
1348  * @return 0 on success, non-zero on failure.
1349  */
1350 static int
1351 mdb_page_touch(MDB_cursor *mc)
1352 {
1353         MDB_page *mp = mc->mc_pg[mc->mc_top];
1354         pgno_t  pgno;
1355
1356         if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1357                 MDB_page *np;
1358                 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1359                         return ENOMEM;
1360                 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1361                 assert(mp->mp_pgno != np->mp_pgno);
1362                 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1363                 pgno = np->mp_pgno;
1364                 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1365                 mp = np;
1366                 mp->mp_pgno = pgno;
1367                 mp->mp_flags |= P_DIRTY;
1368
1369 finish:
1370                 /* Adjust other cursors pointing to mp */
1371                 if (mc->mc_flags & C_SUB) {
1372                         MDB_cursor *m2, *m3;
1373                         MDB_dbi dbi = mc->mc_dbi-1;
1374
1375                         for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1376                                 if (m2 == mc) continue;
1377                                 m3 = &m2->mc_xcursor->mx_cursor;
1378                                 if (m3->mc_snum < mc->mc_snum) continue;
1379                                 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1380                                         m3->mc_pg[mc->mc_top] = mp;
1381                                 }
1382                         }
1383                 } else {
1384                         MDB_cursor *m2;
1385
1386                         for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1387                                 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
1388                                 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1389                                         m2->mc_pg[mc->mc_top] = mp;
1390                                 }
1391                         }
1392                 }
1393                 mc->mc_pg[mc->mc_top] = mp;
1394                 /** If this page has a parent, update the parent to point to
1395                  * this new page.
1396                  */
1397                 if (mc->mc_top)
1398                         SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1399                 else
1400                         mc->mc_db->md_root = mp->mp_pgno;
1401         } else if (mc->mc_txn->mt_parent) {
1402                 MDB_page *np;
1403                 ID2 mid;
1404                 /* If txn has a parent, make sure the page is in our
1405                  * dirty list.
1406                  */
1407                 if (mc->mc_txn->mt_u.dirty_list[0].mid) {
1408                         unsigned x = mdb_mid2l_search(mc->mc_txn->mt_u.dirty_list, mp->mp_pgno);
1409                         if (x <= mc->mc_txn->mt_u.dirty_list[0].mid &&
1410                                 mc->mc_txn->mt_u.dirty_list[x].mid == mp->mp_pgno) {
1411                                 if (mc->mc_txn->mt_u.dirty_list[x].mptr != mp) {
1412                                         mp = mc->mc_txn->mt_u.dirty_list[x].mptr;
1413                                         mc->mc_pg[mc->mc_top] = mp;
1414                                 }
1415                                 return 0;
1416                         }
1417                 }
1418                 /* No - copy it */
1419                 np = mdb_page_malloc(mc);
1420                 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1421                 mid.mid = np->mp_pgno;
1422                 mid.mptr = np;
1423                 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &mid);
1424                 mp = np;
1425                 goto finish;
1426         }
1427         return 0;
1428 }
1429
1430 int
1431 mdb_env_sync(MDB_env *env, int force)
1432 {
1433         int rc = 0;
1434         if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1435                 if (MDB_FDATASYNC(env->me_fd))
1436                         rc = ErrCode();
1437         }
1438         return rc;
1439 }
1440
1441 /** Make shadow copies of all of parent txn's cursors */
1442 static int
1443 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1444 {
1445         MDB_cursor *mc, *m2;
1446         unsigned int i, j, size;
1447
1448         for (i=0;i<src->mt_numdbs; i++) {
1449                 if (src->mt_cursors[i]) {
1450                         size = sizeof(MDB_cursor);
1451                         if (src->mt_cursors[i]->mc_xcursor)
1452                                 size += sizeof(MDB_xcursor);
1453                         for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1454                                 mc = malloc(size);
1455                                 if (!mc)
1456                                         return ENOMEM;
1457                                 mc->mc_orig = m2;
1458                                 mc->mc_txn = dst;
1459                                 mc->mc_dbi = i;
1460                                 mc->mc_db = &dst->mt_dbs[i];
1461                                 mc->mc_dbx = m2->mc_dbx;
1462                                 mc->mc_dbflag = &dst->mt_dbflags[i];
1463                                 mc->mc_snum = m2->mc_snum;
1464                                 mc->mc_top = m2->mc_top;
1465                                 mc->mc_flags = m2->mc_flags | C_SHADOW;
1466                                 for (j=0; j<mc->mc_snum; j++) {
1467                                         mc->mc_pg[j] = m2->mc_pg[j];
1468                                         mc->mc_ki[j] = m2->mc_ki[j];
1469                                 }
1470                                 if (m2->mc_xcursor) {
1471                                         MDB_xcursor *mx, *mx2;
1472                                         mx = (MDB_xcursor *)(mc+1);
1473                                         mc->mc_xcursor = mx;
1474                                         mx2 = m2->mc_xcursor;
1475                                         mx->mx_db = mx2->mx_db;
1476                                         mx->mx_dbx = mx2->mx_dbx;
1477                                         mx->mx_dbflag = mx2->mx_dbflag;
1478                                         mx->mx_cursor.mc_txn = dst;
1479                                         mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1480                                         mx->mx_cursor.mc_db = &mx->mx_db;
1481                                         mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1482                                         mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1483                                         mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1484                                         mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1485                                         mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1486                                         for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1487                                                 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1488                                                 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1489                                         }
1490                                 } else {
1491                                         mc->mc_xcursor = NULL;
1492                                 }
1493                                 mc->mc_next = dst->mt_cursors[i];
1494                                 dst->mt_cursors[i] = mc;
1495                         }
1496                 }
1497         }
1498         return MDB_SUCCESS;
1499 }
1500
1501 /** Merge shadow cursors back into parent's */
1502 static void
1503 mdb_cursor_merge(MDB_txn *txn)
1504 {
1505         MDB_dbi i;
1506         for (i=0; i<txn->mt_numdbs; i++) {
1507                 if (txn->mt_cursors[i]) {
1508                         MDB_cursor *mc;
1509                         while ((mc = txn->mt_cursors[i])) {
1510                                 txn->mt_cursors[i] = mc->mc_next;
1511                                 if (mc->mc_flags & C_SHADOW) {
1512                                         MDB_cursor *m2 = mc->mc_orig;
1513                                         unsigned int j;
1514                                         m2->mc_snum = mc->mc_snum;
1515                                         m2->mc_top = mc->mc_top;
1516                                         for (j=0; j<mc->mc_snum; j++) {
1517                                                 m2->mc_pg[j] = mc->mc_pg[j];
1518                                                 m2->mc_ki[j] = mc->mc_ki[j];
1519                                         }
1520                                 }
1521                                 if (mc->mc_flags & C_ALLOCD)
1522                                         free(mc);
1523                         }
1524                 }
1525         }
1526 }
1527
1528 static void
1529 mdb_txn_reset0(MDB_txn *txn);
1530
1531 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1532  * @param[in] txn the transaction handle to initialize
1533  * @return 0 on success, non-zero on failure. This can only
1534  * fail for read-only transactions, and then only if the
1535  * reader table is full.
1536  */
1537 static int
1538 mdb_txn_renew0(MDB_txn *txn)
1539 {
1540         MDB_env *env = txn->mt_env;
1541         char mt_dbflag = 0;
1542
1543         if (txn->mt_flags & MDB_TXN_RDONLY) {
1544                 MDB_reader *r = pthread_getspecific(env->me_txkey);
1545                 if (!r) {
1546                         unsigned int i;
1547                         pid_t pid = getpid();
1548                         pthread_t tid = pthread_self();
1549
1550                         LOCK_MUTEX_R(env);
1551                         for (i=0; i<env->me_txns->mti_numreaders; i++)
1552                                 if (env->me_txns->mti_readers[i].mr_pid == 0)
1553                                         break;
1554                         if (i == env->me_maxreaders) {
1555                                 UNLOCK_MUTEX_R(env);
1556                                 return ENOMEM;
1557                         }
1558                         env->me_txns->mti_readers[i].mr_pid = pid;
1559                         env->me_txns->mti_readers[i].mr_tid = tid;
1560                         if (i >= env->me_txns->mti_numreaders)
1561                                 env->me_txns->mti_numreaders = i+1;
1562                         UNLOCK_MUTEX_R(env);
1563                         r = &env->me_txns->mti_readers[i];
1564                         pthread_setspecific(env->me_txkey, r);
1565                 }
1566                 txn->mt_toggle = env->me_txns->mti_me_toggle;
1567                 txn->mt_txnid = env->me_txns->mti_txnid;
1568                 /* This happens if a different process was the
1569                  * last writer to the DB.
1570                  */
1571                 if (env->me_wtxnid < txn->mt_txnid)
1572                         mt_dbflag = DB_STALE;
1573                 r->mr_txnid = txn->mt_txnid;
1574                 txn->mt_u.reader = r;
1575         } else {
1576                 LOCK_MUTEX_W(env);
1577
1578                 txn->mt_txnid = env->me_txns->mti_txnid;
1579                 if (env->me_wtxnid < txn->mt_txnid)
1580                         mt_dbflag = DB_STALE;
1581                 txn->mt_txnid++;
1582 #if MDB_DEBUG
1583                 if (txn->mt_txnid == mdb_debug_start)
1584                         mdb_debug = 1;
1585 #endif
1586                 txn->mt_toggle = env->me_txns->mti_me_toggle;
1587                 txn->mt_u.dirty_list = env->me_dirty_list;
1588                 txn->mt_u.dirty_list[0].mid = 0;
1589                 txn->mt_free_pgs = env->me_free_pgs;
1590                 txn->mt_free_pgs[0] = 0;
1591                 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1592                 env->me_txn = txn;
1593         }
1594
1595         /* Copy the DB arrays */
1596         LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1597         txn->mt_numdbs = env->me_numdbs;
1598         txn->mt_dbxs = env->me_dbxs;    /* mostly static anyway */
1599         memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1600         if (txn->mt_numdbs > 2)
1601                 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1602                         (txn->mt_numdbs - 2) * sizeof(MDB_db));
1603         LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1604
1605         memset(txn->mt_dbflags, mt_dbflag, env->me_numdbs);
1606
1607         return MDB_SUCCESS;
1608 }
1609
1610 int
1611 mdb_txn_renew(MDB_txn *txn)
1612 {
1613         int rc;
1614
1615         if (!txn)
1616                 return EINVAL;
1617
1618         if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1619                 DPUTS("environment had fatal error, must shutdown!");
1620                 return MDB_PANIC;
1621         }
1622
1623         rc = mdb_txn_renew0(txn);
1624         if (rc == MDB_SUCCESS) {
1625                 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1626                         txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1627                         (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1628         }
1629         return rc;
1630 }
1631
1632 int
1633 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1634 {
1635         MDB_txn *txn;
1636         int rc, size;
1637
1638         if (env->me_flags & MDB_FATAL_ERROR) {
1639                 DPUTS("environment had fatal error, must shutdown!");
1640                 return MDB_PANIC;
1641         }
1642         if (parent) {
1643                 /* parent already has an active child txn */
1644                 if (parent->mt_child) {
1645                         return EINVAL;
1646                 }
1647         }
1648         size = sizeof(MDB_txn) + env->me_maxdbs * (sizeof(MDB_db)+1);
1649         if (!(flags & MDB_RDONLY))
1650                 size += env->me_maxdbs * sizeof(MDB_cursor *);
1651
1652         if ((txn = calloc(1, size)) == NULL) {
1653                 DPRINTF("calloc: %s", strerror(ErrCode()));
1654                 return ENOMEM;
1655         }
1656         txn->mt_dbs = (MDB_db *)(txn+1);
1657         if (flags & MDB_RDONLY) {
1658                 txn->mt_flags |= MDB_TXN_RDONLY;
1659                 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1660         } else {
1661                 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1662                 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1663         }
1664         txn->mt_env = env;
1665
1666         if (parent) {
1667                 txn->mt_free_pgs = mdb_midl_alloc();
1668                 if (!txn->mt_free_pgs) {
1669                         free(txn);
1670                         return ENOMEM;
1671                 }
1672                 txn->mt_u.dirty_list = malloc(sizeof(ID2)*MDB_IDL_UM_SIZE);
1673                 if (!txn->mt_u.dirty_list) {
1674                         free(txn->mt_free_pgs);
1675                         free(txn);
1676                         return ENOMEM;
1677                 }
1678                 txn->mt_txnid = parent->mt_txnid;
1679                 txn->mt_toggle = parent->mt_toggle;
1680                 txn->mt_u.dirty_list[0].mid = 0;
1681                 txn->mt_free_pgs[0] = 0;
1682                 txn->mt_next_pgno = parent->mt_next_pgno;
1683                 parent->mt_child = txn;
1684                 txn->mt_parent = parent;
1685                 txn->mt_numdbs = parent->mt_numdbs;
1686                 txn->mt_dbxs = parent->mt_dbxs;
1687                 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1688                 memcpy(txn->mt_dbflags, parent->mt_dbflags, txn->mt_numdbs);
1689                 mdb_cursor_shadow(parent, txn);
1690                 rc = 0;
1691         } else {
1692                 rc = mdb_txn_renew0(txn);
1693         }
1694         if (rc)
1695                 free(txn);
1696         else {
1697                 *ret = txn;
1698                 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1699                         txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1700                         (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1701         }
1702
1703         return rc;
1704 }
1705
1706 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1707  * @param[in] txn the transaction handle to reset
1708  */
1709 static void
1710 mdb_txn_reset0(MDB_txn *txn)
1711 {
1712         MDB_env *env = txn->mt_env;
1713
1714         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1715                 txn->mt_u.reader->mr_txnid = 0;
1716         } else {
1717                 MDB_oldpages *mop;
1718                 MDB_page *dp;
1719                 unsigned int i;
1720
1721                 /* close(free) all cursors */
1722                 for (i=0; i<txn->mt_numdbs; i++) {
1723                         if (txn->mt_cursors[i]) {
1724                                 MDB_cursor *mc;
1725                                 while ((mc = txn->mt_cursors[i])) {
1726                                         txn->mt_cursors[i] = mc->mc_next;
1727                                         if (mc->mc_flags & C_ALLOCD)
1728                                                 free(mc);
1729                                 }
1730                         }
1731                 }
1732
1733                 /* return all dirty pages to dpage list */
1734                 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1735                         dp = txn->mt_u.dirty_list[i].mptr;
1736                         if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1737                                 dp->mp_next = txn->mt_env->me_dpages;
1738                                 VGMEMP_FREE(txn->mt_env, dp);
1739                                 txn->mt_env->me_dpages = dp;
1740                         } else {
1741                                 /* large pages just get freed directly */
1742                                 VGMEMP_FREE(txn->mt_env, dp);
1743                                 free(dp);
1744                         }
1745                 }
1746
1747                 if (txn->mt_parent) {
1748                         txn->mt_parent->mt_child = NULL;
1749                         free(txn->mt_free_pgs);
1750                         free(txn->mt_u.dirty_list);
1751                         return;
1752                 } else {
1753                         if (mdb_midl_shrink(&txn->mt_free_pgs))
1754                                 env->me_free_pgs = txn->mt_free_pgs;
1755                 }
1756
1757                 while ((mop = txn->mt_env->me_pghead)) {
1758                         txn->mt_env->me_pghead = mop->mo_next;
1759                         free(mop);
1760                 }
1761                 txn->mt_env->me_pgfirst = 0;
1762                 txn->mt_env->me_pglast = 0;
1763
1764                 env->me_txn = NULL;
1765                 /* The writer mutex was locked in mdb_txn_begin. */
1766                 UNLOCK_MUTEX_W(env);
1767         }
1768 }
1769
1770 void
1771 mdb_txn_reset(MDB_txn *txn)
1772 {
1773         if (txn == NULL)
1774                 return;
1775
1776         DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1777                 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1778                 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1779
1780         mdb_txn_reset0(txn);
1781 }
1782
1783 void
1784 mdb_txn_abort(MDB_txn *txn)
1785 {
1786         if (txn == NULL)
1787                 return;
1788
1789         DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1790                 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1791                 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1792
1793         if (txn->mt_child)
1794                 mdb_txn_abort(txn->mt_child);
1795
1796         mdb_txn_reset0(txn);
1797         free(txn);
1798 }
1799
1800 int
1801 mdb_txn_commit(MDB_txn *txn)
1802 {
1803         int              n, done;
1804         unsigned int i;
1805         ssize_t          rc;
1806         off_t            size;
1807         MDB_page        *dp;
1808         MDB_env *env;
1809         pgno_t  next, freecnt;
1810         MDB_cursor mc;
1811
1812         assert(txn != NULL);
1813         assert(txn->mt_env != NULL);
1814
1815         if (txn->mt_child) {
1816                 mdb_txn_commit(txn->mt_child);
1817                 txn->mt_child = NULL;
1818         }
1819
1820         env = txn->mt_env;
1821
1822         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1823                 if (txn->mt_numdbs > env->me_numdbs) {
1824                         /* update the DB tables */
1825                         int toggle = !env->me_db_toggle;
1826                         MDB_db *ip, *jp;
1827                         MDB_dbi i;
1828
1829                         ip = &env->me_dbs[toggle][env->me_numdbs];
1830                         jp = &txn->mt_dbs[env->me_numdbs];
1831                         LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1832                         for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
1833                                 *ip++ = *jp++;
1834                         }
1835
1836                         env->me_db_toggle = toggle;
1837                         env->me_numdbs = txn->mt_numdbs;
1838                         LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1839                 }
1840                 mdb_txn_abort(txn);
1841                 return MDB_SUCCESS;
1842         }
1843
1844         if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1845                 DPUTS("error flag is set, can't commit");
1846                 if (txn->mt_parent)
1847                         txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
1848                 mdb_txn_abort(txn);
1849                 return EINVAL;
1850         }
1851
1852         /* Merge (and close) our cursors with parent's */
1853         mdb_cursor_merge(txn);
1854
1855         if (txn->mt_parent) {
1856                 MDB_db *ip, *jp;
1857                 MDB_dbi i;
1858                 unsigned x, y;
1859                 ID2L dst, src;
1860
1861                 /* Update parent's DB table */
1862                 ip = &txn->mt_parent->mt_dbs[2];
1863                 jp = &txn->mt_dbs[2];
1864                 for (i = 2; i < txn->mt_numdbs; i++) {
1865                         if (ip->md_root != jp->md_root)
1866                                 *ip = *jp;
1867                         ip++; jp++;
1868                 }
1869                 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
1870
1871                 /* Append our free list to parent's */
1872                 mdb_midl_append_list(&txn->mt_parent->mt_free_pgs,
1873                         txn->mt_free_pgs);
1874                 mdb_midl_free(txn->mt_free_pgs);
1875
1876                 /* Merge our dirty list with parent's */
1877                 dst = txn->mt_parent->mt_u.dirty_list;
1878                 src = txn->mt_u.dirty_list;
1879                 x = mdb_mid2l_search(dst, src[1].mid);
1880                 for (y=1; y<=src[0].mid; y++) {
1881                         while (x <= dst[0].mid && dst[x].mid != src[y].mid) x++;
1882                         if (x > dst[0].mid)
1883                                 break;
1884                         free(dst[x].mptr);
1885                         dst[x].mptr = src[y].mptr;
1886                 }
1887                 x = dst[0].mid;
1888                 for (; y<=src[0].mid; y++) {
1889                         if (++x >= MDB_IDL_UM_MAX) {
1890                                 mdb_txn_abort(txn);
1891                                 return ENOMEM;
1892                         }
1893                         dst[x] = src[y];
1894                 }
1895                 dst[0].mid = x;
1896                 free(txn->mt_u.dirty_list);
1897                 txn->mt_parent->mt_child = NULL;
1898                 free(txn);
1899                 return MDB_SUCCESS;
1900         }
1901
1902         if (txn != env->me_txn) {
1903                 DPUTS("attempt to commit unknown transaction");
1904                 mdb_txn_abort(txn);
1905                 return EINVAL;
1906         }
1907
1908         if (!txn->mt_u.dirty_list[0].mid)
1909                 goto done;
1910
1911         DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1912             txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1913
1914         mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1915
1916         /* should only be one record now */
1917         if (env->me_pghead) {
1918                 /* make sure first page of freeDB is touched and on freelist */
1919                 mdb_page_search(&mc, NULL, 1);
1920         }
1921
1922         /* Delete IDLs we used from the free list */
1923         if (env->me_pgfirst) {
1924                 txnid_t cur;
1925                 MDB_val key;
1926                 int exact = 0;
1927
1928                 key.mv_size = sizeof(cur);
1929                 for (cur = env->me_pgfirst; cur <= env->me_pglast; cur++) {
1930                         key.mv_data = &cur;
1931
1932                         mdb_cursor_set(&mc, &key, NULL, MDB_SET, &exact);
1933                         mdb_cursor_del(&mc, 0);
1934                 }
1935                 env->me_pgfirst = 0;
1936                 env->me_pglast = 0;
1937         }
1938
1939         /* save to free list */
1940 free2:
1941         freecnt = txn->mt_free_pgs[0];
1942         if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1943                 MDB_val key, data;
1944
1945                 /* make sure last page of freeDB is touched and on freelist */
1946                 key.mv_size = MAXKEYSIZE+1;
1947                 key.mv_data = NULL;
1948                 mdb_page_search(&mc, &key, 1);
1949
1950                 mdb_midl_sort(txn->mt_free_pgs);
1951 #if MDB_DEBUG > 1
1952                 {
1953                         unsigned int i;
1954                         ID *idl = txn->mt_free_pgs;
1955                         DPRINTF("IDL write txn %zu root %zu num %zu",
1956                                 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1957                         for (i=0; i<idl[0]; i++) {
1958                                 DPRINTF("IDL %zu", idl[i+1]);
1959                         }
1960                 }
1961 #endif
1962                 /* write to last page of freeDB */
1963                 key.mv_size = sizeof(pgno_t);
1964                 key.mv_data = &txn->mt_txnid;
1965                 data.mv_data = txn->mt_free_pgs;
1966                 /* The free list can still grow during this call,
1967                  * despite the pre-emptive touches above. So check
1968                  * and make sure the entire thing got written.
1969                  */
1970                 do {
1971                         freecnt = txn->mt_free_pgs[0];
1972                         data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1973                         rc = mdb_cursor_put(&mc, &key, &data, 0);
1974                         if (rc) {
1975                                 mdb_txn_abort(txn);
1976                                 return rc;
1977                         }
1978                 } while (freecnt != txn->mt_free_pgs[0]);
1979         }
1980         /* should only be one record now */
1981 again:
1982         if (env->me_pghead) {
1983                 MDB_val key, data;
1984                 MDB_oldpages *mop;
1985                 pgno_t orig;
1986                 txnid_t id;
1987
1988                 mop = env->me_pghead;
1989                 id = mop->mo_txnid;
1990                 key.mv_size = sizeof(id);
1991                 key.mv_data = &id;
1992                 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1993                 data.mv_data = mop->mo_pages;
1994                 orig = mop->mo_pages[0];
1995                 /* These steps may grow the freelist again
1996                  * due to freed overflow pages...
1997                  */
1998                 mdb_cursor_put(&mc, &key, &data, 0);
1999                 if (mop == env->me_pghead && env->me_pghead->mo_txnid == id) {
2000                         /* could have been used again here */
2001                         if (mop->mo_pages[0] != orig) {
2002                                 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
2003                                 data.mv_data = mop->mo_pages;
2004                                 id = mop->mo_txnid;
2005                                 mdb_cursor_put(&mc, &key, &data, 0);
2006                         }
2007                         env->me_pghead = NULL;
2008                         free(mop);
2009                 } else {
2010                         /* was completely used up */
2011                         mdb_cursor_del(&mc, 0);
2012                         if (env->me_pghead)
2013                                 goto again;
2014                 }
2015                 env->me_pgfirst = 0;
2016                 env->me_pglast = 0;
2017         }
2018         /* Check for growth of freelist again */
2019         if (freecnt != txn->mt_free_pgs[0])
2020                 goto free2;
2021
2022         if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
2023                 if (mdb_midl_shrink(&txn->mt_free_pgs))
2024                         env->me_free_pgs = txn->mt_free_pgs;
2025         }
2026
2027         /* Update DB root pointers. Their pages have already been
2028          * touched so this is all in-place and cannot fail.
2029          */
2030         {
2031                 MDB_dbi i;
2032                 MDB_val data;
2033                 data.mv_size = sizeof(MDB_db);
2034
2035                 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2036                 for (i = 2; i < txn->mt_numdbs; i++) {
2037                         if (txn->mt_dbflags[i] & DB_DIRTY) {
2038                                 data.mv_data = &txn->mt_dbs[i];
2039                                 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2040                         }
2041                 }
2042         }
2043 #if MDB_DEBUG > 2
2044         mdb_audit(txn);
2045 #endif
2046
2047         /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
2048          */
2049         next = 0;
2050         i = 1;
2051         do {
2052 #ifdef _WIN32
2053                 /* Windows actually supports scatter/gather I/O, but only on
2054                  * unbuffered file handles. Since we're relying on the OS page
2055                  * cache for all our data, that's self-defeating. So we just
2056                  * write pages one at a time. We use the ov structure to set
2057                  * the write offset, to at least save the overhead of a Seek
2058                  * system call.
2059                  */
2060                 OVERLAPPED ov;
2061                 memset(&ov, 0, sizeof(ov));
2062                 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2063                         size_t wsize;
2064                         dp = txn->mt_u.dirty_list[i].mptr;
2065                         DPRINTF("committing page %zu", dp->mp_pgno);
2066                         size = dp->mp_pgno * env->me_psize;
2067                         ov.Offset = size & 0xffffffff;
2068                         ov.OffsetHigh = size >> 16;
2069                         ov.OffsetHigh >>= 16;
2070                         /* clear dirty flag */
2071                         dp->mp_flags &= ~P_DIRTY;
2072                         wsize = env->me_psize;
2073                         if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
2074                         rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
2075                         if (!rc) {
2076                                 n = ErrCode();
2077                                 DPRINTF("WriteFile: %d", n);
2078                                 mdb_txn_abort(txn);
2079                                 return n;
2080                         }
2081                 }
2082                 done = 1;
2083 #else
2084                 struct iovec     iov[MDB_COMMIT_PAGES];
2085                 n = 0;
2086                 done = 1;
2087                 size = 0;
2088                 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2089                         dp = txn->mt_u.dirty_list[i].mptr;
2090                         if (dp->mp_pgno != next) {
2091                                 if (n) {
2092                                         rc = writev(env->me_fd, iov, n);
2093                                         if (rc != size) {
2094                                                 n = ErrCode();
2095                                                 if (rc > 0)
2096                                                         DPUTS("short write, filesystem full?");
2097                                                 else
2098                                                         DPRINTF("writev: %s", strerror(n));
2099                                                 mdb_txn_abort(txn);
2100                                                 return n;
2101                                         }
2102                                         n = 0;
2103                                         size = 0;
2104                                 }
2105                                 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
2106                                 next = dp->mp_pgno;
2107                         }
2108                         DPRINTF("committing page %zu", dp->mp_pgno);
2109                         iov[n].iov_len = env->me_psize;
2110                         if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
2111                         iov[n].iov_base = (char *)dp;
2112                         size += iov[n].iov_len;
2113                         next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
2114                         /* clear dirty flag */
2115                         dp->mp_flags &= ~P_DIRTY;
2116                         if (++n >= MDB_COMMIT_PAGES) {
2117                                 done = 0;
2118                                 i++;
2119                                 break;
2120                         }
2121                 }
2122
2123                 if (n == 0)
2124                         break;
2125
2126                 rc = writev(env->me_fd, iov, n);
2127                 if (rc != size) {
2128                         n = ErrCode();
2129                         if (rc > 0)
2130                                 DPUTS("short write, filesystem full?");
2131                         else
2132                                 DPRINTF("writev: %s", strerror(n));
2133                         mdb_txn_abort(txn);
2134                         return n;
2135                 }
2136 #endif
2137         } while (!done);
2138
2139         /* Drop the dirty pages.
2140          */
2141         for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
2142                 dp = txn->mt_u.dirty_list[i].mptr;
2143                 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
2144                         dp->mp_next = txn->mt_env->me_dpages;
2145                         VGMEMP_FREE(txn->mt_env, dp);
2146                         txn->mt_env->me_dpages = dp;
2147                 } else {
2148                         VGMEMP_FREE(txn->mt_env, dp);
2149                         free(dp);
2150                 }
2151                 txn->mt_u.dirty_list[i].mid = 0;
2152         }
2153         txn->mt_u.dirty_list[0].mid = 0;
2154
2155         if ((n = mdb_env_sync(env, 0)) != 0 ||
2156             (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
2157                 mdb_txn_abort(txn);
2158                 return n;
2159         }
2160         env->me_wtxnid = txn->mt_txnid;
2161
2162 done:
2163         env->me_txn = NULL;
2164         /* update the DB tables */
2165         {
2166                 int toggle = !env->me_db_toggle;
2167                 MDB_db *ip, *jp;
2168                 MDB_dbi i;
2169
2170                 ip = &env->me_dbs[toggle][2];
2171                 jp = &txn->mt_dbs[2];
2172                 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
2173                 for (i = 2; i < txn->mt_numdbs; i++) {
2174                         if (ip->md_root != jp->md_root)
2175                                 *ip = *jp;
2176                         ip++; jp++;
2177                 }
2178
2179                 env->me_db_toggle = toggle;
2180                 env->me_numdbs = txn->mt_numdbs;
2181                 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
2182         }
2183
2184         UNLOCK_MUTEX_W(env);
2185         free(txn);
2186
2187         return MDB_SUCCESS;
2188 }
2189
2190 /** Read the environment parameters of a DB environment before
2191  * mapping it into memory.
2192  * @param[in] env the environment handle
2193  * @param[out] meta address of where to store the meta information
2194  * @return 0 on success, non-zero on failure.
2195  */
2196 static int
2197 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2198 {
2199         MDB_pagebuf     pbuf;
2200         MDB_page        *p;
2201         MDB_meta        *m;
2202         int              rc, err;
2203
2204         /* We don't know the page size yet, so use a minimum value.
2205          */
2206
2207 #ifdef _WIN32
2208         if (!ReadFile(env->me_fd, &pbuf, MDB_PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
2209 #else
2210         if ((rc = read(env->me_fd, &pbuf, MDB_PAGESIZE)) == 0)
2211 #endif
2212         {
2213                 return ENOENT;
2214         }
2215         else if (rc != MDB_PAGESIZE) {
2216                 err = ErrCode();
2217                 if (rc > 0)
2218                         err = EINVAL;
2219                 DPRINTF("read: %s", strerror(err));
2220                 return err;
2221         }
2222
2223         p = (MDB_page *)&pbuf;
2224
2225         if (!F_ISSET(p->mp_flags, P_META)) {
2226                 DPRINTF("page %zu not a meta page", p->mp_pgno);
2227                 return EINVAL;
2228         }
2229
2230         m = METADATA(p);
2231         if (m->mm_magic != MDB_MAGIC) {
2232                 DPUTS("meta has invalid magic");
2233                 return EINVAL;
2234         }
2235
2236         if (m->mm_version != MDB_VERSION) {
2237                 DPRINTF("database is version %u, expected version %u",
2238                     m->mm_version, MDB_VERSION);
2239                 return MDB_VERSION_MISMATCH;
2240         }
2241
2242         memcpy(meta, m, sizeof(*m));
2243         return 0;
2244 }
2245
2246 /** Write the environment parameters of a freshly created DB environment.
2247  * @param[in] env the environment handle
2248  * @param[out] meta address of where to store the meta information
2249  * @return 0 on success, non-zero on failure.
2250  */
2251 static int
2252 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2253 {
2254         MDB_page *p, *q;
2255         MDB_meta *m;
2256         int rc;
2257         unsigned int     psize;
2258
2259         DPUTS("writing new meta page");
2260
2261         GET_PAGESIZE(psize);
2262
2263         meta->mm_magic = MDB_MAGIC;
2264         meta->mm_version = MDB_VERSION;
2265         meta->mm_psize = psize;
2266         meta->mm_last_pg = 1;
2267         meta->mm_flags = env->me_flags & 0xffff;
2268         meta->mm_flags |= MDB_INTEGERKEY;
2269         meta->mm_dbs[0].md_root = P_INVALID;
2270         meta->mm_dbs[1].md_root = P_INVALID;
2271
2272         p = calloc(2, psize);
2273         p->mp_pgno = 0;
2274         p->mp_flags = P_META;
2275
2276         m = METADATA(p);
2277         memcpy(m, meta, sizeof(*meta));
2278
2279         q = (MDB_page *)((char *)p + psize);
2280
2281         q->mp_pgno = 1;
2282         q->mp_flags = P_META;
2283
2284         m = METADATA(q);
2285         memcpy(m, meta, sizeof(*meta));
2286
2287 #ifdef _WIN32
2288         {
2289                 DWORD len;
2290                 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2291                 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2292         }
2293 #else
2294         rc = write(env->me_fd, p, psize * 2);
2295         rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2296 #endif
2297         free(p);
2298         return rc;
2299 }
2300
2301 /** Update the environment info to commit a transaction.
2302  * @param[in] txn the transaction that's being committed
2303  * @return 0 on success, non-zero on failure.
2304  */
2305 static int
2306 mdb_env_write_meta(MDB_txn *txn)
2307 {
2308         MDB_env *env;
2309         MDB_meta        meta, metab;
2310         off_t off;
2311         int rc, len, toggle;
2312         char *ptr;
2313 #ifdef _WIN32
2314         OVERLAPPED ov;
2315 #endif
2316
2317         assert(txn != NULL);
2318         assert(txn->mt_env != NULL);
2319
2320         toggle = !txn->mt_toggle;
2321         DPRINTF("writing meta page %d for root page %zu",
2322                 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2323
2324         env = txn->mt_env;
2325
2326         metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2327         metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2328
2329         ptr = (char *)&meta;
2330         off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2331         len = sizeof(MDB_meta) - off;
2332
2333         ptr += off;
2334         meta.mm_dbs[0] = txn->mt_dbs[0];
2335         meta.mm_dbs[1] = txn->mt_dbs[1];
2336         meta.mm_last_pg = txn->mt_next_pgno - 1;
2337         meta.mm_txnid = txn->mt_txnid;
2338
2339         if (toggle)
2340                 off += env->me_psize;
2341         off += PAGEHDRSZ;
2342
2343         /* Write to the SYNC fd */
2344 #ifdef _WIN32
2345         {
2346                 memset(&ov, 0, sizeof(ov));
2347                 ov.Offset = off;
2348                 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
2349         }
2350 #else
2351         rc = pwrite(env->me_mfd, ptr, len, off);
2352 #endif
2353         if (rc != len) {
2354                 int r2;
2355                 rc = ErrCode();
2356                 DPUTS("write failed, disk error?");
2357                 /* On a failure, the pagecache still contains the new data.
2358                  * Write some old data back, to prevent it from being used.
2359                  * Use the non-SYNC fd; we know it will fail anyway.
2360                  */
2361                 meta.mm_last_pg = metab.mm_last_pg;
2362                 meta.mm_txnid = metab.mm_txnid;
2363 #ifdef _WIN32
2364                 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2365 #else
2366                 r2 = pwrite(env->me_fd, ptr, len, off);
2367 #endif
2368                 env->me_flags |= MDB_FATAL_ERROR;
2369                 return rc;
2370         }
2371         /* Memory ordering issues are irrelevant; since the entire writer
2372          * is wrapped by wmutex, all of these changes will become visible
2373          * after the wmutex is unlocked. Since the DB is multi-version,
2374          * readers will get consistent data regardless of how fresh or
2375          * how stale their view of these values is.
2376          */
2377         LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
2378         txn->mt_env->me_txns->mti_me_toggle = toggle;
2379         txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2380         LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
2381
2382         return MDB_SUCCESS;
2383 }
2384
2385 /** Check both meta pages to see which one is newer.
2386  * @param[in] env the environment handle
2387  * @param[out] which address of where to store the meta toggle ID
2388  * @return 0 on success, non-zero on failure.
2389  */
2390 static int
2391 mdb_env_read_meta(MDB_env *env, int *which)
2392 {
2393         int toggle = 0;
2394
2395         assert(env != NULL);
2396
2397         if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2398                 toggle = 1;
2399
2400         DPRINTF("Using meta page %d", toggle);
2401         *which = toggle;
2402
2403         return MDB_SUCCESS;
2404 }
2405
2406 int
2407 mdb_env_create(MDB_env **env)
2408 {
2409         MDB_env *e;
2410
2411         e = calloc(1, sizeof(MDB_env));
2412         if (!e)
2413                 return ENOMEM;
2414
2415         e->me_free_pgs = mdb_midl_alloc();
2416         if (!e->me_free_pgs) {
2417                 free(e);
2418                 return ENOMEM;
2419         }
2420         e->me_maxreaders = DEFAULT_READERS;
2421         e->me_maxdbs = 2;
2422         e->me_fd = INVALID_HANDLE_VALUE;
2423         e->me_lfd = INVALID_HANDLE_VALUE;
2424         e->me_mfd = INVALID_HANDLE_VALUE;
2425         VGMEMP_CREATE(e,0,0);
2426         *env = e;
2427         return MDB_SUCCESS;
2428 }
2429
2430 int
2431 mdb_env_set_mapsize(MDB_env *env, size_t size)
2432 {
2433         if (env->me_map)
2434                 return EINVAL;
2435         env->me_mapsize = size;
2436         if (env->me_psize)
2437                 env->me_maxpg = env->me_mapsize / env->me_psize;
2438         return MDB_SUCCESS;
2439 }
2440
2441 int
2442 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2443 {
2444         if (env->me_map)
2445                 return EINVAL;
2446         env->me_maxdbs = dbs;
2447         return MDB_SUCCESS;
2448 }
2449
2450 int
2451 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2452 {
2453         if (env->me_map || readers < 1)
2454                 return EINVAL;
2455         env->me_maxreaders = readers;
2456         return MDB_SUCCESS;
2457 }
2458
2459 int
2460 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2461 {
2462         if (!env || !readers)
2463                 return EINVAL;
2464         *readers = env->me_maxreaders;
2465         return MDB_SUCCESS;
2466 }
2467
2468 /** Further setup required for opening an MDB environment
2469  */
2470 static int
2471 mdb_env_open2(MDB_env *env, unsigned int flags)
2472 {
2473         int i, newenv = 0, toggle;
2474         MDB_meta meta;
2475         MDB_page *p;
2476
2477         env->me_flags = flags;
2478
2479         memset(&meta, 0, sizeof(meta));
2480
2481         if ((i = mdb_env_read_header(env, &meta)) != 0) {
2482                 if (i != ENOENT)
2483                         return i;
2484                 DPUTS("new mdbenv");
2485                 newenv = 1;
2486         }
2487
2488         if (!env->me_mapsize) {
2489                 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2490         }
2491
2492 #ifdef _WIN32
2493         {
2494                 HANDLE mh;
2495                 LONG sizelo, sizehi;
2496                 sizelo = env->me_mapsize & 0xffffffff;
2497                 sizehi = env->me_mapsize >> 16;         /* pointless on WIN32, only needed on W64 */
2498                 sizehi >>= 16;
2499                 /* Windows won't create mappings for zero length files.
2500                  * Just allocate the maxsize right now.
2501                  */
2502                 if (newenv) {
2503                         SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2504                         if (!SetEndOfFile(env->me_fd))
2505                                 return ErrCode();
2506                         SetFilePointer(env->me_fd, 0, NULL, 0);
2507                 }
2508                 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
2509                         sizehi, sizelo, NULL);
2510                 if (!mh)
2511                         return ErrCode();
2512                 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
2513                         meta.mm_address);
2514                 CloseHandle(mh);
2515                 if (!env->me_map)
2516                         return ErrCode();
2517         }
2518 #else
2519         i = MAP_SHARED;
2520         if (meta.mm_address && (flags & MDB_FIXEDMAP))
2521                 i |= MAP_FIXED;
2522         env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
2523                 env->me_fd, 0);
2524         if (env->me_map == MAP_FAILED) {
2525                 env->me_map = NULL;
2526                 return ErrCode();
2527         }
2528 #endif
2529
2530         if (newenv) {
2531                 meta.mm_mapsize = env->me_mapsize;
2532                 if (flags & MDB_FIXEDMAP)
2533                         meta.mm_address = env->me_map;
2534                 i = mdb_env_init_meta(env, &meta);
2535                 if (i != MDB_SUCCESS) {
2536                         munmap(env->me_map, env->me_mapsize);
2537                         return i;
2538                 }
2539         }
2540         env->me_psize = meta.mm_psize;
2541
2542         env->me_maxpg = env->me_mapsize / env->me_psize;
2543
2544         p = (MDB_page *)env->me_map;
2545         env->me_metas[0] = METADATA(p);
2546         env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2547
2548         if ((i = mdb_env_read_meta(env, &toggle)) != 0)
2549                 return i;
2550
2551         DPRINTF("opened database version %u, pagesize %u",
2552             env->me_metas[toggle]->mm_version, env->me_psize);
2553         DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
2554         DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
2555         DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
2556         DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
2557         DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
2558         DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
2559
2560         return MDB_SUCCESS;
2561 }
2562
2563 #ifndef _WIN32
2564 /** Release a reader thread's slot in the reader lock table.
2565  *      This function is called automatically when a thread exits.
2566  *      Windows doesn't support destructor callbacks for thread-specific storage,
2567  *      so this function is not compiled there.
2568  * @param[in] ptr This points to the slot in the reader lock table.
2569  */
2570 static void
2571 mdb_env_reader_dest(void *ptr)
2572 {
2573         MDB_reader *reader = ptr;
2574
2575         reader->mr_txnid = 0;
2576         reader->mr_pid = 0;
2577         reader->mr_tid = 0;
2578 }
2579 #endif
2580
2581 /** Downgrade the exclusive lock on the region back to shared */
2582 static void
2583 mdb_env_share_locks(MDB_env *env)
2584 {
2585         int toggle = 0;
2586
2587         if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2588                 toggle = 1;
2589         env->me_txns->mti_me_toggle = toggle;
2590         env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2591
2592 #ifdef _WIN32
2593         {
2594                 OVERLAPPED ov;
2595                 /* First acquire a shared lock. The Unlock will
2596                  * then release the existing exclusive lock.
2597                  */
2598                 memset(&ov, 0, sizeof(ov));
2599                 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2600                 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2601         }
2602 #else
2603         {
2604                 struct flock lock_info;
2605                 /* The shared lock replaces the existing lock */
2606                 memset((void *)&lock_info, 0, sizeof(lock_info));
2607                 lock_info.l_type = F_RDLCK;
2608                 lock_info.l_whence = SEEK_SET;
2609                 lock_info.l_start = 0;
2610                 lock_info.l_len = 1;
2611                 fcntl(env->me_lfd, F_SETLK, &lock_info);
2612         }
2613 #endif
2614 }
2615 #if defined(_WIN32) || defined(__APPLE__)
2616 /*
2617  * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2618  *
2619  * @(#) $Revision: 5.1 $
2620  * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2621  * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2622  *
2623  *        http://www.isthe.com/chongo/tech/comp/fnv/index.html
2624  *
2625  ***
2626  *
2627  * Please do not copyright this code.  This code is in the public domain.
2628  *
2629  * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2630  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2631  * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2632  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2633  * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2634  * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2635  * PERFORMANCE OF THIS SOFTWARE.
2636  *
2637  * By:
2638  *      chongo <Landon Curt Noll> /\oo/\
2639  *        http://www.isthe.com/chongo/
2640  *
2641  * Share and Enjoy!     :-)
2642  */
2643
2644 typedef unsigned long long      mdb_hash_t;
2645 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2646
2647 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2648  * @param[in] str string to hash
2649  * @param[in] hval      initial value for hash
2650  * @return 64 bit hash
2651  *
2652  * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2653  *       hval arg on the first call.
2654  */
2655 static mdb_hash_t
2656 mdb_hash_str(char *str, mdb_hash_t hval)
2657 {
2658         unsigned char *s = (unsigned char *)str;        /* unsigned string */
2659         /*
2660          * FNV-1a hash each octet of the string
2661          */
2662         while (*s) {
2663                 /* xor the bottom with the current octet */
2664                 hval ^= (mdb_hash_t)*s++;
2665
2666                 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2667                 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2668                         (hval << 7) + (hval << 8) + (hval << 40);
2669         }
2670         /* return our new hash value */
2671         return hval;
2672 }
2673
2674 /** Hash the string and output the hash in hex.
2675  * @param[in] str string to hash
2676  * @param[out] hexbuf an array of 17 chars to hold the hash
2677  */
2678 static void
2679 mdb_hash_hex(char *str, char *hexbuf)
2680 {
2681         int i;
2682         mdb_hash_t h = mdb_hash_str(str, MDB_HASH_INIT);
2683         for (i=0; i<8; i++) {
2684                 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2685                 h >>= 8;
2686         }
2687 }
2688 #endif
2689
2690 /** Open and/or initialize the lock region for the environment.
2691  * @param[in] env The MDB environment.
2692  * @param[in] lpath The pathname of the file used for the lock region.
2693  * @param[in] mode The Unix permissions for the file, if we create it.
2694  * @param[out] excl Set to true if we got an exclusive lock on the region.
2695  * @return 0 on success, non-zero on failure.
2696  */
2697 static int
2698 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2699 {
2700         int rc;
2701         off_t size, rsize;
2702
2703         *excl = 0;
2704
2705 #ifdef _WIN32
2706         if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2707                 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2708                 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2709                 rc = ErrCode();
2710                 return rc;
2711         }
2712         /* Try to get exclusive lock. If we succeed, then
2713          * nobody is using the lock region and we should initialize it.
2714          */
2715         {
2716                 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2717                         *excl = 1;
2718                 } else {
2719                         OVERLAPPED ov;
2720                         memset(&ov, 0, sizeof(ov));
2721                         if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2722                                 rc = ErrCode();
2723                                 goto fail;
2724                         }
2725                 }
2726         }
2727         size = GetFileSize(env->me_lfd, NULL);
2728 #else
2729         if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2730                 rc = ErrCode();
2731                 return rc;
2732         }
2733         /* Try to get exclusive lock. If we succeed, then
2734          * nobody is using the lock region and we should initialize it.
2735          */
2736         {
2737                 struct flock lock_info;
2738                 memset((void *)&lock_info, 0, sizeof(lock_info));
2739                 lock_info.l_type = F_WRLCK;
2740                 lock_info.l_whence = SEEK_SET;
2741                 lock_info.l_start = 0;
2742                 lock_info.l_len = 1;
2743                 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2744                 if (rc == 0) {
2745                         *excl = 1;
2746                 } else {
2747                         lock_info.l_type = F_RDLCK;
2748                         rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2749                         if (rc) {
2750                                 rc = ErrCode();
2751                                 goto fail;
2752                         }
2753                 }
2754         }
2755         size = lseek(env->me_lfd, 0, SEEK_END);
2756 #endif
2757         rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2758         if (size < rsize && *excl) {
2759 #ifdef _WIN32
2760                 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2761                 if (!SetEndOfFile(env->me_lfd)) {
2762                         rc = ErrCode();
2763                         goto fail;
2764                 }
2765 #else
2766                 if (ftruncate(env->me_lfd, rsize) != 0) {
2767                         rc = ErrCode();
2768                         goto fail;
2769                 }
2770 #endif
2771         } else {
2772                 rsize = size;
2773                 size = rsize - sizeof(MDB_txninfo);
2774                 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2775         }
2776         {
2777 #ifdef _WIN32
2778                 HANDLE mh;
2779                 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2780                         0, 0, NULL);
2781                 if (!mh) {
2782                         rc = ErrCode();
2783                         goto fail;
2784                 }
2785                 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2786                 CloseHandle(mh);
2787                 if (!env->me_txns) {
2788                         rc = ErrCode();
2789                         goto fail;
2790                 }
2791 #else
2792                 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2793                         env->me_lfd, 0);
2794                 if (m == MAP_FAILED) {
2795                         env->me_txns = NULL;
2796                         rc = ErrCode();
2797                         goto fail;
2798                 }
2799                 env->me_txns = m;
2800 #endif
2801         }
2802         if (*excl) {
2803 #ifdef _WIN32
2804                 char hexbuf[17];
2805                 if (!mdb_sec_inited) {
2806                         InitializeSecurityDescriptor(&mdb_null_sd,
2807                                 SECURITY_DESCRIPTOR_REVISION);
2808                         SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2809                         mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2810                         mdb_all_sa.bInheritHandle = FALSE;
2811                         mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2812                         mdb_sec_inited = 1;
2813                 }
2814                 mdb_hash_hex(lpath, hexbuf);
2815                 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2816                 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2817                 if (!env->me_rmutex) {
2818                         rc = ErrCode();
2819                         goto fail;
2820                 }
2821                 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2822                 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2823                 if (!env->me_wmutex) {
2824                         rc = ErrCode();
2825                         goto fail;
2826                 }
2827 #else   /* _WIN32 */
2828 #ifdef __APPLE__
2829                 char hexbuf[17];
2830                 mdb_hash_hex(lpath, hexbuf);
2831                 sprintf(env->me_txns->mti_rmname, "MDBr%s", hexbuf);
2832                 if (sem_unlink(env->me_txns->mti_rmname)) {
2833                         rc = ErrCode();
2834                         if (rc != ENOENT && rc != EINVAL)
2835                                 goto fail;
2836                 }
2837                 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2838                 if (!env->me_rmutex) {
2839                         rc = ErrCode();
2840                         goto fail;
2841                 }
2842                 sprintf(env->me_txns->mti_wmname, "MDBw%s", hexbuf);
2843                 if (sem_unlink(env->me_txns->mti_wmname)) {
2844                         rc = ErrCode();
2845                         if (rc != ENOENT && rc != EINVAL)
2846                                 goto fail;
2847                 }
2848                 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2849                 if (!env->me_wmutex) {
2850                         rc = ErrCode();
2851                         goto fail;
2852                 }
2853 #else   /* __APPLE__ */
2854                 pthread_mutexattr_t mattr;
2855
2856                 pthread_mutexattr_init(&mattr);
2857                 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2858                 if (rc) {
2859                         goto fail;
2860                 }
2861                 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2862                 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2863 #endif  /* __APPLE__ */
2864 #endif  /* _WIN32 */
2865                 env->me_txns->mti_version = MDB_VERSION;
2866                 env->me_txns->mti_magic = MDB_MAGIC;
2867                 env->me_txns->mti_txnid = 0;
2868                 env->me_txns->mti_numreaders = 0;
2869                 env->me_txns->mti_me_toggle = 0;
2870
2871         } else {
2872                 if (env->me_txns->mti_magic != MDB_MAGIC) {
2873                         DPUTS("lock region has invalid magic");
2874                         rc = EINVAL;
2875                         goto fail;
2876                 }
2877                 if (env->me_txns->mti_version != MDB_VERSION) {
2878                         DPRINTF("lock region is version %u, expected version %u",
2879                                 env->me_txns->mti_version, MDB_VERSION);
2880                         rc = MDB_VERSION_MISMATCH;
2881                         goto fail;
2882                 }
2883                 rc = ErrCode();
2884                 if (rc != EACCES && rc != EAGAIN) {
2885                         goto fail;
2886                 }
2887 #ifdef _WIN32
2888                 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2889                 if (!env->me_rmutex) {
2890                         rc = ErrCode();
2891                         goto fail;
2892                 }
2893                 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2894                 if (!env->me_wmutex) {
2895                         rc = ErrCode();
2896                         goto fail;
2897                 }
2898 #endif
2899 #ifdef __APPLE__
2900                 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2901                 if (!env->me_rmutex) {
2902                         rc = ErrCode();
2903                         goto fail;
2904                 }
2905                 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2906                 if (!env->me_wmutex) {
2907                         rc = ErrCode();
2908                         goto fail;
2909                 }
2910 #endif
2911         }
2912         return MDB_SUCCESS;
2913
2914 fail:
2915         close(env->me_lfd);
2916         env->me_lfd = INVALID_HANDLE_VALUE;
2917         return rc;
2918
2919 }
2920
2921         /** The name of the lock file in the DB environment */
2922 #define LOCKNAME        "/lock.mdb"
2923         /** The name of the data file in the DB environment */
2924 #define DATANAME        "/data.mdb"
2925         /** The suffix of the lock file when no subdir is used */
2926 #define LOCKSUFF        "-lock"
2927
2928 int
2929 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2930 {
2931         int             oflags, rc, len, excl;
2932         char *lpath, *dpath;
2933
2934         len = strlen(path);
2935         if (flags & MDB_NOSUBDIR) {
2936                 rc = len + sizeof(LOCKSUFF) + len + 1;
2937         } else {
2938                 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
2939         }
2940         lpath = malloc(rc);
2941         if (!lpath)
2942                 return ENOMEM;
2943         if (flags & MDB_NOSUBDIR) {
2944                 dpath = lpath + len + sizeof(LOCKSUFF);
2945                 sprintf(lpath, "%s" LOCKSUFF, path);
2946                 strcpy(dpath, path);
2947         } else {
2948                 dpath = lpath + len + sizeof(LOCKNAME);
2949                 sprintf(lpath, "%s" LOCKNAME, path);
2950                 sprintf(dpath, "%s" DATANAME, path);
2951         }
2952
2953         rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2954         if (rc)
2955                 goto leave;
2956
2957 #ifdef _WIN32
2958         if (F_ISSET(flags, MDB_RDONLY)) {
2959                 oflags = GENERIC_READ;
2960                 len = OPEN_EXISTING;
2961         } else {
2962                 oflags = GENERIC_READ|GENERIC_WRITE;
2963                 len = OPEN_ALWAYS;
2964         }
2965         mode = FILE_ATTRIBUTE_NORMAL;
2966         if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2967                         NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2968                 rc = ErrCode();
2969                 goto leave;
2970         }
2971 #else
2972         if (F_ISSET(flags, MDB_RDONLY))
2973                 oflags = O_RDONLY;
2974         else
2975                 oflags = O_RDWR | O_CREAT;
2976
2977         if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2978                 rc = ErrCode();
2979                 goto leave;
2980         }
2981 #endif
2982
2983         if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2984                 /* synchronous fd for meta writes */
2985 #ifdef _WIN32
2986                 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2987                         mode |= FILE_FLAG_WRITE_THROUGH;
2988                 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2989                         NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2990                         rc = ErrCode();
2991                         goto leave;
2992                 }
2993 #else
2994                 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2995                         oflags |= MDB_DSYNC;
2996                 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2997                         rc = ErrCode();
2998                         goto leave;
2999                 }
3000 #endif
3001                 env->me_path = strdup(path);
3002                 DPRINTF("opened dbenv %p", (void *) env);
3003                 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3004                 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
3005                 if (excl)
3006                         mdb_env_share_locks(env);
3007                 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3008                 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
3009                 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
3010                 env->me_numdbs = 2;
3011         }
3012
3013 leave:
3014         if (rc) {
3015                 if (env->me_fd != INVALID_HANDLE_VALUE) {
3016                         close(env->me_fd);
3017                         env->me_fd = INVALID_HANDLE_VALUE;
3018                 }
3019                 if (env->me_lfd != INVALID_HANDLE_VALUE) {
3020                         close(env->me_lfd);
3021                         env->me_lfd = INVALID_HANDLE_VALUE;
3022                 }
3023         }
3024         free(lpath);
3025         return rc;
3026 }
3027
3028 void
3029 mdb_env_close(MDB_env *env)
3030 {
3031         MDB_page *dp;
3032
3033         if (env == NULL)
3034                 return;
3035
3036         VGMEMP_DESTROY(env);
3037         while (env->me_dpages) {
3038                 dp = env->me_dpages;
3039                 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
3040                 env->me_dpages = dp->mp_next;
3041                 free(dp);
3042         }
3043
3044         free(env->me_dbs[1]);
3045         free(env->me_dbs[0]);
3046         free(env->me_dbxs);
3047         free(env->me_path);
3048
3049         LAZY_RWLOCK_DESTROY(&env->me_dblock);
3050         pthread_key_delete(env->me_txkey);
3051
3052         if (env->me_map) {
3053                 munmap(env->me_map, env->me_mapsize);
3054         }
3055         close(env->me_mfd);
3056         close(env->me_fd);
3057         if (env->me_txns) {
3058                 pid_t pid = getpid();
3059                 unsigned int i;
3060                 for (i=0; i<env->me_txns->mti_numreaders; i++)
3061                         if (env->me_txns->mti_readers[i].mr_pid == pid)
3062                                 env->me_txns->mti_readers[i].mr_pid = 0;
3063                 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
3064         }
3065         close(env->me_lfd);
3066         mdb_midl_free(env->me_free_pgs);
3067         free(env);
3068 }
3069
3070 /** Compare two items pointing at aligned size_t's */
3071 static int
3072 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
3073 {
3074         return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
3075                 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
3076 }
3077
3078 /** Compare two items pointing at aligned int's */
3079 static int
3080 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
3081 {
3082         return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
3083                 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
3084 }
3085
3086 /** Compare two items pointing at ints of unknown alignment.
3087  *      Nodes and keys are guaranteed to be 2-byte aligned.
3088  */
3089 static int
3090 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
3091 {
3092 #if BYTE_ORDER == LITTLE_ENDIAN
3093         unsigned short *u, *c;
3094         int x;
3095
3096         u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
3097         c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
3098         do {
3099                 x = *--u - *--c;
3100         } while(!x && u > (unsigned short *)a->mv_data);
3101         return x;
3102 #else
3103         return memcmp(a->mv_data, b->mv_data, a->mv_size);
3104 #endif
3105 }
3106
3107 /** Compare two items lexically */
3108 static int
3109 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
3110 {
3111         int diff;
3112         ssize_t len_diff;
3113         unsigned int len;
3114
3115         len = a->mv_size;
3116         len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3117         if (len_diff > 0) {
3118                 len = b->mv_size;
3119                 len_diff = 1;
3120         }
3121
3122         diff = memcmp(a->mv_data, b->mv_data, len);
3123         return diff ? diff : len_diff<0 ? -1 : len_diff;
3124 }
3125
3126 /** Compare two items in reverse byte order */
3127 static int
3128 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
3129 {
3130         const unsigned char     *p1, *p2, *p1_lim;
3131         ssize_t len_diff;
3132         int diff;
3133
3134         p1_lim = (const unsigned char *)a->mv_data;
3135         p1 = (const unsigned char *)a->mv_data + a->mv_size;
3136         p2 = (const unsigned char *)b->mv_data + b->mv_size;
3137
3138         len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3139         if (len_diff > 0) {
3140                 p1_lim += len_diff;
3141                 len_diff = 1;
3142         }
3143
3144         while (p1 > p1_lim) {
3145                 diff = *--p1 - *--p2;
3146                 if (diff)
3147                         return diff;
3148         }
3149         return len_diff<0 ? -1 : len_diff;
3150 }
3151
3152 /** Search for key within a page, using binary search.
3153  * Returns the smallest entry larger or equal to the key.
3154  * If exactp is non-null, stores whether the found entry was an exact match
3155  * in *exactp (1 or 0).
3156  * Updates the cursor index with the index of the found entry.
3157  * If no entry larger or equal to the key is found, returns NULL.
3158  */
3159 static MDB_node *
3160 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
3161 {
3162         unsigned int     i = 0, nkeys;
3163         int              low, high;
3164         int              rc = 0;
3165         MDB_page *mp = mc->mc_pg[mc->mc_top];
3166         MDB_node        *node = NULL;
3167         MDB_val  nodekey;
3168         MDB_cmp_func *cmp;
3169         DKBUF;
3170
3171         nkeys = NUMKEYS(mp);
3172
3173 #if MDB_DEBUG
3174         {
3175         pgno_t pgno;
3176         COPY_PGNO(pgno, mp->mp_pgno);
3177         DPRINTF("searching %u keys in %s %spage %zu",
3178             nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
3179             pgno);
3180         }
3181 #endif
3182
3183         assert(nkeys > 0);
3184
3185         low = IS_LEAF(mp) ? 0 : 1;
3186         high = nkeys - 1;
3187         cmp = mc->mc_dbx->md_cmp;
3188
3189         /* Branch pages have no data, so if using integer keys,
3190          * alignment is guaranteed. Use faster mdb_cmp_int.
3191          */
3192         if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
3193                 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
3194                         cmp = mdb_cmp_long;
3195                 else
3196                         cmp = mdb_cmp_int;
3197         }
3198
3199         if (IS_LEAF2(mp)) {
3200                 nodekey.mv_size = mc->mc_db->md_pad;
3201                 node = NODEPTR(mp, 0);  /* fake */
3202                 while (low <= high) {
3203                         i = (low + high) >> 1;
3204                         nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
3205                         rc = cmp(key, &nodekey);
3206                         DPRINTF("found leaf index %u [%s], rc = %i",
3207                             i, DKEY(&nodekey), rc);
3208                         if (rc == 0)
3209                                 break;
3210                         if (rc > 0)
3211                                 low = i + 1;
3212                         else
3213                                 high = i - 1;
3214                 }
3215         } else {
3216                 while (low <= high) {
3217                         i = (low + high) >> 1;
3218
3219                         node = NODEPTR(mp, i);
3220                         nodekey.mv_size = NODEKSZ(node);
3221                         nodekey.mv_data = NODEKEY(node);
3222
3223                         rc = cmp(key, &nodekey);
3224 #if MDB_DEBUG
3225                         if (IS_LEAF(mp))
3226                                 DPRINTF("found leaf index %u [%s], rc = %i",
3227                                     i, DKEY(&nodekey), rc);
3228                         else
3229                                 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
3230                                     i, DKEY(&nodekey), NODEPGNO(node), rc);
3231 #endif
3232                         if (rc == 0)
3233                                 break;
3234                         if (rc > 0)
3235                                 low = i + 1;
3236                         else
3237                                 high = i - 1;
3238                 }
3239         }
3240
3241         if (rc > 0) {   /* Found entry is less than the key. */
3242                 i++;    /* Skip to get the smallest entry larger than key. */
3243                 if (!IS_LEAF2(mp))
3244                         node = NODEPTR(mp, i);
3245         }
3246         if (exactp)
3247                 *exactp = (rc == 0);
3248         /* store the key index */
3249         mc->mc_ki[mc->mc_top] = i;
3250         if (i >= nkeys)
3251                 /* There is no entry larger or equal to the key. */
3252                 return NULL;
3253
3254         /* nodeptr is fake for LEAF2 */
3255         return node;
3256 }
3257
3258 #if 0
3259 static void
3260 mdb_cursor_adjust(MDB_cursor *mc, func)
3261 {
3262         MDB_cursor *m2;
3263
3264         for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3265                 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3266                         func(mc, m2);
3267                 }
3268         }
3269 }
3270 #endif
3271
3272 /** Pop a page off the top of the cursor's stack. */
3273 static void
3274 mdb_cursor_pop(MDB_cursor *mc)
3275 {
3276         MDB_page        *top;
3277
3278         if (mc->mc_snum) {
3279                 top = mc->mc_pg[mc->mc_top];
3280                 mc->mc_snum--;
3281                 if (mc->mc_snum)
3282                         mc->mc_top--;
3283
3284                 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3285                         mc->mc_dbi, (void *) mc);
3286         }
3287 }
3288
3289 /** Push a page onto the top of the cursor's stack. */
3290 static int
3291 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3292 {
3293         DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3294                 mc->mc_dbi, (void *) mc);
3295
3296         if (mc->mc_snum >= CURSOR_STACK) {
3297                 assert(mc->mc_snum < CURSOR_STACK);
3298                 return ENOMEM;
3299         }
3300
3301         mc->mc_top = mc->mc_snum++;
3302         mc->mc_pg[mc->mc_top] = mp;
3303         mc->mc_ki[mc->mc_top] = 0;
3304
3305         return MDB_SUCCESS;
3306 }
3307
3308 /** Find the address of the page corresponding to a given page number.
3309  * @param[in] txn the transaction for this access.
3310  * @param[in] pgno the page number for the page to retrieve.
3311  * @param[out] ret address of a pointer where the page's address will be stored.
3312  * @return 0 on success, non-zero on failure.
3313  */
3314 static int
3315 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3316 {
3317         MDB_page *p = NULL;
3318
3319         if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3320                 unsigned x;
3321                 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3322                 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3323                         p = txn->mt_u.dirty_list[x].mptr;
3324                 }
3325         }
3326         if (!p) {
3327                 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
3328                         p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3329         }
3330         *ret = p;
3331         if (!p) {
3332                 DPRINTF("page %zu not found", pgno);
3333                 assert(p != NULL);
3334         }
3335         return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3336 }
3337
3338 /** Search for the page a given key should be in.
3339  * Pushes parent pages on the cursor stack. This function continues a
3340  * search on a cursor that has already been initialized. (Usually by
3341  * #mdb_page_search() but also by #mdb_node_move().)
3342  * @param[in,out] mc the cursor for this operation.
3343  * @param[in] key the key to search for. If NULL, search for the lowest
3344  * page. (This is used by #mdb_cursor_first().)
3345  * @param[in] modify If true, visited pages are updated with new page numbers.
3346  * @return 0 on success, non-zero on failure.
3347  */
3348 static int
3349 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3350 {
3351         MDB_page        *mp = mc->mc_pg[mc->mc_top];
3352         DKBUF;
3353         int rc;
3354
3355
3356         while (IS_BRANCH(mp)) {
3357                 MDB_node        *node;
3358                 indx_t          i;
3359
3360                 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3361                 assert(NUMKEYS(mp) > 1);
3362                 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3363
3364                 if (key == NULL)        /* Initialize cursor to first page. */
3365                         i = 0;
3366                 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
3367                                                         /* cursor to last page */
3368                         i = NUMKEYS(mp)-1;
3369                 } else {
3370                         int      exact;
3371                         node = mdb_node_search(mc, key, &exact);
3372                         if (node == NULL)
3373                                 i = NUMKEYS(mp) - 1;
3374                         else {
3375                                 i = mc->mc_ki[mc->mc_top];
3376                                 if (!exact) {
3377                                         assert(i > 0);
3378                                         i--;
3379                                 }
3380                         }
3381                 }
3382
3383                 if (key)
3384                         DPRINTF("following index %u for key [%s]",
3385                             i, DKEY(key));
3386                 assert(i < NUMKEYS(mp));
3387                 node = NODEPTR(mp, i);
3388
3389                 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3390                         return rc;
3391
3392                 mc->mc_ki[mc->mc_top] = i;
3393                 if ((rc = mdb_cursor_push(mc, mp)))
3394                         return rc;
3395
3396                 if (modify) {
3397                         if ((rc = mdb_page_touch(mc)) != 0)
3398                                 return rc;
3399                         mp = mc->mc_pg[mc->mc_top];
3400                 }
3401         }
3402
3403         if (!IS_LEAF(mp)) {
3404                 DPRINTF("internal error, index points to a %02X page!?",
3405                     mp->mp_flags);
3406                 return MDB_CORRUPTED;
3407         }
3408
3409         DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
3410             key ? DKEY(key) : NULL);
3411
3412         return MDB_SUCCESS;
3413 }
3414
3415 /** Search for the page a given key should be in.
3416  * Pushes parent pages on the cursor stack. This function just sets up
3417  * the search; it finds the root page for \b mc's database and sets this
3418  * as the root of the cursor's stack. Then #mdb_page_search_root() is
3419  * called to complete the search.
3420  * @param[in,out] mc the cursor for this operation.
3421  * @param[in] key the key to search for. If NULL, search for the lowest
3422  * page. (This is used by #mdb_cursor_first().)
3423  * @param[in] modify If true, visited pages are updated with new page numbers.
3424  * @return 0 on success, non-zero on failure.
3425  */
3426 static int
3427 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
3428 {
3429         int              rc;
3430         pgno_t           root;
3431
3432         /* Make sure the txn is still viable, then find the root from
3433          * the txn's db table.
3434          */
3435         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
3436                 DPUTS("transaction has failed, must abort");
3437                 return EINVAL;
3438         } else {
3439                 /* Make sure we're using an up-to-date root */
3440                 if (mc->mc_dbi > MAIN_DBI) {
3441                         if ((*mc->mc_dbflag & DB_STALE) ||
3442                         (modify && !(*mc->mc_dbflag & DB_DIRTY))) {
3443                                 MDB_cursor mc2;
3444                                 unsigned char dbflag = 0;
3445                                 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3446                                 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, modify);
3447                                 if (rc)
3448                                         return rc;
3449                                 if (*mc->mc_dbflag & DB_STALE) {
3450                                         MDB_val data;
3451                                         int exact = 0;
3452                                         MDB_node *leaf = mdb_node_search(&mc2,
3453                                                 &mc->mc_dbx->md_name, &exact);
3454                                         if (!exact)
3455                                                 return MDB_NOTFOUND;
3456                                         mdb_node_read(mc->mc_txn, leaf, &data);
3457                                         memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
3458                                 }
3459                                 if (modify)
3460                                         dbflag = DB_DIRTY;
3461                                 *mc->mc_dbflag = dbflag;
3462                         }
3463                 }
3464                 root = mc->mc_db->md_root;
3465
3466                 if (root == P_INVALID) {                /* Tree is empty. */
3467                         DPUTS("tree is empty");
3468                         return MDB_NOTFOUND;
3469                 }
3470         }
3471
3472         assert(root > 1);
3473         if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
3474                 return rc;
3475
3476         mc->mc_snum = 1;
3477         mc->mc_top = 0;
3478
3479         DPRINTF("db %u root page %zu has flags 0x%X",
3480                 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
3481
3482         if (modify) {
3483                 if ((rc = mdb_page_touch(mc)))
3484                         return rc;
3485         }
3486
3487         return mdb_page_search_root(mc, key, modify);
3488 }
3489
3490 /** Return the data associated with a given node.
3491  * @param[in] txn The transaction for this operation.
3492  * @param[in] leaf The node being read.
3493  * @param[out] data Updated to point to the node's data.
3494  * @return 0 on success, non-zero on failure.
3495  */
3496 static int
3497 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
3498 {
3499         MDB_page        *omp;           /* overflow page */
3500         pgno_t           pgno;
3501         int rc;
3502
3503         if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3504                 data->mv_size = NODEDSZ(leaf);
3505                 data->mv_data = NODEDATA(leaf);
3506                 return MDB_SUCCESS;
3507         }
3508
3509         /* Read overflow data.
3510          */
3511         data->mv_size = NODEDSZ(leaf);
3512         memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
3513         if ((rc = mdb_page_get(txn, pgno, &omp))) {
3514                 DPRINTF("read overflow page %zu failed", pgno);
3515                 return rc;
3516         }
3517         data->mv_data = METADATA(omp);
3518
3519         return MDB_SUCCESS;
3520 }
3521
3522 int
3523 mdb_get(MDB_txn *txn, MDB_dbi dbi,
3524     MDB_val *key, MDB_val *data)
3525 {
3526         MDB_cursor      mc;
3527         MDB_xcursor     mx;
3528         int exact = 0;
3529         DKBUF;
3530
3531         assert(key);
3532         assert(data);
3533         DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
3534
3535         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3536                 return EINVAL;
3537
3538         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3539                 return EINVAL;
3540         }
3541
3542         mdb_cursor_init(&mc, txn, dbi, &mx);
3543         return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
3544 }
3545
3546 /** Find a sibling for a page.
3547  * Replaces the page at the top of the cursor's stack with the
3548  * specified sibling, if one exists.
3549  * @param[in] mc The cursor for this operation.
3550  * @param[in] move_right Non-zero if the right sibling is requested,
3551  * otherwise the left sibling.
3552  * @return 0 on success, non-zero on failure.
3553  */
3554 static int
3555 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
3556 {
3557         int              rc;
3558         MDB_node        *indx;
3559         MDB_page        *mp;
3560
3561         if (mc->mc_snum < 2) {
3562                 return MDB_NOTFOUND;            /* root has no siblings */
3563         }
3564
3565         mdb_cursor_pop(mc);
3566         DPRINTF("parent page is page %zu, index %u",
3567                 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
3568
3569         if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
3570                        : (mc->mc_ki[mc->mc_top] == 0)) {
3571                 DPRINTF("no more keys left, moving to %s sibling",
3572                     move_right ? "right" : "left");
3573                 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
3574                         return rc;
3575         } else {
3576                 if (move_right)
3577                         mc->mc_ki[mc->mc_top]++;
3578                 else
3579                         mc->mc_ki[mc->mc_top]--;
3580                 DPRINTF("just moving to %s index key %u",
3581                     move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3582         }
3583         assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3584
3585         indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3586         if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3587                 return rc;;
3588
3589         mdb_cursor_push(mc, mp);
3590
3591         return MDB_SUCCESS;
3592 }
3593
3594 /** Move the cursor to the next data item. */
3595 static int
3596 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3597 {
3598         MDB_page        *mp;
3599         MDB_node        *leaf;
3600         int rc;
3601
3602         if (mc->mc_flags & C_EOF) {
3603                 return MDB_NOTFOUND;
3604         }
3605
3606         assert(mc->mc_flags & C_INITIALIZED);
3607
3608         mp = mc->mc_pg[mc->mc_top];
3609
3610         if (mc->mc_db->md_flags & MDB_DUPSORT) {
3611                 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3612                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3613                         if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3614                                 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3615                                 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3616                                         return rc;
3617                         }
3618                 } else {
3619                         mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3620                         if (op == MDB_NEXT_DUP)
3621                                 return MDB_NOTFOUND;
3622                 }
3623         }
3624
3625         DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3626
3627         if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3628                 DPUTS("=====> move to next sibling page");
3629                 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3630                         mc->mc_flags |= C_EOF;
3631                         mc->mc_flags &= ~C_INITIALIZED;
3632                         return MDB_NOTFOUND;
3633                 }
3634                 mp = mc->mc_pg[mc->mc_top];
3635                 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3636         } else
3637                 mc->mc_ki[mc->mc_top]++;
3638
3639         DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3640             mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3641
3642         if (IS_LEAF2(mp)) {
3643                 key->mv_size = mc->mc_db->md_pad;
3644                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3645                 return MDB_SUCCESS;
3646         }
3647
3648         assert(IS_LEAF(mp));
3649         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3650
3651         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3652                 mdb_xcursor_init1(mc, leaf);
3653         }
3654         if (data) {
3655                 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3656                         return rc;
3657
3658                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3659                         rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3660                         if (rc != MDB_SUCCESS)
3661                                 return rc;
3662                 }
3663         }
3664
3665         MDB_SET_KEY(leaf, key);
3666         return MDB_SUCCESS;
3667 }
3668
3669 /** Move the cursor to the previous data item. */
3670 static int
3671 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3672 {
3673         MDB_page        *mp;
3674         MDB_node        *leaf;
3675         int rc;
3676
3677         assert(mc->mc_flags & C_INITIALIZED);
3678
3679         mp = mc->mc_pg[mc->mc_top];
3680
3681         if (mc->mc_db->md_flags & MDB_DUPSORT) {
3682                 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3683                 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3684                         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3685                                 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3686                                 if (op != MDB_PREV || rc == MDB_SUCCESS)
3687                                         return rc;
3688                         } else {
3689                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3690                                 if (op == MDB_PREV_DUP)
3691                                         return MDB_NOTFOUND;
3692                         }
3693                 }
3694         }
3695
3696         DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3697
3698         if (mc->mc_ki[mc->mc_top] == 0)  {
3699                 DPUTS("=====> move to prev sibling page");
3700                 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3701                         mc->mc_flags &= ~C_INITIALIZED;
3702                         return MDB_NOTFOUND;
3703                 }
3704                 mp = mc->mc_pg[mc->mc_top];
3705                 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3706                 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3707         } else
3708                 mc->mc_ki[mc->mc_top]--;
3709
3710         mc->mc_flags &= ~C_EOF;
3711
3712         DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3713             mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3714
3715         if (IS_LEAF2(mp)) {
3716                 key->mv_size = mc->mc_db->md_pad;
3717                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3718                 return MDB_SUCCESS;
3719         }
3720
3721         assert(IS_LEAF(mp));
3722         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3723
3724         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3725                 mdb_xcursor_init1(mc, leaf);
3726         }
3727         if (data) {
3728                 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3729                         return rc;
3730
3731                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3732                         rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3733                         if (rc != MDB_SUCCESS)
3734                                 return rc;
3735                 }
3736         }
3737
3738         MDB_SET_KEY(leaf, key);
3739         return MDB_SUCCESS;
3740 }
3741
3742 /** Set the cursor on a specific data item. */
3743 static int
3744 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3745     MDB_cursor_op op, int *exactp)
3746 {
3747         int              rc;
3748         MDB_page        *mp;
3749         MDB_node        *leaf;
3750         DKBUF;
3751
3752         assert(mc);
3753         assert(key);
3754         assert(key->mv_size > 0);
3755
3756         /* See if we're already on the right page */
3757         if (mc->mc_flags & C_INITIALIZED) {
3758                 MDB_val nodekey;
3759
3760                 mp = mc->mc_pg[mc->mc_top];
3761                 if (!NUMKEYS(mp)) {
3762                         mc->mc_ki[mc->mc_top] = 0;
3763                         return MDB_NOTFOUND;
3764                 }
3765                 if (mp->mp_flags & P_LEAF2) {
3766                         nodekey.mv_size = mc->mc_db->md_pad;
3767                         nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3768                 } else {
3769                         leaf = NODEPTR(mp, 0);
3770                         MDB_SET_KEY(leaf, &nodekey);
3771                 }
3772                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3773                 if (rc == 0) {
3774                         /* Probably happens rarely, but first node on the page
3775                          * was the one we wanted.
3776                          */
3777                         mc->mc_ki[mc->mc_top] = 0;
3778                         leaf = NODEPTR(mp, 0);
3779                         if (exactp)
3780                                 *exactp = 1;
3781                         goto set1;
3782                 }
3783                 if (rc > 0) {
3784                         unsigned int i;
3785                         unsigned int nkeys = NUMKEYS(mp);
3786                         if (nkeys > 1) {
3787                                 if (mp->mp_flags & P_LEAF2) {
3788                                         nodekey.mv_data = LEAF2KEY(mp,
3789                                                  nkeys-1, nodekey.mv_size);
3790                                 } else {
3791                                         leaf = NODEPTR(mp, nkeys-1);
3792                                         MDB_SET_KEY(leaf, &nodekey);
3793                                 }
3794                                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3795                                 if (rc == 0) {
3796                                         /* last node was the one we wanted */
3797                                         mc->mc_ki[mc->mc_top] = nkeys-1;
3798                                         leaf = NODEPTR(mp, nkeys-1);
3799                                         if (exactp)
3800                                                 *exactp = 1;
3801                                         goto set1;
3802                                 }
3803                                 if (rc < 0) {
3804                                         /* This is definitely the right page, skip search_page */
3805                                         rc = 0;
3806                                         goto set2;
3807                                 }
3808                         }
3809                         /* If any parents have right-sibs, search.
3810                          * Otherwise, there's nothing further.
3811                          */
3812                         for (i=0; i<mc->mc_top; i++)
3813                                 if (mc->mc_ki[i] <
3814                                         NUMKEYS(mc->mc_pg[i])-1)
3815                                         break;
3816                         if (i == mc->mc_top) {
3817                                 /* There are no other pages */
3818                                 mc->mc_ki[mc->mc_top] = nkeys;
3819                                 return MDB_NOTFOUND;
3820                         }
3821                 }
3822                 if (!mc->mc_top) {
3823                         /* There are no other pages */
3824                         mc->mc_ki[mc->mc_top] = 0;
3825                         return MDB_NOTFOUND;
3826                 }
3827         }
3828
3829         rc = mdb_page_search(mc, key, 0);
3830         if (rc != MDB_SUCCESS)
3831                 return rc;
3832
3833         mp = mc->mc_pg[mc->mc_top];
3834         assert(IS_LEAF(mp));
3835
3836 set2:
3837         leaf = mdb_node_search(mc, key, exactp);
3838         if (exactp != NULL && !*exactp) {
3839                 /* MDB_SET specified and not an exact match. */
3840                 return MDB_NOTFOUND;
3841         }
3842
3843         if (leaf == NULL) {
3844                 DPUTS("===> inexact leaf not found, goto sibling");
3845                 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3846                         return rc;              /* no entries matched */
3847                 mp = mc->mc_pg[mc->mc_top];
3848                 assert(IS_LEAF(mp));
3849                 leaf = NODEPTR(mp, 0);
3850         }
3851
3852 set1:
3853         mc->mc_flags |= C_INITIALIZED;
3854         mc->mc_flags &= ~C_EOF;
3855
3856         if (IS_LEAF2(mp)) {
3857                 key->mv_size = mc->mc_db->md_pad;
3858                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3859                 return MDB_SUCCESS;
3860         }
3861
3862         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3863                 mdb_xcursor_init1(mc, leaf);
3864         }
3865         if (data) {
3866                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3867                         if (op == MDB_SET || op == MDB_SET_RANGE) {
3868                                 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3869                         } else {
3870                                 int ex2, *ex2p;
3871                                 if (op == MDB_GET_BOTH) {
3872                                         ex2p = &ex2;
3873                                         ex2 = 0;
3874                                 } else {
3875                                         ex2p = NULL;
3876                                 }
3877                                 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3878                                 if (rc != MDB_SUCCESS)
3879                                         return rc;
3880                         }
3881                 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3882                         MDB_val d2;
3883                         if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3884                                 return rc;
3885                         rc = mc->mc_dbx->md_dcmp(data, &d2);
3886                         if (rc) {
3887                                 if (op == MDB_GET_BOTH || rc > 0)
3888                                         return MDB_NOTFOUND;
3889                         }
3890
3891                 } else {
3892                         if (mc->mc_xcursor)
3893                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3894                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3895                                 return rc;
3896                 }
3897         }
3898
3899         /* The key already matches in all other cases */
3900         if (op == MDB_SET_RANGE)
3901                 MDB_SET_KEY(leaf, key);
3902         DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3903
3904         return rc;
3905 }
3906
3907 /** Move the cursor to the first item in the database. */
3908 static int
3909 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3910 {
3911         int              rc;
3912         MDB_node        *leaf;
3913
3914         if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3915                 rc = mdb_page_search(mc, NULL, 0);
3916                 if (rc != MDB_SUCCESS)
3917                         return rc;
3918         }
3919         assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3920
3921         leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3922         mc->mc_flags |= C_INITIALIZED;
3923         mc->mc_flags &= ~C_EOF;
3924
3925         mc->mc_ki[mc->mc_top] = 0;
3926
3927         if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3928                 key->mv_size = mc->mc_db->md_pad;
3929                 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3930                 return MDB_SUCCESS;
3931         }
3932
3933         if (data) {
3934                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3935                         mdb_xcursor_init1(mc, leaf);
3936                         rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3937                         if (rc)
3938                                 return rc;
3939                 } else {
3940                         if (mc->mc_xcursor)
3941                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3942                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3943                                 return rc;
3944                 }
3945         }
3946         MDB_SET_KEY(leaf, key);
3947         return MDB_SUCCESS;
3948 }
3949
3950 /** Move the cursor to the last item in the database. */
3951 static int
3952 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3953 {
3954         int              rc;
3955         MDB_node        *leaf;
3956         MDB_val lkey;
3957
3958         lkey.mv_size = MAXKEYSIZE+1;
3959         lkey.mv_data = NULL;
3960
3961         if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3962                 rc = mdb_page_search(mc, &lkey, 0);
3963                 if (rc != MDB_SUCCESS)
3964                         return rc;
3965         }
3966         assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3967
3968         leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3969         mc->mc_flags |= C_INITIALIZED;
3970         mc->mc_flags &= ~C_EOF;
3971
3972         mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3973
3974         if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3975                 key->mv_size = mc->mc_db->md_pad;
3976                 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3977                 return MDB_SUCCESS;
3978         }
3979
3980         if (data) {
3981                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3982                         mdb_xcursor_init1(mc, leaf);
3983                         rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3984                         if (rc)
3985                                 return rc;
3986                 } else {
3987                         if (mc->mc_xcursor)
3988                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3989                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3990                                 return rc;
3991                 }
3992         }
3993
3994         MDB_SET_KEY(leaf, key);
3995         return MDB_SUCCESS;
3996 }
3997
3998 int
3999 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4000     MDB_cursor_op op)
4001 {
4002         int              rc;
4003         int              exact = 0;
4004
4005         assert(mc);
4006
4007         switch (op) {
4008         case MDB_GET_BOTH:
4009         case MDB_GET_BOTH_RANGE:
4010                 if (data == NULL || mc->mc_xcursor == NULL) {
4011                         rc = EINVAL;
4012                         break;
4013                 }
4014                 /* FALLTHRU */
4015         case MDB_SET:
4016         case MDB_SET_RANGE:
4017                 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4018                         rc = EINVAL;
4019                 } else if (op == MDB_SET_RANGE)
4020                         rc = mdb_cursor_set(mc, key, data, op, NULL);
4021                 else
4022                         rc = mdb_cursor_set(mc, key, data, op, &exact);
4023                 break;
4024         case MDB_GET_MULTIPLE:
4025                 if (data == NULL ||
4026                         !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
4027                         !(mc->mc_flags & C_INITIALIZED)) {
4028                         rc = EINVAL;
4029                         break;
4030                 }
4031                 rc = MDB_SUCCESS;
4032                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
4033                         (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
4034                         break;
4035                 goto fetchm;
4036         case MDB_NEXT_MULTIPLE:
4037                 if (data == NULL ||
4038                         !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
4039                         rc = EINVAL;
4040                         break;
4041                 }
4042                 if (!(mc->mc_flags & C_INITIALIZED))
4043                         rc = mdb_cursor_first(mc, key, data);
4044                 else
4045                         rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
4046                 if (rc == MDB_SUCCESS) {
4047                         if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
4048                                 MDB_cursor *mx;
4049 fetchm:
4050                                 mx = &mc->mc_xcursor->mx_cursor;
4051                                 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
4052                                         mx->mc_db->md_pad;
4053                                 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
4054                                 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
4055                         } else {
4056                                 rc = MDB_NOTFOUND;
4057                         }
4058                 }
4059                 break;
4060         case MDB_NEXT:
4061         case MDB_NEXT_DUP:
4062         case MDB_NEXT_NODUP:
4063                 if (!(mc->mc_flags & C_INITIALIZED))
4064                         rc = mdb_cursor_first(mc, key, data);
4065                 else
4066                         rc = mdb_cursor_next(mc, key, data, op);
4067                 break;
4068         case MDB_PREV:
4069         case MDB_PREV_DUP:
4070         case MDB_PREV_NODUP:
4071                 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
4072                         rc = mdb_cursor_last(mc, key, data);
4073                 else
4074                         rc = mdb_cursor_prev(mc, key, data, op);
4075                 break;
4076         case MDB_FIRST:
4077                 rc = mdb_cursor_first(mc, key, data);
4078                 break;
4079         case MDB_FIRST_DUP:
4080                 if (data == NULL ||
4081                         !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4082                         !(mc->mc_flags & C_INITIALIZED) ||
4083                         !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4084                         rc = EINVAL;
4085                         break;
4086                 }
4087                 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4088                 break;
4089         case MDB_LAST:
4090                 rc = mdb_cursor_last(mc, key, data);
4091                 break;
4092         case MDB_LAST_DUP:
4093                 if (data == NULL ||
4094                         !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4095                         !(mc->mc_flags & C_INITIALIZED) ||
4096                         !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4097                         rc = EINVAL;
4098                         break;
4099                 }
4100                 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4101                 break;
4102         default:
4103                 DPRINTF("unhandled/unimplemented cursor operation %u", op);
4104                 rc = EINVAL;
4105                 break;
4106         }
4107
4108         return rc;
4109 }
4110
4111 /** Touch all the pages in the cursor stack.
4112  *      Makes sure all the pages are writable, before attempting a write operation.
4113  * @param[in] mc The cursor to operate on.
4114  */
4115 static int
4116 mdb_cursor_touch(MDB_cursor *mc)
4117 {
4118         int rc;
4119
4120         if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
4121                 MDB_cursor mc2;
4122                 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4123                 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
4124                 if (rc)
4125                          return rc;
4126                 *mc->mc_dbflag = DB_DIRTY;
4127         }
4128         for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
4129                 rc = mdb_page_touch(mc);
4130                 if (rc)
4131                         return rc;
4132         }
4133         mc->mc_top = mc->mc_snum-1;
4134         return MDB_SUCCESS;
4135 }
4136
4137 int
4138 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4139     unsigned int flags)
4140 {
4141         MDB_node        *leaf = NULL;
4142         MDB_val xdata, *rdata, dkey;
4143         MDB_page        *fp;
4144         MDB_db dummy;
4145         int do_sub = 0;
4146         unsigned int mcount = 0;
4147         size_t nsize;
4148         int rc, rc2;
4149         MDB_pagebuf pbuf;
4150         char dbuf[MAXKEYSIZE+1];
4151         unsigned int nflags;
4152         DKBUF;
4153
4154         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4155                 return EACCES;
4156
4157         DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
4158                 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
4159
4160         dkey.mv_size = 0;
4161
4162         if (flags == MDB_CURRENT) {
4163                 if (!(mc->mc_flags & C_INITIALIZED))
4164                         return EINVAL;
4165                 rc = MDB_SUCCESS;
4166         } else if (mc->mc_db->md_root == P_INVALID) {
4167                 MDB_page *np;
4168                 /* new database, write a root leaf page */
4169                 DPUTS("allocating new root leaf page");
4170                 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
4171                         return ENOMEM;
4172                 }
4173                 mc->mc_snum = 0;
4174                 mdb_cursor_push(mc, np);
4175                 mc->mc_db->md_root = np->mp_pgno;
4176                 mc->mc_db->md_depth++;
4177                 *mc->mc_dbflag = DB_DIRTY;
4178                 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
4179                         == MDB_DUPFIXED)
4180                         np->mp_flags |= P_LEAF2;
4181                 mc->mc_flags |= C_INITIALIZED;
4182                 rc = MDB_NOTFOUND;
4183                 goto top;
4184         } else {
4185                 int exact = 0;
4186                 MDB_val d2;
4187                 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
4188                 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
4189                         DPRINTF("duplicate key [%s]", DKEY(key));
4190                         *data = d2;
4191                         return MDB_KEYEXIST;
4192                 }
4193                 if (rc && rc != MDB_NOTFOUND)
4194                         return rc;
4195         }
4196
4197         /* Cursor is positioned, now make sure all pages are writable */
4198         rc2 = mdb_cursor_touch(mc);
4199         if (rc2)
4200                 return rc2;
4201
4202 top:
4203         /* The key already exists */
4204         if (rc == MDB_SUCCESS) {
4205                 /* there's only a key anyway, so this is a no-op */
4206                 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4207                         unsigned int ksize = mc->mc_db->md_pad;
4208                         if (key->mv_size != ksize)
4209                                 return EINVAL;
4210                         if (flags == MDB_CURRENT) {
4211                                 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
4212                                 memcpy(ptr, key->mv_data, ksize);
4213                         }
4214                         return MDB_SUCCESS;
4215                 }
4216
4217                 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4218
4219                 /* DB has dups? */
4220                 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
4221                         /* Was a single item before, must convert now */
4222 more:
4223                         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4224                                 /* Just overwrite the current item */
4225                                 if (flags == MDB_CURRENT)
4226                                         goto current;
4227
4228                                 dkey.mv_size = NODEDSZ(leaf);
4229                                 dkey.mv_data = NODEDATA(leaf);
4230 #if UINT_MAX < SIZE_MAX
4231                                 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
4232 #ifdef MISALIGNED_OK
4233                                         mc->mc_dbx->md_dcmp = mdb_cmp_long;
4234 #else
4235                                         mc->mc_dbx->md_dcmp = mdb_cmp_cint;
4236 #endif
4237 #endif
4238                                 /* if data matches, ignore it */
4239                                 if (!mc->mc_dbx->md_dcmp(data, &dkey))
4240                                         return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
4241
4242                                 /* create a fake page for the dup items */
4243                                 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
4244                                 dkey.mv_data = dbuf;
4245                                 fp = (MDB_page *)&pbuf;
4246                                 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4247                                 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
4248                                 fp->mp_lower = PAGEHDRSZ;
4249                                 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
4250                                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4251                                         fp->mp_flags |= P_LEAF2;
4252                                         fp->mp_pad = data->mv_size;
4253                                 } else {
4254                                         fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
4255                                                 (dkey.mv_size & 1) + (data->mv_size & 1);
4256                                 }
4257                                 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4258                                 do_sub = 1;
4259                                 rdata = &xdata;
4260                                 xdata.mv_size = fp->mp_upper;
4261                                 xdata.mv_data = fp;
4262                                 flags |= F_DUPDATA;
4263                                 goto new_sub;
4264                         }
4265                         if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4266                                 /* See if we need to convert from fake page to subDB */
4267                                 MDB_page *mp;
4268                                 unsigned int offset;
4269                                 unsigned int i;
4270
4271                                 fp = NODEDATA(leaf);
4272                                 if (flags == MDB_CURRENT) {
4273                                         fp->mp_flags |= P_DIRTY;
4274                                         COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
4275                                         mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
4276                                         flags |= F_DUPDATA;
4277                                         goto put_sub;
4278                                 }
4279                                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4280                                         offset = fp->mp_pad;
4281                                 } else {
4282                                         offset = NODESIZE + sizeof(indx_t) + data->mv_size;
4283                                 }
4284                                 offset += offset & 1;
4285                                 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
4286                                         offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
4287                                                 MDB_MINKEYS) {
4288                                         /* yes, convert it */
4289                                         dummy.md_flags = 0;
4290                                         if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4291                                                 dummy.md_pad = fp->mp_pad;
4292                                                 dummy.md_flags = MDB_DUPFIXED;
4293                                                 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4294                                                         dummy.md_flags |= MDB_INTEGERKEY;
4295                                         }
4296                                         dummy.md_depth = 1;
4297                                         dummy.md_branch_pages = 0;
4298                                         dummy.md_leaf_pages = 1;
4299                                         dummy.md_overflow_pages = 0;
4300                                         dummy.md_entries = NUMKEYS(fp);
4301                                         rdata = &xdata;
4302                                         xdata.mv_size = sizeof(MDB_db);
4303                                         xdata.mv_data = &dummy;
4304                                         mp = mdb_page_alloc(mc, 1);
4305                                         if (!mp)
4306                                                 return ENOMEM;
4307                                         offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4308                                         flags |= F_DUPDATA|F_SUBDATA;
4309                                         dummy.md_root = mp->mp_pgno;
4310                                 } else {
4311                                         /* no, just grow it */
4312                                         rdata = &xdata;
4313                                         xdata.mv_size = NODEDSZ(leaf) + offset;
4314                                         xdata.mv_data = &pbuf;
4315                                         mp = (MDB_page *)&pbuf;
4316                                         mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4317                                         flags |= F_DUPDATA;
4318                                 }
4319                                 mp->mp_flags = fp->mp_flags | P_DIRTY;
4320                                 mp->mp_pad   = fp->mp_pad;
4321                                 mp->mp_lower = fp->mp_lower;
4322                                 mp->mp_upper = fp->mp_upper + offset;
4323                                 if (IS_LEAF2(fp)) {
4324                                         memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4325                                 } else {
4326                                         nsize = NODEDSZ(leaf) - fp->mp_upper;
4327                                         memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
4328                                         for (i=0; i<NUMKEYS(fp); i++)
4329                                                 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
4330                                 }
4331                                 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4332                                 do_sub = 1;
4333                                 goto new_sub;
4334                         }
4335                         /* data is on sub-DB, just store it */
4336                         flags |= F_DUPDATA|F_SUBDATA;
4337                         goto put_sub;
4338                 }
4339 current:
4340                 /* overflow page overwrites need special handling */
4341                 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4342                         MDB_page *omp;
4343                         pgno_t pg;
4344                         int ovpages, dpages;
4345
4346                         ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
4347                         dpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4348                         memcpy(&pg, NODEDATA(leaf), sizeof(pg));
4349                         mdb_page_get(mc->mc_txn, pg, &omp);
4350                         /* Is the ov page writable and large enough? */
4351                         if ((omp->mp_flags & P_DIRTY) && ovpages >= dpages) {
4352                                 /* yes, overwrite it. Note in this case we don't
4353                                  * bother to try shrinking the node if the new data
4354                                  * is smaller than the overflow threshold.
4355                                  */
4356                                 if (F_ISSET(flags, MDB_RESERVE))
4357                                         data->mv_data = METADATA(omp);
4358                                 else
4359                                         memcpy(METADATA(omp), data->mv_data, data->mv_size);
4360                                 goto done;
4361                         } else {
4362                                 /* no, free ovpages */
4363                                 int i;
4364                                 mc->mc_db->md_overflow_pages -= ovpages;
4365                                 for (i=0; i<ovpages; i++) {
4366                                         DPRINTF("freed ov page %zu", pg);
4367                                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
4368                                         pg++;
4369                                 }
4370                         }
4371                 } else if (NODEDSZ(leaf) == data->mv_size) {
4372                         /* same size, just replace it. Note that we could
4373                          * also reuse this node if the new data is smaller,
4374                          * but instead we opt to shrink the node in that case.
4375                          */
4376                         if (F_ISSET(flags, MDB_RESERVE))
4377                                 data->mv_data = NODEDATA(leaf);
4378                         else
4379                                 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4380                         goto done;
4381                 }
4382                 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4383                 mc->mc_db->md_entries--;
4384         } else {
4385                 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
4386         }
4387
4388         rdata = data;
4389
4390 new_sub:
4391         nflags = flags & NODE_ADD_FLAGS;
4392         nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
4393         if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
4394                 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
4395                         nflags &= ~MDB_APPEND;
4396                 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
4397         } else {
4398                 /* There is room already in this leaf page. */
4399                 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
4400                 if (rc == 0 && !do_sub) {
4401                         /* Adjust other cursors pointing to mp */
4402                         MDB_cursor *m2, *m3;
4403                         MDB_dbi dbi = mc->mc_dbi;
4404                         unsigned i = mc->mc_top;
4405                         MDB_page *mp = mc->mc_pg[i];
4406
4407                         if (mc->mc_flags & C_SUB)
4408                                 dbi--;
4409
4410                         for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4411                                 if (mc->mc_flags & C_SUB)
4412                                         m3 = &m2->mc_xcursor->mx_cursor;
4413                                 else
4414                                         m3 = m2;
4415                                 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
4416                                 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
4417                                         m3->mc_ki[i]++;
4418                                 }
4419                         }
4420                 }
4421         }
4422
4423         if (rc != MDB_SUCCESS)
4424                 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4425         else {
4426                 /* Now store the actual data in the child DB. Note that we're
4427                  * storing the user data in the keys field, so there are strict
4428                  * size limits on dupdata. The actual data fields of the child
4429                  * DB are all zero size.
4430                  */
4431                 if (do_sub) {
4432                         int xflags;
4433 put_sub:
4434                         xdata.mv_size = 0;
4435                         xdata.mv_data = "";
4436                         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4437                         if (flags & MDB_CURRENT) {
4438                                 xflags = MDB_CURRENT;
4439                         } else {
4440                                 mdb_xcursor_init1(mc, leaf);
4441                                 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
4442                         }
4443                         /* converted, write the original data first */
4444                         if (dkey.mv_size) {
4445                                 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
4446                                 if (rc)
4447                                         return rc;
4448                                 {
4449                                         /* Adjust other cursors pointing to mp */
4450                                         MDB_cursor *m2;
4451                                         unsigned i = mc->mc_top;
4452                                         MDB_page *mp = mc->mc_pg[i];
4453
4454                                         for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4455                                                 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
4456                                                 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
4457                                                         mdb_xcursor_init1(m2, leaf);
4458                                                 }
4459                                         }
4460                                 }
4461                         }
4462                         xflags |= (flags & MDB_APPEND);
4463                         rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
4464                         if (flags & F_SUBDATA) {
4465                                 void *db = NODEDATA(leaf);
4466                                 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4467                         }
4468                 }
4469                 /* sub-writes might have failed so check rc again.
4470                  * Don't increment count if we just replaced an existing item.
4471                  */
4472                 if (!rc && !(flags & MDB_CURRENT))
4473                         mc->mc_db->md_entries++;
4474                 if (flags & MDB_MULTIPLE) {
4475                         mcount++;
4476                         if (mcount < data[1].mv_size) {
4477                                 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
4478                                 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4479                                 goto more;
4480                         }
4481                 }
4482         }
4483 done:
4484         return rc;
4485 }
4486
4487 int
4488 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
4489 {
4490         MDB_node        *leaf;
4491         int rc;
4492
4493         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4494                 return EACCES;
4495
4496         if (!mc->mc_flags & C_INITIALIZED)
4497                 return EINVAL;
4498
4499         rc = mdb_cursor_touch(mc);
4500         if (rc)
4501                 return rc;
4502
4503         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4504
4505         if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4506                 if (flags != MDB_NODUPDATA) {
4507                         if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4508                                 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
4509                         }
4510                         rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
4511                         /* If sub-DB still has entries, we're done */
4512                         if (mc->mc_xcursor->mx_db.md_entries) {
4513                                 if (leaf->mn_flags & F_SUBDATA) {
4514                                         /* update subDB info */
4515                                         void *db = NODEDATA(leaf);
4516                                         memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4517                                 } else {
4518                                         /* shrink fake page */
4519                                         mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4520                                 }
4521                                 mc->mc_db->md_entries--;
4522                                 return rc;
4523                         }
4524                         /* otherwise fall thru and delete the sub-DB */
4525                 }
4526
4527                 if (leaf->mn_flags & F_SUBDATA) {
4528                         /* add all the child DB's pages to the free list */
4529                         rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
4530                         if (rc == MDB_SUCCESS) {
4531                                 mc->mc_db->md_entries -=
4532                                         mc->mc_xcursor->mx_db.md_entries;
4533                         }
4534                 }
4535         }
4536
4537         return mdb_cursor_del0(mc, leaf);
4538 }
4539
4540 /** Allocate and initialize new pages for a database.
4541  * @param[in] mc a cursor on the database being added to.
4542  * @param[in] flags flags defining what type of page is being allocated.
4543  * @param[in] num the number of pages to allocate. This is usually 1,
4544  * unless allocating overflow pages for a large record.
4545  * @return Address of a page, or NULL on failure.
4546  */
4547 static MDB_page *
4548 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
4549 {
4550         MDB_page        *np;
4551
4552         if ((np = mdb_page_alloc(mc, num)) == NULL)
4553                 return NULL;
4554         DPRINTF("allocated new mpage %zu, page size %u",
4555             np->mp_pgno, mc->mc_txn->mt_env->me_psize);
4556         np->mp_flags = flags | P_DIRTY;
4557         np->mp_lower = PAGEHDRSZ;
4558         np->mp_upper = mc->mc_txn->mt_env->me_psize;
4559
4560         if (IS_BRANCH(np))
4561                 mc->mc_db->md_branch_pages++;
4562         else if (IS_LEAF(np))
4563                 mc->mc_db->md_leaf_pages++;
4564         else if (IS_OVERFLOW(np)) {
4565                 mc->mc_db->md_overflow_pages += num;
4566                 np->mp_pages = num;
4567         }
4568
4569         return np;
4570 }
4571
4572 /** Calculate the size of a leaf node.
4573  * The size depends on the environment's page size; if a data item
4574  * is too large it will be put onto an overflow page and the node
4575  * size will only include the key and not the data. Sizes are always
4576  * rounded up to an even number of bytes, to guarantee 2-byte alignment
4577  * of the #MDB_node headers.
4578  * @param[in] env The environment handle.
4579  * @param[in] key The key for the node.
4580  * @param[in] data The data for the node.
4581  * @return The number of bytes needed to store the node.
4582  */
4583 static size_t
4584 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
4585 {
4586         size_t           sz;
4587
4588         sz = LEAFSIZE(key, data);
4589         if (sz >= env->me_psize / MDB_MINKEYS) {
4590                 /* put on overflow page */
4591                 sz -= data->mv_size - sizeof(pgno_t);
4592         }
4593         sz += sz & 1;
4594
4595         return sz + sizeof(indx_t);
4596 }
4597
4598 /** Calculate the size of a branch node.
4599  * The size should depend on the environment's page size but since
4600  * we currently don't support spilling large keys onto overflow
4601  * pages, it's simply the size of the #MDB_node header plus the
4602  * size of the key. Sizes are always rounded up to an even number
4603  * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
4604  * @param[in] env The environment handle.
4605  * @param[in] key The key for the node.
4606  * @return The number of bytes needed to store the node.
4607  */
4608 static size_t
4609 mdb_branch_size(MDB_env *env, MDB_val *key)
4610 {
4611         size_t           sz;
4612
4613         sz = INDXSIZE(key);
4614         if (sz >= env->me_psize / MDB_MINKEYS) {
4615                 /* put on overflow page */
4616                 /* not implemented */
4617                 /* sz -= key->size - sizeof(pgno_t); */
4618         }
4619
4620         return sz + sizeof(indx_t);
4621 }
4622
4623 /** Add a node to the page pointed to by the cursor.
4624  * @param[in] mc The cursor for this operation.
4625  * @param[in] indx The index on the page where the new node should be added.
4626  * @param[in] key The key for the new node.
4627  * @param[in] data The data for the new node, if any.
4628  * @param[in] pgno The page number, if adding a branch node.
4629  * @param[in] flags Flags for the node.
4630  * @return 0 on success, non-zero on failure. Possible errors are:
4631  * <ul>
4632  *      <li>ENOMEM - failed to allocate overflow pages for the node.
4633  *      <li>ENOSPC - there is insufficient room in the page. This error
4634  *      should never happen since all callers already calculate the
4635  *      page's free space before calling this function.
4636  * </ul>
4637  */
4638 static int
4639 mdb_node_add(MDB_cursor *mc, indx_t indx,
4640     MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
4641 {
4642         unsigned int     i;
4643         size_t           node_size = NODESIZE;
4644         indx_t           ofs;
4645         MDB_node        *node;
4646         MDB_page        *mp = mc->mc_pg[mc->mc_top];
4647         MDB_page        *ofp = NULL;            /* overflow page */
4648         DKBUF;
4649
4650         assert(mp->mp_upper >= mp->mp_lower);
4651
4652         DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
4653             IS_LEAF(mp) ? "leaf" : "branch",
4654                 IS_SUBP(mp) ? "sub-" : "",
4655             mp->mp_pgno, indx, data ? data->mv_size : 0,
4656                 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
4657
4658         if (IS_LEAF2(mp)) {
4659                 /* Move higher keys up one slot. */
4660                 int ksize = mc->mc_db->md_pad, dif;
4661                 char *ptr = LEAF2KEY(mp, indx, ksize);
4662                 dif = NUMKEYS(mp) - indx;
4663                 if (dif > 0)
4664                         memmove(ptr+ksize, ptr, dif*ksize);
4665                 /* insert new key */
4666                 memcpy(ptr, key->mv_data, ksize);
4667
4668                 /* Just using these for counting */
4669                 mp->mp_lower += sizeof(indx_t);
4670                 mp->mp_upper -= ksize - sizeof(indx_t);
4671                 return MDB_SUCCESS;
4672         }
4673
4674         if (key != NULL)
4675                 node_size += key->mv_size;
4676
4677         if (IS_LEAF(mp)) {
4678                 assert(data);
4679                 if (F_ISSET(flags, F_BIGDATA)) {
4680                         /* Data already on overflow page. */
4681                         node_size += sizeof(pgno_t);
4682                 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4683                         int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4684                         /* Put data on overflow page. */
4685                         DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
4686                             data->mv_size, node_size+data->mv_size);
4687                         node_size += sizeof(pgno_t);
4688                         if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
4689                                 return ENOMEM;
4690                         DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4691                         flags |= F_BIGDATA;
4692                 } else {
4693                         node_size += data->mv_size;
4694                 }
4695         }
4696         node_size += node_size & 1;
4697
4698         if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4699                 DPRINTF("not enough room in page %zu, got %u ptrs",
4700                     mp->mp_pgno, NUMKEYS(mp));
4701                 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4702                     mp->mp_upper - mp->mp_lower);
4703                 DPRINTF("node size = %zu", node_size);
4704                 return ENOSPC;
4705         }
4706
4707         /* Move higher pointers up one slot. */
4708         for (i = NUMKEYS(mp); i > indx; i--)
4709                 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4710
4711         /* Adjust free space offsets. */
4712         ofs = mp->mp_upper - node_size;
4713         assert(ofs >= mp->mp_lower + sizeof(indx_t));
4714         mp->mp_ptrs[indx] = ofs;
4715         mp->mp_upper = ofs;
4716         mp->mp_lower += sizeof(indx_t);
4717
4718         /* Write the node data. */
4719         node = NODEPTR(mp, indx);
4720         node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4721         node->mn_flags = flags;
4722         if (IS_LEAF(mp))
4723                 SETDSZ(node,data->mv_size);
4724         else
4725                 SETPGNO(node,pgno);
4726
4727         if (key)
4728                 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4729
4730         if (IS_LEAF(mp)) {
4731                 assert(key);
4732                 if (ofp == NULL) {
4733                         if (F_ISSET(flags, F_BIGDATA))
4734                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
4735                                     sizeof(pgno_t));
4736                         else if (F_ISSET(flags, MDB_RESERVE))
4737                                 data->mv_data = node->mn_data + key->mv_size;
4738                         else
4739                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
4740                                     data->mv_size);
4741                 } else {
4742                         memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4743                             sizeof(pgno_t));
4744                         if (F_ISSET(flags, MDB_RESERVE))
4745                                 data->mv_data = METADATA(ofp);
4746                         else
4747                                 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4748                 }
4749         }
4750
4751         return MDB_SUCCESS;
4752 }
4753
4754 /** Delete the specified node from a page.
4755  * @param[in] mp The page to operate on.
4756  * @param[in] indx The index of the node to delete.
4757  * @param[in] ksize The size of a node. Only used if the page is
4758  * part of a #MDB_DUPFIXED database.
4759  */
4760 static void
4761 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4762 {
4763         unsigned int     sz;
4764         indx_t           i, j, numkeys, ptr;
4765         MDB_node        *node;
4766         char            *base;
4767
4768 #if MDB_DEBUG
4769         {
4770         pgno_t pgno;
4771         COPY_PGNO(pgno, mp->mp_pgno);
4772         DPRINTF("delete node %u on %s page %zu", indx,
4773             IS_LEAF(mp) ? "leaf" : "branch", pgno);
4774         }
4775 #endif
4776         assert(indx < NUMKEYS(mp));
4777
4778         if (IS_LEAF2(mp)) {
4779                 int x = NUMKEYS(mp) - 1 - indx;
4780                 base = LEAF2KEY(mp, indx, ksize);
4781                 if (x)
4782                         memmove(base, base + ksize, x * ksize);
4783                 mp->mp_lower -= sizeof(indx_t);
4784                 mp->mp_upper += ksize - sizeof(indx_t);
4785                 return;
4786         }
4787
4788         node = NODEPTR(mp, indx);
4789         sz = NODESIZE + node->mn_ksize;
4790         if (IS_LEAF(mp)) {
4791                 if (F_ISSET(node->mn_flags, F_BIGDATA))
4792                         sz += sizeof(pgno_t);
4793                 else
4794                         sz += NODEDSZ(node);
4795         }
4796         sz += sz & 1;
4797
4798         ptr = mp->mp_ptrs[indx];
4799         numkeys = NUMKEYS(mp);
4800         for (i = j = 0; i < numkeys; i++) {
4801                 if (i != indx) {
4802                         mp->mp_ptrs[j] = mp->mp_ptrs[i];
4803                         if (mp->mp_ptrs[i] < ptr)
4804                                 mp->mp_ptrs[j] += sz;
4805                         j++;
4806                 }
4807         }
4808
4809         base = (char *)mp + mp->mp_upper;
4810         memmove(base + sz, base, ptr - mp->mp_upper);
4811
4812         mp->mp_lower -= sizeof(indx_t);
4813         mp->mp_upper += sz;
4814 }
4815
4816 /** Compact the main page after deleting a node on a subpage.
4817  * @param[in] mp The main page to operate on.
4818  * @param[in] indx The index of the subpage on the main page.
4819  */
4820 static void
4821 mdb_node_shrink(MDB_page *mp, indx_t indx)
4822 {
4823         MDB_node *node;
4824         MDB_page *sp, *xp;
4825         char *base;
4826         int osize, nsize;
4827         int delta;
4828         indx_t           i, numkeys, ptr;
4829
4830         node = NODEPTR(mp, indx);
4831         sp = (MDB_page *)NODEDATA(node);
4832         osize = NODEDSZ(node);
4833
4834         delta = sp->mp_upper - sp->mp_lower;
4835         SETDSZ(node, osize - delta);
4836         xp = (MDB_page *)((char *)sp + delta);
4837
4838         /* shift subpage upward */
4839         if (IS_LEAF2(sp)) {
4840                 nsize = NUMKEYS(sp) * sp->mp_pad;
4841                 memmove(METADATA(xp), METADATA(sp), nsize);
4842         } else {
4843                 int i;
4844                 nsize = osize - sp->mp_upper;
4845                 numkeys = NUMKEYS(sp);
4846                 for (i=numkeys-1; i>=0; i--)
4847                         xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4848         }
4849         xp->mp_upper = sp->mp_lower;
4850         xp->mp_lower = sp->mp_lower;
4851         xp->mp_flags = sp->mp_flags;
4852         xp->mp_pad = sp->mp_pad;
4853         COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
4854
4855         /* shift lower nodes upward */
4856         ptr = mp->mp_ptrs[indx];
4857         numkeys = NUMKEYS(mp);
4858         for (i = 0; i < numkeys; i++) {
4859                 if (mp->mp_ptrs[i] <= ptr)
4860                         mp->mp_ptrs[i] += delta;
4861         }
4862
4863         base = (char *)mp + mp->mp_upper;
4864         memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4865         mp->mp_upper += delta;
4866 }
4867
4868 /** Initial setup of a sorted-dups cursor.
4869  * Sorted duplicates are implemented as a sub-database for the given key.
4870  * The duplicate data items are actually keys of the sub-database.
4871  * Operations on the duplicate data items are performed using a sub-cursor
4872  * initialized when the sub-database is first accessed. This function does
4873  * the preliminary setup of the sub-cursor, filling in the fields that
4874  * depend only on the parent DB.
4875  * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4876  */
4877 static void
4878 mdb_xcursor_init0(MDB_cursor *mc)
4879 {
4880         MDB_xcursor *mx = mc->mc_xcursor;
4881
4882         mx->mx_cursor.mc_xcursor = NULL;
4883         mx->mx_cursor.mc_txn = mc->mc_txn;
4884         mx->mx_cursor.mc_db = &mx->mx_db;
4885         mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4886         mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4887         mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
4888         mx->mx_cursor.mc_snum = 0;
4889         mx->mx_cursor.mc_top = 0;
4890         mx->mx_cursor.mc_flags = C_SUB;
4891         mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4892         mx->mx_dbx.md_dcmp = NULL;
4893         mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4894 }
4895
4896 /** Final setup of a sorted-dups cursor.
4897  *      Sets up the fields that depend on the data from the main cursor.
4898  * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4899  * @param[in] node The data containing the #MDB_db record for the
4900  * sorted-dup database.
4901  */
4902 static void
4903 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4904 {
4905         MDB_xcursor *mx = mc->mc_xcursor;
4906
4907         if (node->mn_flags & F_SUBDATA) {
4908                 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
4909                 mx->mx_cursor.mc_snum = 0;
4910                 mx->mx_cursor.mc_flags = C_SUB;
4911         } else {
4912                 MDB_page *fp = NODEDATA(node);
4913                 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
4914                 mx->mx_db.md_flags = 0;
4915                 mx->mx_db.md_depth = 1;
4916                 mx->mx_db.md_branch_pages = 0;
4917                 mx->mx_db.md_leaf_pages = 1;
4918                 mx->mx_db.md_overflow_pages = 0;
4919                 mx->mx_db.md_entries = NUMKEYS(fp);
4920                 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
4921                 mx->mx_cursor.mc_snum = 1;
4922                 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
4923                 mx->mx_cursor.mc_top = 0;
4924                 mx->mx_cursor.mc_pg[0] = fp;
4925                 mx->mx_cursor.mc_ki[0] = 0;
4926                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4927                         mx->mx_db.md_flags = MDB_DUPFIXED;
4928                         mx->mx_db.md_pad = fp->mp_pad;
4929                         if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4930                                 mx->mx_db.md_flags |= MDB_INTEGERKEY;
4931                 }
4932         }
4933         DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
4934                 mx->mx_db.md_root);
4935         mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
4936                 DB_DIRTY : 0;
4937         mx->mx_dbx.md_name.mv_data = NODEKEY(node);
4938         mx->mx_dbx.md_name.mv_size = node->mn_ksize;
4939 #if UINT_MAX < SIZE_MAX
4940         if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
4941 #ifdef MISALIGNED_OK
4942                 mx->mx_dbx.md_cmp = mdb_cmp_long;
4943 #else
4944                 mx->mx_dbx.md_cmp = mdb_cmp_cint;
4945 #endif
4946 #endif
4947 }
4948
4949 /** Initialize a cursor for a given transaction and database. */
4950 static void
4951 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
4952 {
4953         mc->mc_orig = NULL;
4954         mc->mc_dbi = dbi;
4955         mc->mc_txn = txn;
4956         mc->mc_db = &txn->mt_dbs[dbi];
4957         mc->mc_dbx = &txn->mt_dbxs[dbi];
4958         mc->mc_dbflag = &txn->mt_dbflags[dbi];
4959         mc->mc_snum = 0;
4960         mc->mc_top = 0;
4961         mc->mc_flags = 0;
4962         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4963                 assert(mx != NULL);
4964                 mc->mc_xcursor = mx;
4965                 mdb_xcursor_init0(mc);
4966         } else {
4967                 mc->mc_xcursor = NULL;
4968         }
4969 }
4970
4971 int
4972 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
4973 {
4974         MDB_cursor      *mc;
4975         MDB_xcursor     *mx = NULL;
4976         size_t size = sizeof(MDB_cursor);
4977
4978         if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs)
4979                 return EINVAL;
4980
4981         /* Allow read access to the freelist */
4982         if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
4983                 return EINVAL;
4984
4985         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
4986                 size += sizeof(MDB_xcursor);
4987
4988         if ((mc = malloc(size)) != NULL) {
4989                 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4990                         mx = (MDB_xcursor *)(mc + 1);
4991                 }
4992                 mdb_cursor_init(mc, txn, dbi, mx);
4993                 if (txn->mt_cursors) {
4994                         mc->mc_next = txn->mt_cursors[dbi];
4995                         txn->mt_cursors[dbi] = mc;
4996                 }
4997                 mc->mc_flags |= C_ALLOCD;
4998         } else {
4999                 return ENOMEM;
5000         }
5001
5002         *ret = mc;
5003
5004         return MDB_SUCCESS;
5005 }
5006
5007 /* Return the count of duplicate data items for the current key */
5008 int
5009 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
5010 {
5011         MDB_node        *leaf;
5012
5013         if (mc == NULL || countp == NULL)
5014                 return EINVAL;
5015
5016         if (!(mc->mc_db->md_flags & MDB_DUPSORT))
5017                 return EINVAL;
5018
5019         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5020         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5021                 *countp = 1;
5022         } else {
5023                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
5024                         return EINVAL;
5025
5026                 *countp = mc->mc_xcursor->mx_db.md_entries;
5027         }
5028         return MDB_SUCCESS;
5029 }
5030
5031 void
5032 mdb_cursor_close(MDB_cursor *mc)
5033 {
5034         if (mc != NULL) {
5035                 /* remove from txn, if tracked */
5036                 if (mc->mc_txn->mt_cursors) {
5037                         MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
5038                         while (*prev && *prev != mc) prev = &(*prev)->mc_next;
5039                         if (*prev == mc)
5040                                 *prev = mc->mc_next;
5041                 }
5042                 if (mc->mc_flags & C_ALLOCD)
5043                         free(mc);
5044         }
5045 }
5046
5047 MDB_txn *
5048 mdb_cursor_txn(MDB_cursor *mc)
5049 {
5050         if (!mc) return NULL;
5051         return mc->mc_txn;
5052 }
5053
5054 MDB_dbi
5055 mdb_cursor_dbi(MDB_cursor *mc)
5056 {
5057         if (!mc) return 0;
5058         return mc->mc_dbi;
5059 }
5060
5061 /** Replace the key for a node with a new key.
5062  * @param[in] mp The page containing the node to operate on.
5063  * @param[in] indx The index of the node to operate on.
5064  * @param[in] key The new key to use.
5065  * @return 0 on success, non-zero on failure.
5066  */
5067 static int
5068 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
5069 {
5070         MDB_node                *node;
5071         char                    *base;
5072         size_t                   len;
5073         int                      delta, delta0;
5074         indx_t                   ptr, i, numkeys;
5075         DKBUF;
5076
5077         node = NODEPTR(mp, indx);
5078         ptr = mp->mp_ptrs[indx];
5079 #if MDB_DEBUG
5080         {
5081                 MDB_val k2;
5082                 char kbuf2[(MAXKEYSIZE*2+1)];
5083                 k2.mv_data = NODEKEY(node);
5084                 k2.mv_size = node->mn_ksize;
5085                 DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %zu",
5086                         indx, ptr,
5087                         mdb_dkey(&k2, kbuf2),
5088                         DKEY(key),
5089                         mp->mp_pgno);
5090         }
5091 #endif
5092
5093         delta0 = delta = key->mv_size - node->mn_ksize;
5094
5095         /* Must be 2-byte aligned. If new key is
5096          * shorter by 1, the shift will be skipped.
5097          */
5098         delta += (delta & 1);
5099         if (delta) {
5100                 if (delta > 0 && SIZELEFT(mp) < delta) {
5101                         DPRINTF("OUCH! Not enough room, delta = %d", delta);
5102                         return ENOSPC;
5103                 }
5104
5105                 numkeys = NUMKEYS(mp);
5106                 for (i = 0; i < numkeys; i++) {
5107                         if (mp->mp_ptrs[i] <= ptr)
5108                                 mp->mp_ptrs[i] -= delta;
5109                 }
5110
5111                 base = (char *)mp + mp->mp_upper;
5112                 len = ptr - mp->mp_upper + NODESIZE;
5113                 memmove(base - delta, base, len);
5114                 mp->mp_upper -= delta;
5115
5116                 node = NODEPTR(mp, indx);
5117         }
5118
5119         /* But even if no shift was needed, update ksize */
5120         if (delta0)
5121                 node->mn_ksize = key->mv_size;
5122
5123         if (key->mv_size)
5124                 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
5125
5126         return MDB_SUCCESS;
5127 }
5128
5129 /** Move a node from csrc to cdst.
5130  */
5131 static int
5132 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
5133 {
5134         int                      rc;
5135         MDB_node                *srcnode;
5136         MDB_val          key, data;
5137         pgno_t  srcpg;
5138         unsigned short flags;
5139
5140         DKBUF;
5141
5142         /* Mark src and dst as dirty. */
5143         if ((rc = mdb_page_touch(csrc)) ||
5144             (rc = mdb_page_touch(cdst)))
5145                 return rc;
5146
5147         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5148                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);        /* fake */
5149                 key.mv_size = csrc->mc_db->md_pad;
5150                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5151                 data.mv_size = 0;
5152                 data.mv_data = NULL;
5153                 srcpg = 0;
5154                 flags = 0;
5155         } else {
5156                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
5157                 assert(!((long)srcnode&1));
5158                 srcpg = NODEPGNO(srcnode);
5159                 flags = srcnode->mn_flags;
5160                 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5161                         unsigned int snum = csrc->mc_snum;
5162                         MDB_node *s2;
5163                         /* must find the lowest key below src */
5164                         mdb_page_search_root(csrc, NULL, 0);
5165                         s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5166                         key.mv_size = NODEKSZ(s2);
5167                         key.mv_data = NODEKEY(s2);
5168                         csrc->mc_snum = snum--;
5169                         csrc->mc_top = snum;
5170                 } else {
5171                         key.mv_size = NODEKSZ(srcnode);
5172                         key.mv_data = NODEKEY(srcnode);
5173                 }
5174                 data.mv_size = NODEDSZ(srcnode);
5175                 data.mv_data = NODEDATA(srcnode);
5176         }
5177         if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
5178                 unsigned int snum = cdst->mc_snum;
5179                 MDB_node *s2;
5180                 MDB_val bkey;
5181                 /* must find the lowest key below dst */
5182                 mdb_page_search_root(cdst, NULL, 0);
5183                 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5184                 bkey.mv_size = NODEKSZ(s2);
5185                 bkey.mv_data = NODEKEY(s2);
5186                 cdst->mc_snum = snum--;
5187                 cdst->mc_top = snum;
5188                 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &bkey);
5189         }
5190
5191         DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
5192             IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
5193             csrc->mc_ki[csrc->mc_top],
5194                 DKEY(&key),
5195             csrc->mc_pg[csrc->mc_top]->mp_pgno,
5196             cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
5197
5198         /* Add the node to the destination page.
5199          */
5200         rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
5201         if (rc != MDB_SUCCESS)
5202                 return rc;
5203
5204         /* Delete the node from the source page.
5205          */
5206         mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5207
5208         {
5209                 /* Adjust other cursors pointing to mp */
5210                 MDB_cursor *m2, *m3;
5211                 MDB_dbi dbi = csrc->mc_dbi;
5212                 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
5213
5214                 if (csrc->mc_flags & C_SUB)
5215                         dbi--;
5216
5217                 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5218                         if (m2 == csrc) continue;
5219                         if (csrc->mc_flags & C_SUB)
5220                                 m3 = &m2->mc_xcursor->mx_cursor;
5221                         else
5222                                 m3 = m2;
5223                         if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
5224                                 csrc->mc_ki[csrc->mc_top]) {
5225                                 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
5226                                 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
5227                         }
5228                 }
5229         }
5230
5231         /* Update the parent separators.
5232          */
5233         if (csrc->mc_ki[csrc->mc_top] == 0) {
5234                 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
5235                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5236                                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5237                         } else {
5238                                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5239                                 key.mv_size = NODEKSZ(srcnode);
5240                                 key.mv_data = NODEKEY(srcnode);
5241                         }
5242                         DPRINTF("update separator for source page %zu to [%s]",
5243                                 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
5244                         if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
5245                                 &key)) != MDB_SUCCESS)
5246                                 return rc;
5247                 }
5248                 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5249                         MDB_val  nullkey;
5250                         nullkey.mv_size = 0;
5251                         rc = mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey);
5252                         assert(rc == MDB_SUCCESS);
5253                 }
5254         }
5255
5256         if (cdst->mc_ki[cdst->mc_top] == 0) {
5257                 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
5258                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5259                                 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
5260                         } else {
5261                                 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5262                                 key.mv_size = NODEKSZ(srcnode);
5263                                 key.mv_data = NODEKEY(srcnode);
5264                         }
5265                         DPRINTF("update separator for destination page %zu to [%s]",
5266                                 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
5267                         if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
5268                                 &key)) != MDB_SUCCESS)
5269                                 return rc;
5270                 }
5271                 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
5272                         MDB_val  nullkey;
5273                         nullkey.mv_size = 0;
5274                         rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey);
5275                         assert(rc == MDB_SUCCESS);
5276                 }
5277         }
5278
5279         return MDB_SUCCESS;
5280 }
5281
5282 /** Merge one page into another.
5283  *  The nodes from the page pointed to by \b csrc will
5284  *      be copied to the page pointed to by \b cdst and then
5285  *      the \b csrc page will be freed.
5286  * @param[in] csrc Cursor pointing to the source page.
5287  * @param[in] cdst Cursor pointing to the destination page.
5288  */
5289 static int
5290 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
5291 {
5292         int                      rc;
5293         indx_t                   i, j;
5294         MDB_node                *srcnode;
5295         MDB_val          key, data;
5296         unsigned        nkeys;
5297
5298         DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
5299                 cdst->mc_pg[cdst->mc_top]->mp_pgno);
5300
5301         assert(csrc->mc_snum > 1);      /* can't merge root page */
5302         assert(cdst->mc_snum > 1);
5303
5304         /* Mark dst as dirty. */
5305         if ((rc = mdb_page_touch(cdst)))
5306                 return rc;
5307
5308         /* Move all nodes from src to dst.
5309          */
5310         j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
5311         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5312                 key.mv_size = csrc->mc_db->md_pad;
5313                 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
5314                 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5315                         rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
5316                         if (rc != MDB_SUCCESS)
5317                                 return rc;
5318                         key.mv_data = (char *)key.mv_data + key.mv_size;
5319                 }
5320         } else {
5321                 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5322                         srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
5323                         if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5324                                 unsigned int snum = csrc->mc_snum;
5325                                 MDB_node *s2;
5326                                 /* must find the lowest key below src */
5327                                 mdb_page_search_root(csrc, NULL, 0);
5328                                 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5329                                 key.mv_size = NODEKSZ(s2);
5330                                 key.mv_data = NODEKEY(s2);
5331                                 csrc->mc_snum = snum--;
5332                                 csrc->mc_top = snum;
5333                         } else {
5334                                 key.mv_size = srcnode->mn_ksize;
5335                                 key.mv_data = NODEKEY(srcnode);
5336                         }
5337
5338                         data.mv_size = NODEDSZ(srcnode);
5339                         data.mv_data = NODEDATA(srcnode);
5340                         rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
5341                         if (rc != MDB_SUCCESS)
5342                                 return rc;
5343                 }
5344         }
5345
5346         DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
5347             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);
5348
5349         /* Unlink the src page from parent and add to free list.
5350          */
5351         mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
5352         if (csrc->mc_ki[csrc->mc_top-1] == 0) {
5353                 key.mv_size = 0;
5354                 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
5355                         return rc;
5356         }
5357
5358         mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
5359         if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
5360                 csrc->mc_db->md_leaf_pages--;
5361         else
5362                 csrc->mc_db->md_branch_pages--;
5363         {
5364                 /* Adjust other cursors pointing to mp */
5365                 MDB_cursor *m2, *m3;
5366                 MDB_dbi dbi = csrc->mc_dbi;
5367                 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
5368
5369                 if (csrc->mc_flags & C_SUB)
5370                         dbi--;
5371
5372                 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5373                         if (csrc->mc_flags & C_SUB)
5374                                 m3 = &m2->mc_xcursor->mx_cursor;
5375                         else
5376                                 m3 = m2;
5377                         if (m3 == csrc) continue;
5378                         if (m3->mc_snum < csrc->mc_snum) continue;
5379                         if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
5380                                 m3->mc_pg[csrc->mc_top] = mp;
5381                                 m3->mc_ki[csrc->mc_top] += nkeys;
5382                         }
5383                 }
5384         }
5385         mdb_cursor_pop(csrc);
5386
5387         return mdb_rebalance(csrc);
5388 }
5389
5390 /** Copy the contents of a cursor.
5391  * @param[in] csrc The cursor to copy from.
5392  * @param[out] cdst The cursor to copy to.
5393  */
5394 static void
5395 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
5396 {
5397         unsigned int i;
5398
5399         cdst->mc_txn = csrc->mc_txn;
5400         cdst->mc_dbi = csrc->mc_dbi;
5401         cdst->mc_db  = csrc->mc_db;
5402         cdst->mc_dbx = csrc->mc_dbx;
5403         cdst->mc_snum = csrc->mc_snum;
5404         cdst->mc_top = csrc->mc_top;
5405         cdst->mc_flags = csrc->mc_flags;
5406
5407         for (i=0; i<csrc->mc_snum; i++) {
5408                 cdst->mc_pg[i] = csrc->mc_pg[i];
5409                 cdst->mc_ki[i] = csrc->mc_ki[i];
5410         }
5411 }
5412
5413 /** Rebalance the tree after a delete operation.
5414  * @param[in] mc Cursor pointing to the page where rebalancing
5415  * should begin.
5416  * @return 0 on success, non-zero on failure.
5417  */
5418 static int
5419 mdb_rebalance(MDB_cursor *mc)
5420 {
5421         MDB_node        *node;
5422         int rc;
5423         unsigned int ptop;
5424         MDB_cursor      mn;
5425
5426 #if MDB_DEBUG
5427         {
5428         pgno_t pgno;
5429         COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5430         DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
5431             IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
5432             pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
5433         }
5434 #endif
5435
5436         if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
5437 #if MDB_DEBUG
5438                 pgno_t pgno;
5439                 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5440                 DPRINTF("no need to rebalance page %zu, above fill threshold",
5441                     pgno);
5442 #endif
5443                 return MDB_SUCCESS;
5444         }
5445
5446         if (mc->mc_snum < 2) {
5447                 MDB_page *mp = mc->mc_pg[0];
5448                 if (NUMKEYS(mp) == 0) {
5449                         DPUTS("tree is completely empty");
5450                         mc->mc_db->md_root = P_INVALID;
5451                         mc->mc_db->md_depth = 0;
5452                         mc->mc_db->md_leaf_pages = 0;
5453                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5454                         mc->mc_snum = 0;
5455                         mc->mc_top = 0;
5456                         {
5457                                 /* Adjust other cursors pointing to mp */
5458                                 MDB_cursor *m2, *m3;
5459                                 MDB_dbi dbi = mc->mc_dbi;
5460
5461                                 if (mc->mc_flags & C_SUB)
5462                                         dbi--;
5463
5464                                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5465                                         if (m2 == mc) continue;
5466                                         if (mc->mc_flags & C_SUB)
5467                                                 m3 = &m2->mc_xcursor->mx_cursor;
5468                                         else
5469                                                 m3 = m2;
5470                                         if (m3->mc_snum < mc->mc_snum) continue;
5471                                         if (m3->mc_pg[0] == mp) {
5472                                                 m3->mc_snum = 0;
5473                                                 m3->mc_top = 0;
5474                                         }
5475                                 }
5476                         }
5477                 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
5478                         DPUTS("collapsing root page!");
5479                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5480                         mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
5481                         if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
5482                                 &mc->mc_pg[0])))
5483                                 return rc;
5484                         mc->mc_db->md_depth--;
5485                         mc->mc_db->md_branch_pages--;
5486                         {
5487                                 /* Adjust other cursors pointing to mp */
5488                                 MDB_cursor *m2, *m3;
5489                                 MDB_dbi dbi = mc->mc_dbi;
5490
5491                                 if (mc->mc_flags & C_SUB)
5492                                         dbi--;
5493
5494                                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5495                                         if (m2 == mc) continue;
5496                                         if (mc->mc_flags & C_SUB)
5497                                                 m3 = &m2->mc_xcursor->mx_cursor;
5498                                         else
5499                                                 m3 = m2;
5500                                         if (m3->mc_snum < mc->mc_snum) continue;
5501                                         if (m3->mc_pg[0] == mp) {
5502                                                 m3->mc_pg[0] = mc->mc_pg[0];
5503                                         }
5504                                 }
5505                         }
5506                 } else
5507                         DPUTS("root page doesn't need rebalancing");
5508                 return MDB_SUCCESS;
5509         }
5510
5511         /* The parent (branch page) must have at least 2 pointers,
5512          * otherwise the tree is invalid.
5513          */
5514         ptop = mc->mc_top-1;
5515         assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
5516
5517         /* Leaf page fill factor is below the threshold.
5518          * Try to move keys from left or right neighbor, or
5519          * merge with a neighbor page.
5520          */
5521
5522         /* Find neighbors.
5523          */
5524         mdb_cursor_copy(mc, &mn);
5525         mn.mc_xcursor = NULL;
5526
5527         if (mc->mc_ki[ptop] == 0) {
5528                 /* We're the leftmost leaf in our parent.
5529                  */
5530                 DPUTS("reading right neighbor");
5531                 mn.mc_ki[ptop]++;
5532                 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5533                 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5534                         return rc;
5535                 mn.mc_ki[mn.mc_top] = 0;
5536                 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
5537         } else {
5538                 /* There is at least one neighbor to the left.
5539                  */
5540                 DPUTS("reading left neighbor");
5541                 mn.mc_ki[ptop]--;
5542                 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5543                 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5544                         return rc;
5545                 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
5546                 mc->mc_ki[mc->mc_top] = 0;
5547         }
5548
5549         DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
5550             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);
5551
5552         /* If the neighbor page is above threshold and has at least two
5553          * keys, move one key from it.
5554          *
5555          * Otherwise we should try to merge them.
5556          */
5557         if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
5558                 return mdb_node_move(&mn, mc);
5559         else { /* FIXME: if (has_enough_room()) */
5560                 mc->mc_flags &= ~C_INITIALIZED;
5561                 if (mc->mc_ki[ptop] == 0)
5562                         return mdb_page_merge(&mn, mc);
5563                 else
5564                         return mdb_page_merge(mc, &mn);
5565         }
5566 }
5567
5568 /** Complete a delete operation started by #mdb_cursor_del(). */
5569 static int
5570 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
5571 {
5572         int rc;
5573
5574         /* add overflow pages to free list */
5575         if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5576                 int i, ovpages;
5577                 pgno_t pg;
5578
5579                 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5580                 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5581                 mc->mc_db->md_overflow_pages -= ovpages;
5582                 for (i=0; i<ovpages; i++) {
5583                         DPRINTF("freed ov page %zu", pg);
5584                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5585                         pg++;
5586                 }
5587         }
5588         mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
5589         mc->mc_db->md_entries--;
5590         rc = mdb_rebalance(mc);
5591         if (rc != MDB_SUCCESS)
5592                 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5593
5594         return rc;
5595 }
5596
5597 int
5598 mdb_del(MDB_txn *txn, MDB_dbi dbi,
5599     MDB_val *key, MDB_val *data)
5600 {
5601         MDB_cursor mc;
5602         MDB_xcursor mx;
5603         MDB_cursor_op op;
5604         MDB_val rdata, *xdata;
5605         int              rc, exact;
5606         DKBUF;
5607
5608         assert(key != NULL);
5609
5610         DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
5611
5612         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5613                 return EINVAL;
5614
5615         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5616                 return EACCES;
5617         }
5618
5619         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5620                 return EINVAL;
5621         }
5622
5623         mdb_cursor_init(&mc, txn, dbi, &mx);
5624
5625         exact = 0;
5626         if (data) {
5627                 op = MDB_GET_BOTH;
5628                 rdata = *data;
5629                 xdata = &rdata;
5630         } else {
5631                 op = MDB_SET;
5632                 xdata = NULL;
5633         }
5634         rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
5635         if (rc == 0)
5636                 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
5637         return rc;
5638 }
5639
5640 /** Split a page and insert a new node.
5641  * @param[in,out] mc Cursor pointing to the page and desired insertion index.
5642  * The cursor will be updated to point to the actual page and index where
5643  * the node got inserted after the split.
5644  * @param[in] newkey The key for the newly inserted node.
5645  * @param[in] newdata The data for the newly inserted node.
5646  * @param[in] newpgno The page number, if the new node is a branch node.
5647  * @return 0 on success, non-zero on failure.
5648  */
5649 static int
5650 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
5651         unsigned int nflags)
5652 {
5653         unsigned int flags;
5654         int              rc = MDB_SUCCESS, ins_new = 0, new_root = 0, newpos = 1;
5655         indx_t           newindx;
5656         pgno_t           pgno = 0;
5657         unsigned int     i, j, split_indx, nkeys, pmax;
5658         MDB_node        *node;
5659         MDB_val  sepkey, rkey, xdata, *rdata = &xdata;
5660         MDB_page        *copy;
5661         MDB_page        *mp, *rp, *pp;
5662         unsigned int ptop;
5663         MDB_cursor      mn;
5664         DKBUF;
5665
5666         mp = mc->mc_pg[mc->mc_top];
5667         newindx = mc->mc_ki[mc->mc_top];
5668
5669         DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
5670             IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
5671             DKEY(newkey), mc->mc_ki[mc->mc_top]);
5672
5673         /* Create a right sibling. */
5674         if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
5675                 return ENOMEM;
5676         DPRINTF("new right sibling: page %zu", rp->mp_pgno);
5677
5678         if (mc->mc_snum < 2) {
5679                 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
5680                         return ENOMEM;
5681                 /* shift current top to make room for new parent */
5682                 mc->mc_pg[1] = mc->mc_pg[0];
5683                 mc->mc_ki[1] = mc->mc_ki[0];
5684                 mc->mc_pg[0] = pp;
5685                 mc->mc_ki[0] = 0;
5686                 mc->mc_db->md_root = pp->mp_pgno;
5687                 DPRINTF("root split! new root = %zu", pp->mp_pgno);
5688                 mc->mc_db->md_depth++;
5689                 new_root = 1;
5690
5691                 /* Add left (implicit) pointer. */
5692                 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
5693                         /* undo the pre-push */
5694                         mc->mc_pg[0] = mc->mc_pg[1];
5695                         mc->mc_ki[0] = mc->mc_ki[1];
5696                         mc->mc_db->md_root = mp->mp_pgno;
5697                         mc->mc_db->md_depth--;
5698                         return rc;
5699                 }
5700                 mc->mc_snum = 2;
5701                 mc->mc_top = 1;
5702                 ptop = 0;
5703         } else {
5704                 ptop = mc->mc_top-1;
5705                 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
5706         }
5707
5708         mdb_cursor_copy(mc, &mn);
5709         mn.mc_pg[mn.mc_top] = rp;
5710         mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
5711
5712         if (nflags & MDB_APPEND) {
5713                 mn.mc_ki[mn.mc_top] = 0;
5714                 sepkey = *newkey;
5715                 nkeys = 0;
5716                 split_indx = 0;
5717                 goto newsep;
5718         }
5719
5720         nkeys = NUMKEYS(mp);
5721         split_indx = (nkeys + 1) / 2;
5722
5723         if (IS_LEAF2(rp)) {
5724                 char *split, *ins;
5725                 int x;
5726                 unsigned int lsize, rsize, ksize;
5727                 /* Move half of the keys to the right sibling */
5728                 copy = NULL;
5729                 x = mc->mc_ki[mc->mc_top] - split_indx;
5730                 ksize = mc->mc_db->md_pad;
5731                 split = LEAF2KEY(mp, split_indx, ksize);
5732                 rsize = (nkeys - split_indx) * ksize;
5733                 lsize = (nkeys - split_indx) * sizeof(indx_t);
5734                 mp->mp_lower -= lsize;
5735                 rp->mp_lower += lsize;
5736                 mp->mp_upper += rsize - lsize;
5737                 rp->mp_upper -= rsize - lsize;
5738                 sepkey.mv_size = ksize;
5739                 if (newindx == split_indx) {
5740                         sepkey.mv_data = newkey->mv_data;
5741                 } else {
5742                         sepkey.mv_data = split;
5743                 }
5744                 if (x<0) {
5745                         ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
5746                         memcpy(rp->mp_ptrs, split, rsize);
5747                         sepkey.mv_data = rp->mp_ptrs;
5748                         memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
5749                         memcpy(ins, newkey->mv_data, ksize);
5750                         mp->mp_lower += sizeof(indx_t);
5751                         mp->mp_upper -= ksize - sizeof(indx_t);
5752                 } else {
5753                         if (x)
5754                                 memcpy(rp->mp_ptrs, split, x * ksize);
5755                         ins = LEAF2KEY(rp, x, ksize);
5756                         memcpy(ins, newkey->mv_data, ksize);
5757                         memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
5758                         rp->mp_lower += sizeof(indx_t);
5759                         rp->mp_upper -= ksize - sizeof(indx_t);
5760                         mc->mc_ki[mc->mc_top] = x;
5761                         mc->mc_pg[mc->mc_top] = rp;
5762                 }
5763                 goto newsep;
5764         }
5765
5766         /* For leaf pages, check the split point based on what
5767          * fits where, since otherwise mdb_node_add can fail.
5768          *
5769          * This check is only needed when the data items are
5770          * relatively large, such that being off by one will
5771          * make the difference between success or failure.
5772          * When the size of the data items is much smaller than
5773          * one-half of a page, this check is irrelevant.
5774          */
5775         if (IS_LEAF(mp)) {
5776                 unsigned int psize, nsize;
5777                 /* Maximum free space in an empty page */
5778                 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
5779                 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
5780                 if ((nkeys < 20) || (nsize > pmax/4)) {
5781                         if (newindx <= split_indx) {
5782                                 psize = nsize;
5783                                 newpos = 0;
5784                                 for (i=0; i<split_indx; i++) {
5785                                         node = NODEPTR(mp, i);
5786                                         psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5787                                         if (F_ISSET(node->mn_flags, F_BIGDATA))
5788                                                 psize += sizeof(pgno_t);
5789                                         else
5790                                                 psize += NODEDSZ(node);
5791                                         psize += psize & 1;
5792                                         if (psize > pmax) {
5793                                                 if (i == split_indx - 1 && newindx == split_indx)
5794                                                         newpos = 1;
5795                                                 else
5796                                                         split_indx = i;
5797                                                 break;
5798                                         }
5799                                 }
5800                         } else {
5801                                 psize = nsize;
5802                                 for (i=nkeys-1; i>=split_indx; i--) {
5803                                         node = NODEPTR(mp, i);
5804                                         psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5805                                         if (F_ISSET(node->mn_flags, F_BIGDATA))
5806                                                 psize += sizeof(pgno_t);
5807                                         else
5808                                                 psize += NODEDSZ(node);
5809                                         psize += psize & 1;
5810                                         if (psize > pmax) {
5811                                                 split_indx = i+1;
5812                                                 break;
5813                                         }
5814                                 }
5815                         }
5816                 }
5817         }
5818
5819         /* First find the separating key between the split pages.
5820          * The case where newindx == split_indx is ambiguous; the
5821          * new item could go to the new page or stay on the original
5822          * page. If newpos == 1 it goes to the new page.
5823          */
5824         if (newindx == split_indx && newpos) {
5825                 sepkey.mv_size = newkey->mv_size;
5826                 sepkey.mv_data = newkey->mv_data;
5827         } else {
5828                 node = NODEPTR(mp, split_indx);
5829                 sepkey.mv_size = node->mn_ksize;
5830                 sepkey.mv_data = NODEKEY(node);
5831         }
5832
5833 newsep:
5834         DPRINTF("separator is [%s]", DKEY(&sepkey));
5835
5836         /* Copy separator key to the parent.
5837          */
5838         if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
5839                 mn.mc_snum--;
5840                 mn.mc_top--;
5841                 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
5842
5843                 /* Right page might now have changed parent.
5844                  * Check if left page also changed parent.
5845                  */
5846                 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
5847                     mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
5848                         mc->mc_pg[ptop] = mn.mc_pg[ptop];
5849                         mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
5850                 }
5851         } else {
5852                 mn.mc_top--;
5853                 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
5854                 mn.mc_top++;
5855         }
5856         if (rc != MDB_SUCCESS) {
5857                 return rc;
5858         }
5859         if (nflags & MDB_APPEND) {
5860                 mc->mc_pg[mc->mc_top] = rp;
5861                 mc->mc_ki[mc->mc_top] = 0;
5862                 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
5863                 if (rc)
5864                         return rc;
5865                 goto done;
5866         }
5867         if (IS_LEAF2(rp)) {
5868                 goto done;
5869         }
5870
5871         /* Move half of the keys to the right sibling. */
5872
5873         /* grab a page to hold a temporary copy */
5874         copy = mdb_page_malloc(mc);
5875         if (copy == NULL)
5876                 return ENOMEM;
5877
5878         copy->mp_pgno  = mp->mp_pgno;
5879         copy->mp_flags = mp->mp_flags;
5880         copy->mp_lower = PAGEHDRSZ;
5881         copy->mp_upper = mc->mc_txn->mt_env->me_psize;
5882         mc->mc_pg[mc->mc_top] = copy;
5883         for (i = j = 0; i <= nkeys; j++) {
5884                 if (i == split_indx) {
5885                 /* Insert in right sibling. */
5886                 /* Reset insert index for right sibling. */
5887                         if (i != newindx || (newpos ^ ins_new)) {
5888                                 j = 0;
5889                                 mc->mc_pg[mc->mc_top] = rp;
5890                         }
5891                 }
5892
5893                 if (i == newindx && !ins_new) {
5894                         /* Insert the original entry that caused the split. */
5895                         rkey.mv_data = newkey->mv_data;
5896                         rkey.mv_size = newkey->mv_size;
5897                         if (IS_LEAF(mp)) {
5898                                 rdata = newdata;
5899                         } else
5900                                 pgno = newpgno;
5901                         flags = nflags;
5902
5903                         ins_new = 1;
5904
5905                         /* Update index for the new key. */
5906                         mc->mc_ki[mc->mc_top] = j;
5907                 } else if (i == nkeys) {
5908                         break;
5909                 } else {
5910                         node = NODEPTR(mp, i);
5911                         rkey.mv_data = NODEKEY(node);
5912                         rkey.mv_size = node->mn_ksize;
5913                         if (IS_LEAF(mp)) {
5914                                 xdata.mv_data = NODEDATA(node);
5915                                 xdata.mv_size = NODEDSZ(node);
5916                                 rdata = &xdata;
5917                         } else
5918                                 pgno = NODEPGNO(node);
5919                         flags = node->mn_flags;
5920
5921                         i++;
5922                 }
5923
5924                 if (!IS_LEAF(mp) && j == 0) {
5925                         /* First branch index doesn't need key data. */
5926                         rkey.mv_size = 0;
5927                 }
5928
5929                 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
5930                 if (rc) break;
5931         }
5932
5933         nkeys = NUMKEYS(copy);
5934         for (i=0; i<nkeys; i++)
5935                 mp->mp_ptrs[i] = copy->mp_ptrs[i];
5936         mp->mp_lower = copy->mp_lower;
5937         mp->mp_upper = copy->mp_upper;
5938         memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
5939                 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
5940
5941         /* reset back to original page */
5942         if (newindx < split_indx || (!newpos && newindx == split_indx)) {
5943                 mc->mc_pg[mc->mc_top] = mp;
5944                 if (nflags & MDB_RESERVE) {
5945                         node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5946                         if (!(node->mn_flags & F_BIGDATA))
5947                                 newdata->mv_data = NODEDATA(node);
5948                 }
5949         }
5950
5951         /* return tmp page to freelist */
5952         copy->mp_next = mc->mc_txn->mt_env->me_dpages;
5953         VGMEMP_FREE(mc->mc_txn->mt_env, copy);
5954         mc->mc_txn->mt_env->me_dpages = copy;
5955 done:
5956         {
5957                 /* Adjust other cursors pointing to mp */
5958                 MDB_cursor *m2, *m3;
5959                 MDB_dbi dbi = mc->mc_dbi;
5960
5961                 if (mc->mc_flags & C_SUB)
5962                         dbi--;
5963
5964                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5965                         if (m2 == mc) continue;
5966                         if (mc->mc_flags & C_SUB)
5967                                 m3 = &m2->mc_xcursor->mx_cursor;
5968                         else
5969                                 m3 = m2;
5970                         if (!(m3->mc_flags & C_INITIALIZED))
5971                                 continue;
5972                         if (new_root) {
5973                                 int k;
5974                                 /* root split */
5975                                 for (k=m3->mc_top; k>=0; k--) {
5976                                         m3->mc_ki[k+1] = m3->mc_ki[k];
5977                                         m3->mc_pg[k+1] = m3->mc_pg[k];
5978                                 }
5979                                 m3->mc_ki[0] = mc->mc_ki[0];
5980                                 m3->mc_pg[0] = mc->mc_pg[0];
5981                                 m3->mc_snum++;
5982                                 m3->mc_top++;
5983                         }
5984                         if (m3->mc_pg[mc->mc_top] == mp) {
5985                                 if (m3->mc_ki[m3->mc_top] >= split_indx) {
5986                                         m3->mc_pg[m3->mc_top] = rp;
5987                                         m3->mc_ki[m3->mc_top] -= split_indx;
5988                                 }
5989                         }
5990                 }
5991         }
5992         return rc;
5993 }
5994
5995 int
5996 mdb_put(MDB_txn *txn, MDB_dbi dbi,
5997     MDB_val *key, MDB_val *data, unsigned int flags)
5998 {
5999         MDB_cursor mc;
6000         MDB_xcursor mx;
6001
6002         assert(key != NULL);
6003         assert(data != NULL);
6004
6005         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6006                 return EINVAL;
6007
6008         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
6009                 return EACCES;
6010         }
6011
6012         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
6013                 return EINVAL;
6014         }
6015
6016         if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
6017                 return EINVAL;
6018
6019         mdb_cursor_init(&mc, txn, dbi, &mx);
6020         return mdb_cursor_put(&mc, key, data, flags);
6021 }
6022
6023 /** Only a subset of the @ref mdb_env flags can be changed
6024  *      at runtime. Changing other flags requires closing the environment
6025  *      and re-opening it with the new flags.
6026  */
6027 #define CHANGEABLE      (MDB_NOSYNC)
6028 int
6029 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
6030 {
6031         if ((flag & CHANGEABLE) != flag)
6032                 return EINVAL;
6033         if (onoff)
6034                 env->me_flags |= flag;
6035         else
6036                 env->me_flags &= ~flag;
6037         return MDB_SUCCESS;
6038 }
6039
6040 int
6041 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
6042 {
6043         if (!env || !arg)
6044                 return EINVAL;
6045
6046         *arg = env->me_flags;
6047         return MDB_SUCCESS;
6048 }
6049
6050 int
6051 mdb_env_get_path(MDB_env *env, const char **arg)
6052 {
6053         if (!env || !arg)
6054                 return EINVAL;
6055
6056         *arg = env->me_path;
6057         return MDB_SUCCESS;
6058 }
6059
6060 /** Common code for #mdb_stat() and #mdb_env_stat().
6061  * @param[in] env the environment to operate in.
6062  * @param[in] db the #MDB_db record containing the stats to return.
6063  * @param[out] arg the address of an #MDB_stat structure to receive the stats.
6064  * @return 0, this function always succeeds.
6065  */
6066 static int
6067 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
6068 {
6069         arg->ms_psize = env->me_psize;
6070         arg->ms_depth = db->md_depth;
6071         arg->ms_branch_pages = db->md_branch_pages;
6072         arg->ms_leaf_pages = db->md_leaf_pages;
6073         arg->ms_overflow_pages = db->md_overflow_pages;
6074         arg->ms_entries = db->md_entries;
6075
6076         return MDB_SUCCESS;
6077 }
6078 int
6079 mdb_env_stat(MDB_env *env, MDB_stat *arg)
6080 {
6081         int toggle;
6082
6083         if (env == NULL || arg == NULL)
6084                 return EINVAL;
6085
6086         mdb_env_read_meta(env, &toggle);
6087
6088         return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
6089 }
6090
6091 /** Set the default comparison functions for a database.
6092  * Called immediately after a database is opened to set the defaults.
6093  * The user can then override them with #mdb_set_compare() or
6094  * #mdb_set_dupsort().
6095  * @param[in] txn A transaction handle returned by #mdb_txn_begin()
6096  * @param[in] dbi A database handle returned by #mdb_open()
6097  */
6098 static void
6099 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
6100 {
6101         if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
6102                 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memnr;
6103         else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
6104                 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_cint;
6105         else
6106                 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memn;
6107
6108         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6109                 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
6110                         if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
6111                                 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_int;
6112                         else
6113                                 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_cint;
6114                 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
6115                         txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memnr;
6116                 } else {
6117                         txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memn;
6118                 }
6119         } else {
6120                 txn->mt_dbxs[dbi].md_dcmp = NULL;
6121         }
6122 }
6123
6124 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
6125 {
6126         MDB_val key, data;
6127         MDB_dbi i;
6128         MDB_cursor mc;
6129         int rc, dbflag, exact;
6130         size_t len;
6131
6132         if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
6133                 mdb_default_cmp(txn, FREE_DBI);
6134         }
6135
6136         /* main DB? */
6137         if (!name) {
6138                 *dbi = MAIN_DBI;
6139                 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
6140                         txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
6141                 mdb_default_cmp(txn, MAIN_DBI);
6142                 return MDB_SUCCESS;
6143         }
6144
6145         if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
6146                 mdb_default_cmp(txn, MAIN_DBI);
6147         }
6148
6149         /* Is the DB already open? */
6150         len = strlen(name);
6151         for (i=2; i<txn->mt_numdbs; i++) {
6152                 if (len == txn->mt_dbxs[i].md_name.mv_size &&
6153                         !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
6154                         *dbi = i;
6155                         return MDB_SUCCESS;
6156                 }
6157         }
6158
6159         if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
6160                 return ENFILE;
6161
6162         /* Find the DB info */
6163         dbflag = 0;
6164         exact = 0;
6165         key.mv_size = len;
6166         key.mv_data = (void *)name;
6167         mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
6168         rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
6169         if (rc == MDB_SUCCESS) {
6170                 /* make sure this is actually a DB */
6171                 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
6172                 if (!(node->mn_flags & F_SUBDATA))
6173                         return EINVAL;
6174         } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
6175                 /* Create if requested */
6176                 MDB_db dummy;
6177                 data.mv_size = sizeof(MDB_db);
6178                 data.mv_data = &dummy;
6179                 memset(&dummy, 0, sizeof(dummy));
6180                 dummy.md_root = P_INVALID;
6181                 dummy.md_flags = flags & 0xffff;
6182                 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
6183                 dbflag = DB_DIRTY;
6184         }
6185
6186         /* OK, got info, add to table */
6187         if (rc == MDB_SUCCESS) {
6188                 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
6189                 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
6190                 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
6191                 txn->mt_dbflags[txn->mt_numdbs] = dbflag;
6192                 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
6193                 *dbi = txn->mt_numdbs;
6194                 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
6195                 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
6196                 mdb_default_cmp(txn, txn->mt_numdbs);
6197                 txn->mt_numdbs++;
6198         }
6199
6200         return rc;
6201 }
6202
6203 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
6204 {
6205         if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
6206                 return EINVAL;
6207
6208         return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
6209 }
6210
6211 void mdb_close(MDB_env *env, MDB_dbi dbi)
6212 {
6213         char *ptr;
6214         if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
6215                 return;
6216         ptr = env->me_dbxs[dbi].md_name.mv_data;
6217         env->me_dbxs[dbi].md_name.mv_data = NULL;
6218         env->me_dbxs[dbi].md_name.mv_size = 0;
6219         free(ptr);
6220 }
6221
6222 /** Add all the DB's pages to the free list.
6223  * @param[in] mc Cursor on the DB to free.
6224  * @param[in] subs non-Zero to check for sub-DBs in this DB.
6225  * @return 0 on success, non-zero on failure.
6226  */
6227 static int
6228 mdb_drop0(MDB_cursor *mc, int subs)
6229 {
6230         int rc;
6231
6232         rc = mdb_page_search(mc, NULL, 0);
6233         if (rc == MDB_SUCCESS) {
6234                 MDB_node *ni;
6235                 MDB_cursor mx;
6236                 unsigned int i;
6237
6238                 /* LEAF2 pages have no nodes, cannot have sub-DBs */
6239                 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
6240                         mdb_cursor_pop(mc);
6241
6242                 mdb_cursor_copy(mc, &mx);
6243                 while (mc->mc_snum > 0) {
6244                         if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
6245                                 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
6246                                         ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
6247                                         if (ni->mn_flags & F_SUBDATA) {
6248                                                 mdb_xcursor_init1(mc, ni);
6249                                                 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6250                                                 if (rc)
6251                                                         return rc;
6252                                         }
6253                                 }
6254                         } else {
6255                                 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
6256                                         pgno_t pg;
6257                                         ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
6258                                         pg = NODEPGNO(ni);
6259                                         /* free it */
6260                                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
6261                                 }
6262                         }
6263                         if (!mc->mc_top)
6264                                 break;
6265                         rc = mdb_cursor_sibling(mc, 1);
6266                         if (rc) {
6267                                 /* no more siblings, go back to beginning
6268                                  * of previous level. (stack was already popped
6269                                  * by mdb_cursor_sibling)
6270                                  */
6271                                 for (i=1; i<mc->mc_top; i++)
6272                                         mc->mc_pg[i] = mx.mc_pg[i];
6273                         }
6274                 }
6275                 /* free it */
6276                 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
6277                         mc->mc_db->md_root);
6278         }
6279         return 0;
6280 }
6281
6282 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
6283 {
6284         MDB_cursor *mc;
6285         int rc;
6286
6287         if (!txn || !dbi || dbi >= txn->mt_numdbs)
6288                 return EINVAL;
6289
6290         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6291                 return EACCES;
6292
6293         rc = mdb_cursor_open(txn, dbi, &mc);
6294         if (rc)
6295                 return rc;
6296
6297         rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
6298         if (rc)
6299                 goto leave;
6300
6301         /* Can't delete the main DB */
6302         if (del && dbi > MAIN_DBI) {
6303                 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
6304                 if (!rc)
6305                         mdb_close(txn->mt_env, dbi);
6306         } else {
6307                 txn->mt_dbflags[dbi] |= DB_DIRTY;
6308                 txn->mt_dbs[dbi].md_depth = 0;
6309                 txn->mt_dbs[dbi].md_branch_pages = 0;
6310                 txn->mt_dbs[dbi].md_leaf_pages = 0;
6311                 txn->mt_dbs[dbi].md_overflow_pages = 0;
6312                 txn->mt_dbs[dbi].md_entries = 0;
6313                 txn->mt_dbs[dbi].md_root = P_INVALID;
6314         }
6315 leave:
6316         mdb_cursor_close(mc);
6317         return rc;
6318 }
6319
6320 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6321 {
6322         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6323                 return EINVAL;
6324
6325         txn->mt_dbxs[dbi].md_cmp = cmp;
6326         return MDB_SUCCESS;
6327 }
6328
6329 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6330 {
6331         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6332                 return EINVAL;
6333
6334         txn->mt_dbxs[dbi].md_dcmp = cmp;
6335         return MDB_SUCCESS;
6336 }
6337
6338 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
6339 {
6340         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6341                 return EINVAL;
6342
6343         txn->mt_dbxs[dbi].md_rel = rel;
6344         return MDB_SUCCESS;
6345 }
6346
6347 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
6348 {
6349         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6350                 return EINVAL;
6351
6352         txn->mt_dbxs[dbi].md_relctx = ctx;
6353         return MDB_SUCCESS;
6354 }
6355
6356 /** @} */