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