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