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