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