]> git.sur5r.net Git - openldap/blob - libraries/libmdb/mdb.c
Fix txn_commit error check
[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 && !(mc->mc_flags & C_INITIALIZED)) 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         /* Update DB root pointers. Their pages have already been
1881          * touched so this is all in-place and cannot fail.
1882          */
1883         {
1884                 MDB_dbi i;
1885                 MDB_val data;
1886                 data.mv_size = sizeof(MDB_db);
1887
1888                 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
1889                 for (i = 2; i < txn->mt_numdbs; i++) {
1890                         if (txn->mt_dbflags[i] & DB_DIRTY) {
1891                                 data.mv_data = &txn->mt_dbs[i];
1892                                 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1893                         }
1894                 }
1895         }
1896
1897         mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1898
1899         /* should only be one record now */
1900         if (env->me_pghead) {
1901                 /* make sure first page of freeDB is touched and on freelist */
1902                 mdb_page_search(&mc, NULL, MDB_PS_MODIFY);
1903         }
1904
1905         /* Delete IDLs we used from the free list */
1906         if (env->me_pgfirst) {
1907                 txnid_t cur;
1908                 MDB_val key;
1909                 int exact = 0;
1910
1911                 key.mv_size = sizeof(cur);
1912                 for (cur = env->me_pgfirst; cur <= env->me_pglast; cur++) {
1913                         key.mv_data = &cur;
1914
1915                         mdb_cursor_set(&mc, &key, NULL, MDB_SET, &exact);
1916                         rc = mdb_cursor_del(&mc, 0);
1917                         if (rc) {
1918                                 mdb_txn_abort(txn);
1919                                 return rc;
1920                         }
1921                 }
1922                 env->me_pgfirst = 0;
1923                 env->me_pglast = 0;
1924         }
1925
1926         /* save to free list */
1927 free2:
1928         freecnt = txn->mt_free_pgs[0];
1929         if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1930                 MDB_val key, data;
1931
1932                 /* make sure last page of freeDB is touched and on freelist */
1933                 key.mv_size = MAXKEYSIZE+1;
1934                 key.mv_data = NULL;
1935                 mdb_page_search(&mc, &key, MDB_PS_MODIFY);
1936
1937                 mdb_midl_sort(txn->mt_free_pgs);
1938 #if MDB_DEBUG > 1
1939                 {
1940                         unsigned int i;
1941                         MDB_IDL idl = txn->mt_free_pgs;
1942                         DPRINTF("IDL write txn %zu root %zu num %zu",
1943                                 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1944                         for (i=0; i<idl[0]; i++) {
1945                                 DPRINTF("IDL %zu", idl[i+1]);
1946                         }
1947                 }
1948 #endif
1949                 /* write to last page of freeDB */
1950                 key.mv_size = sizeof(pgno_t);
1951                 key.mv_data = &txn->mt_txnid;
1952                 data.mv_data = txn->mt_free_pgs;
1953                 /* The free list can still grow during this call,
1954                  * despite the pre-emptive touches above. So check
1955                  * and make sure the entire thing got written.
1956                  */
1957                 do {
1958                         freecnt = txn->mt_free_pgs[0];
1959                         data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1960                         rc = mdb_cursor_put(&mc, &key, &data, 0);
1961                         if (rc) {
1962                                 mdb_txn_abort(txn);
1963                                 return rc;
1964                         }
1965                 } while (freecnt != txn->mt_free_pgs[0]);
1966         }
1967         /* should only be one record now */
1968 again:
1969         if (env->me_pghead) {
1970                 MDB_val key, data;
1971                 MDB_oldpages *mop;
1972                 pgno_t orig;
1973                 txnid_t id;
1974
1975                 mop = env->me_pghead;
1976                 id = mop->mo_txnid;
1977                 key.mv_size = sizeof(id);
1978                 key.mv_data = &id;
1979                 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1980                 data.mv_data = mop->mo_pages;
1981                 orig = mop->mo_pages[0];
1982                 /* These steps may grow the freelist again
1983                  * due to freed overflow pages...
1984                  */
1985                 mdb_cursor_put(&mc, &key, &data, 0);
1986                 if (mop == env->me_pghead && env->me_pghead->mo_txnid == id) {
1987                         /* could have been used again here */
1988                         if (mop->mo_pages[0] != orig) {
1989                                 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1990                                 data.mv_data = mop->mo_pages;
1991                                 id = mop->mo_txnid;
1992                                 mdb_cursor_put(&mc, &key, &data, 0);
1993                         }
1994                         env->me_pghead = NULL;
1995                         free(mop);
1996                 } else {
1997                         /* was completely used up */
1998                         mdb_cursor_del(&mc, 0);
1999                         if (env->me_pghead)
2000                                 goto again;
2001                 }
2002                 env->me_pgfirst = 0;
2003                 env->me_pglast = 0;
2004         }
2005
2006         while (env->me_pgfree) {
2007                 MDB_oldpages *mop = env->me_pgfree;
2008                 env->me_pgfree = mop->mo_next;
2009                 free(mop);;
2010         }
2011
2012         /* Check for growth of freelist again */
2013         if (freecnt != txn->mt_free_pgs[0])
2014                 goto free2;
2015
2016         if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
2017                 if (mdb_midl_shrink(&txn->mt_free_pgs))
2018                         env->me_free_pgs = txn->mt_free_pgs;
2019         }
2020
2021 #if MDB_DEBUG > 2
2022         mdb_audit(txn);
2023 #endif
2024
2025         /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
2026          */
2027         next = 0;
2028         i = 1;
2029         do {
2030 #ifdef _WIN32
2031                 /* Windows actually supports scatter/gather I/O, but only on
2032                  * unbuffered file handles. Since we're relying on the OS page
2033                  * cache for all our data, that's self-defeating. So we just
2034                  * write pages one at a time. We use the ov structure to set
2035                  * the write offset, to at least save the overhead of a Seek
2036                  * system call.
2037                  */
2038                 OVERLAPPED ov;
2039                 memset(&ov, 0, sizeof(ov));
2040                 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2041                         size_t wsize;
2042                         dp = txn->mt_u.dirty_list[i].mptr;
2043                         DPRINTF("committing page %zu", dp->mp_pgno);
2044                         size = dp->mp_pgno * env->me_psize;
2045                         ov.Offset = size & 0xffffffff;
2046                         ov.OffsetHigh = size >> 16;
2047                         ov.OffsetHigh >>= 16;
2048                         /* clear dirty flag */
2049                         dp->mp_flags &= ~P_DIRTY;
2050                         wsize = env->me_psize;
2051                         if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
2052                         rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
2053                         if (!rc) {
2054                                 n = ErrCode();
2055                                 DPRINTF("WriteFile: %d", n);
2056                                 mdb_txn_abort(txn);
2057                                 return n;
2058                         }
2059                 }
2060                 done = 1;
2061 #else
2062                 struct iovec     iov[MDB_COMMIT_PAGES];
2063                 n = 0;
2064                 done = 1;
2065                 size = 0;
2066                 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2067                         dp = txn->mt_u.dirty_list[i].mptr;
2068                         if (dp->mp_pgno != next) {
2069                                 if (n) {
2070                                         rc = writev(env->me_fd, iov, n);
2071                                         if (rc != size) {
2072                                                 n = ErrCode();
2073                                                 if (rc > 0)
2074                                                         DPUTS("short write, filesystem full?");
2075                                                 else
2076                                                         DPRINTF("writev: %s", strerror(n));
2077                                                 mdb_txn_abort(txn);
2078                                                 return n;
2079                                         }
2080                                         n = 0;
2081                                         size = 0;
2082                                 }
2083                                 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
2084                                 next = dp->mp_pgno;
2085                         }
2086                         DPRINTF("committing page %zu", dp->mp_pgno);
2087                         iov[n].iov_len = env->me_psize;
2088                         if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
2089                         iov[n].iov_base = (char *)dp;
2090                         size += iov[n].iov_len;
2091                         next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
2092                         /* clear dirty flag */
2093                         dp->mp_flags &= ~P_DIRTY;
2094                         if (++n >= MDB_COMMIT_PAGES) {
2095                                 done = 0;
2096                                 i++;
2097                                 break;
2098                         }
2099                 }
2100
2101                 if (n == 0)
2102                         break;
2103
2104                 rc = writev(env->me_fd, iov, n);
2105                 if (rc != size) {
2106                         n = ErrCode();
2107                         if (rc > 0)
2108                                 DPUTS("short write, filesystem full?");
2109                         else
2110                                 DPRINTF("writev: %s", strerror(n));
2111                         mdb_txn_abort(txn);
2112                         return n;
2113                 }
2114 #endif
2115         } while (!done);
2116
2117         /* Drop the dirty pages.
2118          */
2119         for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
2120                 dp = txn->mt_u.dirty_list[i].mptr;
2121                 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
2122                         dp->mp_next = txn->mt_env->me_dpages;
2123                         VGMEMP_FREE(txn->mt_env, dp);
2124                         txn->mt_env->me_dpages = dp;
2125                 } else {
2126                         VGMEMP_FREE(txn->mt_env, dp);
2127                         free(dp);
2128                 }
2129                 txn->mt_u.dirty_list[i].mid = 0;
2130         }
2131         txn->mt_u.dirty_list[0].mid = 0;
2132
2133         if ((n = mdb_env_sync(env, 0)) != 0 ||
2134             (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
2135                 mdb_txn_abort(txn);
2136                 return n;
2137         }
2138
2139 done:
2140         env->me_txn = NULL;
2141         if (txn->mt_numdbs > env->me_numdbs) {
2142                 /* update the DB flags */
2143                 MDB_dbi i;
2144                 for (i = env->me_numdbs; i<txn->mt_numdbs; i++)
2145                         env->me_dbflags[i] = txn->mt_dbs[i].md_flags;
2146                 env->me_numdbs = i;
2147         }
2148
2149         UNLOCK_MUTEX_W(env);
2150         free(txn);
2151
2152         return MDB_SUCCESS;
2153 }
2154
2155 /** Read the environment parameters of a DB environment before
2156  * mapping it into memory.
2157  * @param[in] env the environment handle
2158  * @param[out] meta address of where to store the meta information
2159  * @return 0 on success, non-zero on failure.
2160  */
2161 static int
2162 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2163 {
2164         MDB_pagebuf     pbuf;
2165         MDB_page        *p;
2166         MDB_meta        *m;
2167         int              rc, err;
2168
2169         /* We don't know the page size yet, so use a minimum value.
2170          */
2171
2172 #ifdef _WIN32
2173         if (!ReadFile(env->me_fd, &pbuf, MDB_PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
2174 #else
2175         if ((rc = read(env->me_fd, &pbuf, MDB_PAGESIZE)) == 0)
2176 #endif
2177         {
2178                 return ENOENT;
2179         }
2180         else if (rc != MDB_PAGESIZE) {
2181                 err = ErrCode();
2182                 if (rc > 0)
2183                         err = EINVAL;
2184                 DPRINTF("read: %s", strerror(err));
2185                 return err;
2186         }
2187
2188         p = (MDB_page *)&pbuf;
2189
2190         if (!F_ISSET(p->mp_flags, P_META)) {
2191                 DPRINTF("page %zu not a meta page", p->mp_pgno);
2192                 return EINVAL;
2193         }
2194
2195         m = METADATA(p);
2196         if (m->mm_magic != MDB_MAGIC) {
2197                 DPUTS("meta has invalid magic");
2198                 return EINVAL;
2199         }
2200
2201         if (m->mm_version != MDB_VERSION) {
2202                 DPRINTF("database is version %u, expected version %u",
2203                     m->mm_version, MDB_VERSION);
2204                 return MDB_VERSION_MISMATCH;
2205         }
2206
2207         memcpy(meta, m, sizeof(*m));
2208         return 0;
2209 }
2210
2211 /** Write the environment parameters of a freshly created DB environment.
2212  * @param[in] env the environment handle
2213  * @param[out] meta address of where to store the meta information
2214  * @return 0 on success, non-zero on failure.
2215  */
2216 static int
2217 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2218 {
2219         MDB_page *p, *q;
2220         MDB_meta *m;
2221         int rc;
2222         unsigned int     psize;
2223
2224         DPUTS("writing new meta page");
2225
2226         GET_PAGESIZE(psize);
2227
2228         meta->mm_magic = MDB_MAGIC;
2229         meta->mm_version = MDB_VERSION;
2230         meta->mm_psize = psize;
2231         meta->mm_last_pg = 1;
2232         meta->mm_flags = env->me_flags & 0xffff;
2233         meta->mm_flags |= MDB_INTEGERKEY;
2234         meta->mm_dbs[0].md_root = P_INVALID;
2235         meta->mm_dbs[1].md_root = P_INVALID;
2236
2237         p = calloc(2, psize);
2238         p->mp_pgno = 0;
2239         p->mp_flags = P_META;
2240
2241         m = METADATA(p);
2242         memcpy(m, meta, sizeof(*meta));
2243
2244         q = (MDB_page *)((char *)p + psize);
2245
2246         q->mp_pgno = 1;
2247         q->mp_flags = P_META;
2248
2249         m = METADATA(q);
2250         memcpy(m, meta, sizeof(*meta));
2251
2252 #ifdef _WIN32
2253         {
2254                 DWORD len;
2255                 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2256                 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2257         }
2258 #else
2259         rc = write(env->me_fd, p, psize * 2);
2260         rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2261 #endif
2262         free(p);
2263         return rc;
2264 }
2265
2266 /** Update the environment info to commit a transaction.
2267  * @param[in] txn the transaction that's being committed
2268  * @return 0 on success, non-zero on failure.
2269  */
2270 static int
2271 mdb_env_write_meta(MDB_txn *txn)
2272 {
2273         MDB_env *env;
2274         MDB_meta        meta, metab;
2275         off_t off;
2276         int rc, len, toggle;
2277         char *ptr;
2278 #ifdef _WIN32
2279         OVERLAPPED ov;
2280 #endif
2281
2282         assert(txn != NULL);
2283         assert(txn->mt_env != NULL);
2284
2285         toggle = !txn->mt_toggle;
2286         DPRINTF("writing meta page %d for root page %zu",
2287                 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2288
2289         env = txn->mt_env;
2290
2291         metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2292         metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2293
2294         ptr = (char *)&meta;
2295         off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2296         len = sizeof(MDB_meta) - off;
2297
2298         ptr += off;
2299         meta.mm_dbs[0] = txn->mt_dbs[0];
2300         meta.mm_dbs[1] = txn->mt_dbs[1];
2301         meta.mm_last_pg = txn->mt_next_pgno - 1;
2302         meta.mm_txnid = txn->mt_txnid;
2303
2304         if (toggle)
2305                 off += env->me_psize;
2306         off += PAGEHDRSZ;
2307
2308         /* Write to the SYNC fd */
2309 #ifdef _WIN32
2310         {
2311                 memset(&ov, 0, sizeof(ov));
2312                 ov.Offset = off;
2313                 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
2314         }
2315 #else
2316         rc = pwrite(env->me_mfd, ptr, len, off);
2317 #endif
2318         if (rc != len) {
2319                 int r2;
2320                 rc = ErrCode();
2321                 DPUTS("write failed, disk error?");
2322                 /* On a failure, the pagecache still contains the new data.
2323                  * Write some old data back, to prevent it from being used.
2324                  * Use the non-SYNC fd; we know it will fail anyway.
2325                  */
2326                 meta.mm_last_pg = metab.mm_last_pg;
2327                 meta.mm_txnid = metab.mm_txnid;
2328 #ifdef _WIN32
2329                 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2330 #else
2331                 r2 = pwrite(env->me_fd, ptr, len, off);
2332 #endif
2333                 env->me_flags |= MDB_FATAL_ERROR;
2334                 return rc;
2335         }
2336         /* Memory ordering issues are irrelevant; since the entire writer
2337          * is wrapped by wmutex, all of these changes will become visible
2338          * after the wmutex is unlocked. Since the DB is multi-version,
2339          * readers will get consistent data regardless of how fresh or
2340          * how stale their view of these values is.
2341          */
2342         txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2343
2344         return MDB_SUCCESS;
2345 }
2346
2347 /** Check both meta pages to see which one is newer.
2348  * @param[in] env the environment handle
2349  * @return meta toggle (0 or 1).
2350  */
2351 static int
2352 mdb_env_pick_meta(const MDB_env *env)
2353 {
2354         return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
2355 }
2356
2357 int
2358 mdb_env_create(MDB_env **env)
2359 {
2360         MDB_env *e;
2361
2362         e = calloc(1, sizeof(MDB_env));
2363         if (!e)
2364                 return ENOMEM;
2365
2366         e->me_free_pgs = mdb_midl_alloc();
2367         if (!e->me_free_pgs) {
2368                 free(e);
2369                 return ENOMEM;
2370         }
2371         e->me_maxreaders = DEFAULT_READERS;
2372         e->me_maxdbs = 2;
2373         e->me_fd = INVALID_HANDLE_VALUE;
2374         e->me_lfd = INVALID_HANDLE_VALUE;
2375         e->me_mfd = INVALID_HANDLE_VALUE;
2376         VGMEMP_CREATE(e,0,0);
2377         *env = e;
2378         return MDB_SUCCESS;
2379 }
2380
2381 int
2382 mdb_env_set_mapsize(MDB_env *env, size_t size)
2383 {
2384         if (env->me_map)
2385                 return EINVAL;
2386         env->me_mapsize = size;
2387         if (env->me_psize)
2388                 env->me_maxpg = env->me_mapsize / env->me_psize;
2389         return MDB_SUCCESS;
2390 }
2391
2392 int
2393 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2394 {
2395         if (env->me_map)
2396                 return EINVAL;
2397         env->me_maxdbs = dbs;
2398         return MDB_SUCCESS;
2399 }
2400
2401 int
2402 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2403 {
2404         if (env->me_map || readers < 1)
2405                 return EINVAL;
2406         env->me_maxreaders = readers;
2407         return MDB_SUCCESS;
2408 }
2409
2410 int
2411 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2412 {
2413         if (!env || !readers)
2414                 return EINVAL;
2415         *readers = env->me_maxreaders;
2416         return MDB_SUCCESS;
2417 }
2418
2419 /** Further setup required for opening an MDB environment
2420  */
2421 static int
2422 mdb_env_open2(MDB_env *env, unsigned int flags)
2423 {
2424         int i, newenv = 0;
2425         MDB_meta meta;
2426         MDB_page *p;
2427
2428         env->me_flags = flags;
2429
2430         memset(&meta, 0, sizeof(meta));
2431
2432         if ((i = mdb_env_read_header(env, &meta)) != 0) {
2433                 if (i != ENOENT)
2434                         return i;
2435                 DPUTS("new mdbenv");
2436                 newenv = 1;
2437         }
2438
2439         if (!env->me_mapsize) {
2440                 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2441         }
2442
2443 #ifdef _WIN32
2444         {
2445                 HANDLE mh;
2446                 LONG sizelo, sizehi;
2447                 sizelo = env->me_mapsize & 0xffffffff;
2448                 sizehi = env->me_mapsize >> 16;         /* pointless on WIN32, only needed on W64 */
2449                 sizehi >>= 16;
2450                 /* Windows won't create mappings for zero length files.
2451                  * Just allocate the maxsize right now.
2452                  */
2453                 if (newenv) {
2454                         SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2455                         if (!SetEndOfFile(env->me_fd))
2456                                 return ErrCode();
2457                         SetFilePointer(env->me_fd, 0, NULL, 0);
2458                 }
2459                 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
2460                         sizehi, sizelo, NULL);
2461                 if (!mh)
2462                         return ErrCode();
2463                 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
2464                         meta.mm_address);
2465                 CloseHandle(mh);
2466                 if (!env->me_map)
2467                         return ErrCode();
2468         }
2469 #else
2470         i = MAP_SHARED;
2471         if (meta.mm_address && (flags & MDB_FIXEDMAP))
2472                 i |= MAP_FIXED;
2473         env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
2474                 env->me_fd, 0);
2475         if (env->me_map == MAP_FAILED) {
2476                 env->me_map = NULL;
2477                 return ErrCode();
2478         }
2479 #endif
2480
2481         if (newenv) {
2482                 meta.mm_mapsize = env->me_mapsize;
2483                 if (flags & MDB_FIXEDMAP)
2484                         meta.mm_address = env->me_map;
2485                 i = mdb_env_init_meta(env, &meta);
2486                 if (i != MDB_SUCCESS) {
2487                         munmap(env->me_map, env->me_mapsize);
2488                         return i;
2489                 }
2490         }
2491         env->me_psize = meta.mm_psize;
2492
2493         env->me_maxpg = env->me_mapsize / env->me_psize;
2494
2495         p = (MDB_page *)env->me_map;
2496         env->me_metas[0] = METADATA(p);
2497         env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2498
2499 #if MDB_DEBUG
2500         {
2501                 int toggle = mdb_env_pick_meta(env);
2502                 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
2503
2504                 DPRINTF("opened database version %u, pagesize %u",
2505                         env->me_metas[0]->mm_version, env->me_psize);
2506                 DPRINTF("using meta page %d",  toggle);
2507                 DPRINTF("depth: %u",           db->md_depth);
2508                 DPRINTF("entries: %zu",        db->md_entries);
2509                 DPRINTF("branch pages: %zu",   db->md_branch_pages);
2510                 DPRINTF("leaf pages: %zu",     db->md_leaf_pages);
2511                 DPRINTF("overflow pages: %zu", db->md_overflow_pages);
2512                 DPRINTF("root: %zu",           db->md_root);
2513         }
2514 #endif
2515
2516         return MDB_SUCCESS;
2517 }
2518
2519
2520 /** Release a reader thread's slot in the reader lock table.
2521  *      This function is called automatically when a thread exits.
2522  * @param[in] ptr This points to the slot in the reader lock table.
2523  */
2524 static void
2525 mdb_env_reader_dest(void *ptr)
2526 {
2527         MDB_reader *reader = ptr;
2528
2529         reader->mr_txnid = 0;
2530         reader->mr_pid = 0;
2531         reader->mr_tid = 0;
2532 }
2533
2534 #ifdef _WIN32
2535 /** Junk for arranging thread-specific callbacks on Windows. This is
2536  *      necessarily platform and compiler-specific. Windows supports up
2537  *      to 1088 keys. Let's assume nobody opens more than 64 environments
2538  *      in a single process, for now. They can override this if needed.
2539  */
2540 #ifndef MAX_TLS_KEYS
2541 #define MAX_TLS_KEYS    64
2542 #endif
2543 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
2544 static int mdb_tls_nkeys;
2545
2546 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
2547 {
2548         int i;
2549         switch(reason) {
2550         case DLL_PROCESS_ATTACH: break;
2551         case DLL_THREAD_ATTACH: break;
2552         case DLL_THREAD_DETACH:
2553                 for (i=0; i<mdb_tls_nkeys; i++) {
2554                         MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
2555                         mdb_env_reader_dest(r);
2556                 }
2557                 break;
2558         case DLL_PROCESS_DETACH: break;
2559         }
2560 }
2561 #ifdef __GNUC__
2562 #ifdef _WIN64
2563 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
2564 #else
2565 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
2566 #endif
2567 #else
2568 #ifdef _WIN64
2569 /* Force some symbol references.
2570  *      _tls_used forces the linker to create the TLS directory if not already done
2571  *      mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
2572  */
2573 #pragma comment(linker, "/INCLUDE:_tls_used")
2574 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
2575 #pragma const_seg(".CRT$XLB")
2576 extern const PIMAGE_TLS_CALLBACK mdb_tls_callback;
2577 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
2578 #pragma const_seg()
2579 #else   /* WIN32 */
2580 #pragma comment(linker, "/INCLUDE:__tls_used")
2581 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
2582 #pragma data_seg(".CRT$XLB")
2583 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
2584 #pragma data_seg()
2585 #endif  /* WIN 32/64 */
2586 #endif  /* !__GNUC__ */
2587 #endif
2588
2589 /** Downgrade the exclusive lock on the region back to shared */
2590 static void
2591 mdb_env_share_locks(MDB_env *env)
2592 {
2593         int toggle = mdb_env_pick_meta(env);
2594
2595         env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2596
2597 #ifdef _WIN32
2598         {
2599                 OVERLAPPED ov;
2600                 /* First acquire a shared lock. The Unlock will
2601                  * then release the existing exclusive lock.
2602                  */
2603                 memset(&ov, 0, sizeof(ov));
2604                 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2605                 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2606         }
2607 #else
2608         {
2609                 struct flock lock_info;
2610                 /* The shared lock replaces the existing lock */
2611                 memset((void *)&lock_info, 0, sizeof(lock_info));
2612                 lock_info.l_type = F_RDLCK;
2613                 lock_info.l_whence = SEEK_SET;
2614                 lock_info.l_start = 0;
2615                 lock_info.l_len = 1;
2616                 fcntl(env->me_lfd, F_SETLK, &lock_info);
2617         }
2618 #endif
2619 }
2620 #if defined(_WIN32) || defined(__APPLE__)
2621 /*
2622  * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2623  *
2624  * @(#) $Revision: 5.1 $
2625  * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2626  * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2627  *
2628  *        http://www.isthe.com/chongo/tech/comp/fnv/index.html
2629  *
2630  ***
2631  *
2632  * Please do not copyright this code.  This code is in the public domain.
2633  *
2634  * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2635  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2636  * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2637  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2638  * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2639  * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2640  * PERFORMANCE OF THIS SOFTWARE.
2641  *
2642  * By:
2643  *      chongo <Landon Curt Noll> /\oo/\
2644  *        http://www.isthe.com/chongo/
2645  *
2646  * Share and Enjoy!     :-)
2647  */
2648
2649 typedef unsigned long long      mdb_hash_t;
2650 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2651
2652 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2653  * @param[in] str string to hash
2654  * @param[in] hval      initial value for hash
2655  * @return 64 bit hash
2656  *
2657  * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2658  *       hval arg on the first call.
2659  */
2660 static mdb_hash_t
2661 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
2662 {
2663         unsigned char *s = (unsigned char *)val->mv_data;       /* unsigned string */
2664         unsigned char *end = s + val->mv_size;
2665         /*
2666          * FNV-1a hash each octet of the string
2667          */
2668         while (s < end) {
2669                 /* xor the bottom with the current octet */
2670                 hval ^= (mdb_hash_t)*s++;
2671
2672                 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2673                 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2674                         (hval << 7) + (hval << 8) + (hval << 40);
2675         }
2676         /* return our new hash value */
2677         return hval;
2678 }
2679
2680 /** Hash the string and output the hash in hex.
2681  * @param[in] str string to hash
2682  * @param[out] hexbuf an array of 17 chars to hold the hash
2683  */
2684 static void
2685 mdb_hash_hex(MDB_val *val, char *hexbuf)
2686 {
2687         int i;
2688         mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
2689         for (i=0; i<8; i++) {
2690                 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2691                 h >>= 8;
2692         }
2693 }
2694 #endif
2695
2696 /** Open and/or initialize the lock region for the environment.
2697  * @param[in] env The MDB environment.
2698  * @param[in] lpath The pathname of the file used for the lock region.
2699  * @param[in] mode The Unix permissions for the file, if we create it.
2700  * @param[out] excl Set to true if we got an exclusive lock on the region.
2701  * @return 0 on success, non-zero on failure.
2702  */
2703 static int
2704 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2705 {
2706         int rc;
2707         off_t size, rsize;
2708
2709         *excl = 0;
2710
2711 #ifdef _WIN32
2712         if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2713                 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2714                 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2715                 rc = ErrCode();
2716                 return rc;
2717         }
2718         /* Try to get exclusive lock. If we succeed, then
2719          * nobody is using the lock region and we should initialize it.
2720          */
2721         {
2722                 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2723                         *excl = 1;
2724                 } else {
2725                         OVERLAPPED ov;
2726                         memset(&ov, 0, sizeof(ov));
2727                         if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2728                                 rc = ErrCode();
2729                                 goto fail;
2730                         }
2731                 }
2732         }
2733         size = GetFileSize(env->me_lfd, NULL);
2734
2735 #else
2736 #if !(O_CLOEXEC)
2737         {
2738                 int fdflags;
2739                 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1)
2740                         return ErrCode();
2741                 /* Lose record locks when exec*() */
2742                 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
2743                         fcntl(env->me_lfd, F_SETFD, fdflags);
2744         }
2745 #else /* O_CLOEXEC on Linux: Open file and set FD_CLOEXEC atomically */
2746         if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT|O_CLOEXEC, mode)) == -1)
2747                 return ErrCode();
2748 #endif
2749
2750         /* Try to get exclusive lock. If we succeed, then
2751          * nobody is using the lock region and we should initialize it.
2752          */
2753         {
2754                 struct flock lock_info;
2755                 memset((void *)&lock_info, 0, sizeof(lock_info));
2756                 lock_info.l_type = F_WRLCK;
2757                 lock_info.l_whence = SEEK_SET;
2758                 lock_info.l_start = 0;
2759                 lock_info.l_len = 1;
2760                 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2761                 if (rc == 0) {
2762                         *excl = 1;
2763                 } else {
2764                         lock_info.l_type = F_RDLCK;
2765                         rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2766                         if (rc) {
2767                                 rc = ErrCode();
2768                                 goto fail;
2769                         }
2770                 }
2771         }
2772         size = lseek(env->me_lfd, 0, SEEK_END);
2773 #endif
2774         rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2775         if (size < rsize && *excl) {
2776 #ifdef _WIN32
2777                 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2778                 if (!SetEndOfFile(env->me_lfd)) {
2779                         rc = ErrCode();
2780                         goto fail;
2781                 }
2782 #else
2783                 if (ftruncate(env->me_lfd, rsize) != 0) {
2784                         rc = ErrCode();
2785                         goto fail;
2786                 }
2787 #endif
2788         } else {
2789                 rsize = size;
2790                 size = rsize - sizeof(MDB_txninfo);
2791                 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2792         }
2793         {
2794 #ifdef _WIN32
2795                 HANDLE mh;
2796                 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2797                         0, 0, NULL);
2798                 if (!mh) {
2799                         rc = ErrCode();
2800                         goto fail;
2801                 }
2802                 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2803                 CloseHandle(mh);
2804                 if (!env->me_txns) {
2805                         rc = ErrCode();
2806                         goto fail;
2807                 }
2808 #else
2809                 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2810                         env->me_lfd, 0);
2811                 if (m == MAP_FAILED) {
2812                         env->me_txns = NULL;
2813                         rc = ErrCode();
2814                         goto fail;
2815                 }
2816                 env->me_txns = m;
2817 #endif
2818         }
2819         if (*excl) {
2820 #ifdef _WIN32
2821                 BY_HANDLE_FILE_INFORMATION stbuf;
2822                 struct {
2823                         DWORD volume;
2824                         DWORD nhigh;
2825                         DWORD nlow;
2826                 } idbuf;
2827                 MDB_val val;
2828                 char hexbuf[17];
2829
2830                 if (!mdb_sec_inited) {
2831                         InitializeSecurityDescriptor(&mdb_null_sd,
2832                                 SECURITY_DESCRIPTOR_REVISION);
2833                         SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2834                         mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2835                         mdb_all_sa.bInheritHandle = FALSE;
2836                         mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2837                         mdb_sec_inited = 1;
2838                 }
2839                 GetFileInformationByHandle(env->me_lfd, &stbuf);
2840                 idbuf.volume = stbuf.dwVolumeSerialNumber;
2841                 idbuf.nhigh  = stbuf.nFileIndexHigh;
2842                 idbuf.nlow   = stbuf.nFileIndexLow;
2843                 val.mv_data = &idbuf;
2844                 val.mv_size = sizeof(idbuf);
2845                 mdb_hash_hex(&val, hexbuf);
2846                 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2847                 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2848                 if (!env->me_rmutex) {
2849                         rc = ErrCode();
2850                         goto fail;
2851                 }
2852                 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2853                 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2854                 if (!env->me_wmutex) {
2855                         rc = ErrCode();
2856                         goto fail;
2857                 }
2858 #else   /* _WIN32 */
2859 #ifdef __APPLE__
2860                 struct stat stbuf;
2861                 struct {
2862                         dev_t dev;
2863                         ino_t ino;
2864                 } idbuf;
2865                 MDB_val val;
2866                 char hexbuf[17];
2867
2868                 fstat(env->me_lfd, &stbuf);
2869                 idbuf.dev = stbuf.st_dev;
2870                 idbuf.ino = stbuf.st_ino;
2871                 val.mv_data = &idbuf;
2872                 val.mv_size = sizeof(idbuf);
2873                 mdb_hash_hex(&val, hexbuf);
2874                 sprintf(env->me_txns->mti_rmname, "/MDBr%s", hexbuf);
2875                 if (sem_unlink(env->me_txns->mti_rmname)) {
2876                         rc = ErrCode();
2877                         if (rc != ENOENT && rc != EINVAL)
2878                                 goto fail;
2879                 }
2880                 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2881                 if (!env->me_rmutex) {
2882                         rc = ErrCode();
2883                         goto fail;
2884                 }
2885                 sprintf(env->me_txns->mti_wmname, "/MDBw%s", hexbuf);
2886                 if (sem_unlink(env->me_txns->mti_wmname)) {
2887                         rc = ErrCode();
2888                         if (rc != ENOENT && rc != EINVAL)
2889                                 goto fail;
2890                 }
2891                 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2892                 if (!env->me_wmutex) {
2893                         rc = ErrCode();
2894                         goto fail;
2895                 }
2896 #else   /* __APPLE__ */
2897                 pthread_mutexattr_t mattr;
2898
2899                 pthread_mutexattr_init(&mattr);
2900                 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2901                 if (rc) {
2902                         goto fail;
2903                 }
2904                 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2905                 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2906 #endif  /* __APPLE__ */
2907 #endif  /* _WIN32 */
2908                 env->me_txns->mti_version = MDB_VERSION;
2909                 env->me_txns->mti_magic = MDB_MAGIC;
2910                 env->me_txns->mti_txnid = 0;
2911                 env->me_txns->mti_numreaders = 0;
2912
2913         } else {
2914                 if (env->me_txns->mti_magic != MDB_MAGIC) {
2915                         DPUTS("lock region has invalid magic");
2916                         rc = EINVAL;
2917                         goto fail;
2918                 }
2919                 if (env->me_txns->mti_version != MDB_VERSION) {
2920                         DPRINTF("lock region is version %u, expected version %u",
2921                                 env->me_txns->mti_version, MDB_VERSION);
2922                         rc = MDB_VERSION_MISMATCH;
2923                         goto fail;
2924                 }
2925                 rc = ErrCode();
2926                 if (rc != EACCES && rc != EAGAIN) {
2927                         goto fail;
2928                 }
2929 #ifdef _WIN32
2930                 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2931                 if (!env->me_rmutex) {
2932                         rc = ErrCode();
2933                         goto fail;
2934                 }
2935                 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2936                 if (!env->me_wmutex) {
2937                         rc = ErrCode();
2938                         goto fail;
2939                 }
2940 #endif
2941 #ifdef __APPLE__
2942                 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2943                 if (!env->me_rmutex) {
2944                         rc = ErrCode();
2945                         goto fail;
2946                 }
2947                 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2948                 if (!env->me_wmutex) {
2949                         rc = ErrCode();
2950                         goto fail;
2951                 }
2952 #endif
2953         }
2954         return MDB_SUCCESS;
2955
2956 fail:
2957         close(env->me_lfd);
2958         env->me_lfd = INVALID_HANDLE_VALUE;
2959         return rc;
2960
2961 }
2962
2963         /** The name of the lock file in the DB environment */
2964 #define LOCKNAME        "/lock.mdb"
2965         /** The name of the data file in the DB environment */
2966 #define DATANAME        "/data.mdb"
2967         /** The suffix of the lock file when no subdir is used */
2968 #define LOCKSUFF        "-lock"
2969
2970 int
2971 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2972 {
2973         int             oflags, rc, len, excl;
2974         char *lpath, *dpath;
2975
2976         len = strlen(path);
2977         if (flags & MDB_NOSUBDIR) {
2978                 rc = len + sizeof(LOCKSUFF) + len + 1;
2979         } else {
2980                 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
2981         }
2982         lpath = malloc(rc);
2983         if (!lpath)
2984                 return ENOMEM;
2985         if (flags & MDB_NOSUBDIR) {
2986                 dpath = lpath + len + sizeof(LOCKSUFF);
2987                 sprintf(lpath, "%s" LOCKSUFF, path);
2988                 strcpy(dpath, path);
2989         } else {
2990                 dpath = lpath + len + sizeof(LOCKNAME);
2991                 sprintf(lpath, "%s" LOCKNAME, path);
2992                 sprintf(dpath, "%s" DATANAME, path);
2993         }
2994
2995         rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2996         if (rc)
2997                 goto leave;
2998
2999 #ifdef _WIN32
3000         if (F_ISSET(flags, MDB_RDONLY)) {
3001                 oflags = GENERIC_READ;
3002                 len = OPEN_EXISTING;
3003         } else {
3004                 oflags = GENERIC_READ|GENERIC_WRITE;
3005                 len = OPEN_ALWAYS;
3006         }
3007         mode = FILE_ATTRIBUTE_NORMAL;
3008         env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
3009                 NULL, len, mode, NULL);
3010 #else
3011         if (F_ISSET(flags, MDB_RDONLY))
3012                 oflags = O_RDONLY;
3013         else
3014                 oflags = O_RDWR | O_CREAT;
3015
3016         env->me_fd = open(dpath, oflags, mode);
3017 #endif
3018         if (env->me_fd == INVALID_HANDLE_VALUE) {
3019                 rc = ErrCode();
3020                 goto leave;
3021         }
3022
3023         if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
3024                 if (flags & (MDB_RDONLY|MDB_NOSYNC|MDB_NOMETASYNC)) {
3025                         env->me_mfd = env->me_fd;
3026                 } else {
3027                         /* synchronous fd for meta writes */
3028 #ifdef _WIN32
3029                         env->me_mfd = CreateFile(dpath, oflags,
3030                                 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
3031                                 mode | FILE_FLAG_WRITE_THROUGH, NULL);
3032 #else
3033                         env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
3034 #endif
3035                         if (env->me_mfd == INVALID_HANDLE_VALUE) {
3036                                 rc = ErrCode();
3037                                 goto leave;
3038                         }
3039                 }
3040                 env->me_path = strdup(path);
3041                 DPRINTF("opened dbenv %p", (void *) env);
3042                 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3043 #ifdef _WIN32
3044                 /* Windows TLS callbacks need help finding their TLS info. */
3045                 if (mdb_tls_nkeys < MAX_TLS_KEYS)
3046                         mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3047                 else {
3048                         rc = ENOMEM;
3049                         goto leave;
3050                 }
3051 #endif
3052                 if (excl)
3053                         mdb_env_share_locks(env);
3054                 env->me_numdbs = 2;
3055                 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3056                 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
3057                 if (!env->me_dbxs || !env->me_dbflags)
3058                         rc = ENOMEM;
3059         }
3060
3061 leave:
3062         if (rc) {
3063                 if (env->me_fd != INVALID_HANDLE_VALUE) {
3064                         close(env->me_fd);
3065                         env->me_fd = INVALID_HANDLE_VALUE;
3066                 }
3067                 if (env->me_lfd != INVALID_HANDLE_VALUE) {
3068                         close(env->me_lfd);
3069                         env->me_lfd = INVALID_HANDLE_VALUE;
3070                 }
3071         }
3072         free(lpath);
3073         return rc;
3074 }
3075
3076 void
3077 mdb_env_close(MDB_env *env)
3078 {
3079         MDB_page *dp;
3080
3081         if (env == NULL)
3082                 return;
3083
3084         VGMEMP_DESTROY(env);
3085         while (env->me_dpages) {
3086                 dp = env->me_dpages;
3087                 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
3088                 env->me_dpages = dp->mp_next;
3089                 free(dp);
3090         }
3091
3092         free(env->me_dbflags);
3093         free(env->me_dbxs);
3094         free(env->me_path);
3095
3096         pthread_key_delete(env->me_txkey);
3097 #ifdef _WIN32
3098         /* Delete our key from the global list */
3099         { int i;
3100                 for (i=0; i<mdb_tls_nkeys; i++)
3101                         if (mdb_tls_keys[i] == env->me_txkey) {
3102                                 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
3103                                 mdb_tls_nkeys--;
3104                                 break;
3105                         }
3106         }
3107 #endif
3108
3109         if (env->me_map) {
3110                 munmap(env->me_map, env->me_mapsize);
3111         }
3112         if (env->me_mfd != env->me_fd)
3113                 close(env->me_mfd);
3114         close(env->me_fd);
3115         if (env->me_txns) {
3116                 pid_t pid = getpid();
3117                 unsigned int i;
3118                 for (i=0; i<env->me_txns->mti_numreaders; i++)
3119                         if (env->me_txns->mti_readers[i].mr_pid == pid)
3120                                 env->me_txns->mti_readers[i].mr_pid = 0;
3121                 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
3122         }
3123         close(env->me_lfd);
3124         mdb_midl_free(env->me_free_pgs);
3125         free(env);
3126 }
3127
3128 /** Compare two items pointing at aligned size_t's */
3129 static int
3130 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
3131 {
3132         return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
3133                 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
3134 }
3135
3136 /** Compare two items pointing at aligned int's */
3137 static int
3138 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
3139 {
3140         return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
3141                 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
3142 }
3143
3144 /** Compare two items pointing at ints of unknown alignment.
3145  *      Nodes and keys are guaranteed to be 2-byte aligned.
3146  */
3147 static int
3148 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
3149 {
3150 #if BYTE_ORDER == LITTLE_ENDIAN
3151         unsigned short *u, *c;
3152         int x;
3153
3154         u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
3155         c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
3156         do {
3157                 x = *--u - *--c;
3158         } while(!x && u > (unsigned short *)a->mv_data);
3159         return x;
3160 #else
3161         return memcmp(a->mv_data, b->mv_data, a->mv_size);
3162 #endif
3163 }
3164
3165 /** Compare two items lexically */
3166 static int
3167 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
3168 {
3169         int diff;
3170         ssize_t len_diff;
3171         unsigned int len;
3172
3173         len = a->mv_size;
3174         len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3175         if (len_diff > 0) {
3176                 len = b->mv_size;
3177                 len_diff = 1;
3178         }
3179
3180         diff = memcmp(a->mv_data, b->mv_data, len);
3181         return diff ? diff : len_diff<0 ? -1 : len_diff;
3182 }
3183
3184 /** Compare two items in reverse byte order */
3185 static int
3186 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
3187 {
3188         const unsigned char     *p1, *p2, *p1_lim;
3189         ssize_t len_diff;
3190         int diff;
3191
3192         p1_lim = (const unsigned char *)a->mv_data;
3193         p1 = (const unsigned char *)a->mv_data + a->mv_size;
3194         p2 = (const unsigned char *)b->mv_data + b->mv_size;
3195
3196         len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3197         if (len_diff > 0) {
3198                 p1_lim += len_diff;
3199                 len_diff = 1;
3200         }
3201
3202         while (p1 > p1_lim) {
3203                 diff = *--p1 - *--p2;
3204                 if (diff)
3205                         return diff;
3206         }
3207         return len_diff<0 ? -1 : len_diff;
3208 }
3209
3210 /** Search for key within a page, using binary search.
3211  * Returns the smallest entry larger or equal to the key.
3212  * If exactp is non-null, stores whether the found entry was an exact match
3213  * in *exactp (1 or 0).
3214  * Updates the cursor index with the index of the found entry.
3215  * If no entry larger or equal to the key is found, returns NULL.
3216  */
3217 static MDB_node *
3218 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
3219 {
3220         unsigned int     i = 0, nkeys;
3221         int              low, high;
3222         int              rc = 0;
3223         MDB_page *mp = mc->mc_pg[mc->mc_top];
3224         MDB_node        *node = NULL;
3225         MDB_val  nodekey;
3226         MDB_cmp_func *cmp;
3227         DKBUF;
3228
3229         nkeys = NUMKEYS(mp);
3230
3231 #if MDB_DEBUG
3232         {
3233         pgno_t pgno;
3234         COPY_PGNO(pgno, mp->mp_pgno);
3235         DPRINTF("searching %u keys in %s %spage %zu",
3236             nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
3237             pgno);
3238         }
3239 #endif
3240
3241         assert(nkeys > 0);
3242
3243         low = IS_LEAF(mp) ? 0 : 1;
3244         high = nkeys - 1;
3245         cmp = mc->mc_dbx->md_cmp;
3246
3247         /* Branch pages have no data, so if using integer keys,
3248          * alignment is guaranteed. Use faster mdb_cmp_int.
3249          */
3250         if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
3251                 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
3252                         cmp = mdb_cmp_long;
3253                 else
3254                         cmp = mdb_cmp_int;
3255         }
3256
3257         if (IS_LEAF2(mp)) {
3258                 nodekey.mv_size = mc->mc_db->md_pad;
3259                 node = NODEPTR(mp, 0);  /* fake */
3260                 while (low <= high) {
3261                         i = (low + high) >> 1;
3262                         nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
3263                         rc = cmp(key, &nodekey);
3264                         DPRINTF("found leaf index %u [%s], rc = %i",
3265                             i, DKEY(&nodekey), rc);
3266                         if (rc == 0)
3267                                 break;
3268                         if (rc > 0)
3269                                 low = i + 1;
3270                         else
3271                                 high = i - 1;
3272                 }
3273         } else {
3274                 while (low <= high) {
3275                         i = (low + high) >> 1;
3276
3277                         node = NODEPTR(mp, i);
3278                         nodekey.mv_size = NODEKSZ(node);
3279                         nodekey.mv_data = NODEKEY(node);
3280
3281                         rc = cmp(key, &nodekey);
3282 #if MDB_DEBUG
3283                         if (IS_LEAF(mp))
3284                                 DPRINTF("found leaf index %u [%s], rc = %i",
3285                                     i, DKEY(&nodekey), rc);
3286                         else
3287                                 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
3288                                     i, DKEY(&nodekey), NODEPGNO(node), rc);
3289 #endif
3290                         if (rc == 0)
3291                                 break;
3292                         if (rc > 0)
3293                                 low = i + 1;
3294                         else
3295                                 high = i - 1;
3296                 }
3297         }
3298
3299         if (rc > 0) {   /* Found entry is less than the key. */
3300                 i++;    /* Skip to get the smallest entry larger than key. */
3301                 if (!IS_LEAF2(mp))
3302                         node = NODEPTR(mp, i);
3303         }
3304         if (exactp)
3305                 *exactp = (rc == 0);
3306         /* store the key index */
3307         mc->mc_ki[mc->mc_top] = i;
3308         if (i >= nkeys)
3309                 /* There is no entry larger or equal to the key. */
3310                 return NULL;
3311
3312         /* nodeptr is fake for LEAF2 */
3313         return node;
3314 }
3315
3316 #if 0
3317 static void
3318 mdb_cursor_adjust(MDB_cursor *mc, func)
3319 {
3320         MDB_cursor *m2;
3321
3322         for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3323                 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3324                         func(mc, m2);
3325                 }
3326         }
3327 }
3328 #endif
3329
3330 /** Pop a page off the top of the cursor's stack. */
3331 static void
3332 mdb_cursor_pop(MDB_cursor *mc)
3333 {
3334         MDB_page        *top;
3335
3336         if (mc->mc_snum) {
3337                 top = mc->mc_pg[mc->mc_top];
3338                 mc->mc_snum--;
3339                 if (mc->mc_snum)
3340                         mc->mc_top--;
3341
3342                 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3343                         mc->mc_dbi, (void *) mc);
3344         }
3345 }
3346
3347 /** Push a page onto the top of the cursor's stack. */
3348 static int
3349 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3350 {
3351         DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3352                 mc->mc_dbi, (void *) mc);
3353
3354         if (mc->mc_snum >= CURSOR_STACK) {
3355                 assert(mc->mc_snum < CURSOR_STACK);
3356                 return ENOMEM;
3357         }
3358
3359         mc->mc_top = mc->mc_snum++;
3360         mc->mc_pg[mc->mc_top] = mp;
3361         mc->mc_ki[mc->mc_top] = 0;
3362
3363         return MDB_SUCCESS;
3364 }
3365
3366 /** Find the address of the page corresponding to a given page number.
3367  * @param[in] txn the transaction for this access.
3368  * @param[in] pgno the page number for the page to retrieve.
3369  * @param[out] ret address of a pointer where the page's address will be stored.
3370  * @return 0 on success, non-zero on failure.
3371  */
3372 static int
3373 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3374 {
3375         MDB_page *p = NULL;
3376
3377         if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3378                 unsigned x;
3379                 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3380                 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3381                         p = txn->mt_u.dirty_list[x].mptr;
3382                 }
3383         }
3384         if (!p) {
3385                 if (pgno < txn->mt_next_pgno)
3386                         p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3387         }
3388         *ret = p;
3389         if (!p) {
3390                 DPRINTF("page %zu not found", pgno);
3391                 assert(p != NULL);
3392         }
3393         return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3394 }
3395
3396 /** Search for the page a given key should be in.
3397  * Pushes parent pages on the cursor stack. This function continues a
3398  * search on a cursor that has already been initialized. (Usually by
3399  * #mdb_page_search() but also by #mdb_node_move().)
3400  * @param[in,out] mc the cursor for this operation.
3401  * @param[in] key the key to search for. If NULL, search for the lowest
3402  * page. (This is used by #mdb_cursor_first().)
3403  * @param[in] flags If MDB_PS_MODIFY set, visited pages are updated with new page numbers.
3404  *   If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
3405  * @return 0 on success, non-zero on failure.
3406  */
3407 static int
3408 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3409 {
3410         MDB_page        *mp = mc->mc_pg[mc->mc_top];
3411         DKBUF;
3412         int rc;
3413
3414
3415         while (IS_BRANCH(mp)) {
3416                 MDB_node        *node;
3417                 indx_t          i;
3418
3419                 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3420                 assert(NUMKEYS(mp) > 1);
3421                 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3422
3423                 if (key == NULL)        /* Initialize cursor to first page. */
3424                         i = 0;
3425                 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
3426                                                         /* cursor to last page */
3427                         i = NUMKEYS(mp)-1;
3428                 } else {
3429                         int      exact;
3430                         node = mdb_node_search(mc, key, &exact);
3431                         if (node == NULL)
3432                                 i = NUMKEYS(mp) - 1;
3433                         else {
3434                                 i = mc->mc_ki[mc->mc_top];
3435                                 if (!exact) {
3436                                         assert(i > 0);
3437                                         i--;
3438                                 }
3439                         }
3440                 }
3441
3442                 if (key)
3443                         DPRINTF("following index %u for key [%s]",
3444                             i, DKEY(key));
3445                 assert(i < NUMKEYS(mp));
3446                 node = NODEPTR(mp, i);
3447
3448                 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3449                         return rc;
3450
3451                 mc->mc_ki[mc->mc_top] = i;
3452                 if ((rc = mdb_cursor_push(mc, mp)))
3453                         return rc;
3454
3455                 if (modify) {
3456                         if ((rc = mdb_page_touch(mc)) != 0)
3457                                 return rc;
3458                         mp = mc->mc_pg[mc->mc_top];
3459                 }
3460         }
3461
3462         if (!IS_LEAF(mp)) {
3463                 DPRINTF("internal error, index points to a %02X page!?",
3464                     mp->mp_flags);
3465                 return MDB_CORRUPTED;
3466         }
3467
3468         DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
3469             key ? DKEY(key) : NULL);
3470
3471         return MDB_SUCCESS;
3472 }
3473
3474 /** Search for the page a given key should be in.
3475  * Pushes parent pages on the cursor stack. This function just sets up
3476  * the search; it finds the root page for \b mc's database and sets this
3477  * as the root of the cursor's stack. Then #mdb_page_search_root() is
3478  * called to complete the search.
3479  * @param[in,out] mc the cursor for this operation.
3480  * @param[in] key the key to search for. If NULL, search for the lowest
3481  * page. (This is used by #mdb_cursor_first().)
3482  * @param[in] modify If true, visited pages are updated with new page numbers.
3483  * @return 0 on success, non-zero on failure.
3484  */
3485 static int
3486 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
3487 {
3488         int              rc;
3489         pgno_t           root;
3490
3491         /* Make sure the txn is still viable, then find the root from
3492          * the txn's db table.
3493          */
3494         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
3495                 DPUTS("transaction has failed, must abort");
3496                 return EINVAL;
3497         } else {
3498                 /* Make sure we're using an up-to-date root */
3499                 if (mc->mc_dbi > MAIN_DBI) {
3500                         if ((*mc->mc_dbflag & DB_STALE) ||
3501                         ((flags & MDB_PS_MODIFY) && !(*mc->mc_dbflag & DB_DIRTY))) {
3502                                 MDB_cursor mc2;
3503                                 unsigned char dbflag = 0;
3504                                 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3505                                 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, flags & MDB_PS_MODIFY);
3506                                 if (rc)
3507                                         return rc;
3508                                 if (*mc->mc_dbflag & DB_STALE) {
3509                                         MDB_val data;
3510                                         int exact = 0;
3511                                         MDB_node *leaf = mdb_node_search(&mc2,
3512                                                 &mc->mc_dbx->md_name, &exact);
3513                                         if (!exact)
3514                                                 return MDB_NOTFOUND;
3515                                         mdb_node_read(mc->mc_txn, leaf, &data);
3516                                         memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
3517                                 }
3518                                 if (flags & MDB_PS_MODIFY)
3519                                         dbflag = DB_DIRTY;
3520                                 *mc->mc_dbflag = dbflag;
3521                         }
3522                 }
3523                 root = mc->mc_db->md_root;
3524
3525                 if (root == P_INVALID) {                /* Tree is empty. */
3526                         DPUTS("tree is empty");
3527                         return MDB_NOTFOUND;
3528                 }
3529         }
3530
3531         assert(root > 1);
3532         if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
3533                 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
3534                         return rc;
3535
3536         mc->mc_snum = 1;
3537         mc->mc_top = 0;
3538
3539         DPRINTF("db %u root page %zu has flags 0x%X",
3540                 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
3541
3542         if (flags & MDB_PS_MODIFY) {
3543                 if ((rc = mdb_page_touch(mc)))
3544                         return rc;
3545         }
3546
3547         if (flags & MDB_PS_ROOTONLY)
3548                 return MDB_SUCCESS;
3549
3550         return mdb_page_search_root(mc, key, flags);
3551 }
3552
3553 /** Return the data associated with a given node.
3554  * @param[in] txn The transaction for this operation.
3555  * @param[in] leaf The node being read.
3556  * @param[out] data Updated to point to the node's data.
3557  * @return 0 on success, non-zero on failure.
3558  */
3559 static int
3560 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
3561 {
3562         MDB_page        *omp;           /* overflow page */
3563         pgno_t           pgno;
3564         int rc;
3565
3566         if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3567                 data->mv_size = NODEDSZ(leaf);
3568                 data->mv_data = NODEDATA(leaf);
3569                 return MDB_SUCCESS;
3570         }
3571
3572         /* Read overflow data.
3573          */
3574         data->mv_size = NODEDSZ(leaf);
3575         memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
3576         if ((rc = mdb_page_get(txn, pgno, &omp))) {
3577                 DPRINTF("read overflow page %zu failed", pgno);
3578                 return rc;
3579         }
3580         data->mv_data = METADATA(omp);
3581
3582         return MDB_SUCCESS;
3583 }
3584
3585 int
3586 mdb_get(MDB_txn *txn, MDB_dbi dbi,
3587     MDB_val *key, MDB_val *data)
3588 {
3589         MDB_cursor      mc;
3590         MDB_xcursor     mx;
3591         int exact = 0;
3592         DKBUF;
3593
3594         assert(key);
3595         assert(data);
3596         DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
3597
3598         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3599                 return EINVAL;
3600
3601         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3602                 return EINVAL;
3603         }
3604
3605         mdb_cursor_init(&mc, txn, dbi, &mx);
3606         return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
3607 }
3608
3609 /** Find a sibling for a page.
3610  * Replaces the page at the top of the cursor's stack with the
3611  * specified sibling, if one exists.
3612  * @param[in] mc The cursor for this operation.
3613  * @param[in] move_right Non-zero if the right sibling is requested,
3614  * otherwise the left sibling.
3615  * @return 0 on success, non-zero on failure.
3616  */
3617 static int
3618 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
3619 {
3620         int              rc;
3621         MDB_node        *indx;
3622         MDB_page        *mp;
3623
3624         if (mc->mc_snum < 2) {
3625                 return MDB_NOTFOUND;            /* root has no siblings */
3626         }
3627
3628         mdb_cursor_pop(mc);
3629         DPRINTF("parent page is page %zu, index %u",
3630                 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
3631
3632         if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
3633                        : (mc->mc_ki[mc->mc_top] == 0)) {
3634                 DPRINTF("no more keys left, moving to %s sibling",
3635                     move_right ? "right" : "left");
3636                 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
3637                         return rc;
3638         } else {
3639                 if (move_right)
3640                         mc->mc_ki[mc->mc_top]++;
3641                 else
3642                         mc->mc_ki[mc->mc_top]--;
3643                 DPRINTF("just moving to %s index key %u",
3644                     move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3645         }
3646         assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3647
3648         indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3649         if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3650                 return rc;;
3651
3652         mdb_cursor_push(mc, mp);
3653
3654         return MDB_SUCCESS;
3655 }
3656
3657 /** Move the cursor to the next data item. */
3658 static int
3659 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3660 {
3661         MDB_page        *mp;
3662         MDB_node        *leaf;
3663         int rc;
3664
3665         if (mc->mc_flags & C_EOF) {
3666                 return MDB_NOTFOUND;
3667         }
3668
3669         assert(mc->mc_flags & C_INITIALIZED);
3670
3671         mp = mc->mc_pg[mc->mc_top];
3672
3673         if (mc->mc_db->md_flags & MDB_DUPSORT) {
3674                 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3675                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3676                         if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3677                                 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3678                                 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3679                                         return rc;
3680                         }
3681                 } else {
3682                         mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3683                         if (op == MDB_NEXT_DUP)
3684                                 return MDB_NOTFOUND;
3685                 }
3686         }
3687
3688         DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3689
3690         if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3691                 DPUTS("=====> move to next sibling page");
3692                 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3693                         mc->mc_flags |= C_EOF;
3694                         mc->mc_flags &= ~C_INITIALIZED;
3695                         return MDB_NOTFOUND;
3696                 }
3697                 mp = mc->mc_pg[mc->mc_top];
3698                 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3699         } else
3700                 mc->mc_ki[mc->mc_top]++;
3701
3702         DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3703             mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3704
3705         if (IS_LEAF2(mp)) {
3706                 key->mv_size = mc->mc_db->md_pad;
3707                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3708                 return MDB_SUCCESS;
3709         }
3710
3711         assert(IS_LEAF(mp));
3712         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3713
3714         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3715                 mdb_xcursor_init1(mc, leaf);
3716         }
3717         if (data) {
3718                 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3719                         return rc;
3720
3721                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3722                         rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3723                         if (rc != MDB_SUCCESS)
3724                                 return rc;
3725                 }
3726         }
3727
3728         MDB_SET_KEY(leaf, key);
3729         return MDB_SUCCESS;
3730 }
3731
3732 /** Move the cursor to the previous data item. */
3733 static int
3734 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3735 {
3736         MDB_page        *mp;
3737         MDB_node        *leaf;
3738         int rc;
3739
3740         assert(mc->mc_flags & C_INITIALIZED);
3741
3742         mp = mc->mc_pg[mc->mc_top];
3743
3744         if (mc->mc_db->md_flags & MDB_DUPSORT) {
3745                 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3746                 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3747                         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3748                                 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3749                                 if (op != MDB_PREV || rc == MDB_SUCCESS)
3750                                         return rc;
3751                         } else {
3752                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3753                                 if (op == MDB_PREV_DUP)
3754                                         return MDB_NOTFOUND;
3755                         }
3756                 }
3757         }
3758
3759         DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3760
3761         if (mc->mc_ki[mc->mc_top] == 0)  {
3762                 DPUTS("=====> move to prev sibling page");
3763                 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3764                         mc->mc_flags &= ~C_INITIALIZED;
3765                         return MDB_NOTFOUND;
3766                 }
3767                 mp = mc->mc_pg[mc->mc_top];
3768                 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3769                 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3770         } else
3771                 mc->mc_ki[mc->mc_top]--;
3772
3773         mc->mc_flags &= ~C_EOF;
3774
3775         DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3776             mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3777
3778         if (IS_LEAF2(mp)) {
3779                 key->mv_size = mc->mc_db->md_pad;
3780                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3781                 return MDB_SUCCESS;
3782         }
3783
3784         assert(IS_LEAF(mp));
3785         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3786
3787         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3788                 mdb_xcursor_init1(mc, leaf);
3789         }
3790         if (data) {
3791                 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3792                         return rc;
3793
3794                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3795                         rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3796                         if (rc != MDB_SUCCESS)
3797                                 return rc;
3798                 }
3799         }
3800
3801         MDB_SET_KEY(leaf, key);
3802         return MDB_SUCCESS;
3803 }
3804
3805 /** Set the cursor on a specific data item. */
3806 static int
3807 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3808     MDB_cursor_op op, int *exactp)
3809 {
3810         int              rc;
3811         MDB_page        *mp;
3812         MDB_node        *leaf;
3813         DKBUF;
3814
3815         assert(mc);
3816         assert(key);
3817         assert(key->mv_size > 0);
3818
3819         /* See if we're already on the right page */
3820         if (mc->mc_flags & C_INITIALIZED) {
3821                 MDB_val nodekey;
3822
3823                 mp = mc->mc_pg[mc->mc_top];
3824                 if (!NUMKEYS(mp)) {
3825                         mc->mc_ki[mc->mc_top] = 0;
3826                         return MDB_NOTFOUND;
3827                 }
3828                 if (mp->mp_flags & P_LEAF2) {
3829                         nodekey.mv_size = mc->mc_db->md_pad;
3830                         nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3831                 } else {
3832                         leaf = NODEPTR(mp, 0);
3833                         MDB_SET_KEY(leaf, &nodekey);
3834                 }
3835                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3836                 if (rc == 0) {
3837                         /* Probably happens rarely, but first node on the page
3838                          * was the one we wanted.
3839                          */
3840                         mc->mc_ki[mc->mc_top] = 0;
3841                         if (exactp)
3842                                 *exactp = 1;
3843                         goto set1;
3844                 }
3845                 if (rc > 0) {
3846                         unsigned int i;
3847                         unsigned int nkeys = NUMKEYS(mp);
3848                         if (nkeys > 1) {
3849                                 if (mp->mp_flags & P_LEAF2) {
3850                                         nodekey.mv_data = LEAF2KEY(mp,
3851                                                  nkeys-1, nodekey.mv_size);
3852                                 } else {
3853                                         leaf = NODEPTR(mp, nkeys-1);
3854                                         MDB_SET_KEY(leaf, &nodekey);
3855                                 }
3856                                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3857                                 if (rc == 0) {
3858                                         /* last node was the one we wanted */
3859                                         mc->mc_ki[mc->mc_top] = nkeys-1;
3860                                         if (exactp)
3861                                                 *exactp = 1;
3862                                         goto set1;
3863                                 }
3864                                 if (rc < 0) {
3865                                         if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
3866                                                 /* This is definitely the right page, skip search_page */
3867                                                 if (mp->mp_flags & P_LEAF2) {
3868                                                         nodekey.mv_data = LEAF2KEY(mp,
3869                                                                  mc->mc_ki[mc->mc_top], nodekey.mv_size);
3870                                                 } else {
3871                                                         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3872                                                         MDB_SET_KEY(leaf, &nodekey);
3873                                                 }
3874                                                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3875                                                 if (rc == 0) {
3876                                                         /* current node was the one we wanted */
3877                                                         if (exactp)
3878                                                                 *exactp = 1;
3879                                                         goto set1;
3880                                                 }
3881                                         }
3882                                         rc = 0;
3883                                         goto set2;
3884                                 }
3885                         }
3886                         /* If any parents have right-sibs, search.
3887                          * Otherwise, there's nothing further.
3888                          */
3889                         for (i=0; i<mc->mc_top; i++)
3890                                 if (mc->mc_ki[i] <
3891                                         NUMKEYS(mc->mc_pg[i])-1)
3892                                         break;
3893                         if (i == mc->mc_top) {
3894                                 /* There are no other pages */
3895                                 mc->mc_ki[mc->mc_top] = nkeys;
3896                                 return MDB_NOTFOUND;
3897                         }
3898                 }
3899                 if (!mc->mc_top) {
3900                         /* There are no other pages */
3901                         mc->mc_ki[mc->mc_top] = 0;
3902                         return MDB_NOTFOUND;
3903                 }
3904         }
3905
3906         rc = mdb_page_search(mc, key, 0);
3907         if (rc != MDB_SUCCESS)
3908                 return rc;
3909
3910         mp = mc->mc_pg[mc->mc_top];
3911         assert(IS_LEAF(mp));
3912
3913 set2:
3914         leaf = mdb_node_search(mc, key, exactp);
3915         if (exactp != NULL && !*exactp) {
3916                 /* MDB_SET specified and not an exact match. */
3917                 return MDB_NOTFOUND;
3918         }
3919
3920         if (leaf == NULL) {
3921                 DPUTS("===> inexact leaf not found, goto sibling");
3922                 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3923                         return rc;              /* no entries matched */
3924                 mp = mc->mc_pg[mc->mc_top];
3925                 assert(IS_LEAF(mp));
3926                 leaf = NODEPTR(mp, 0);
3927         }
3928
3929 set1:
3930         mc->mc_flags |= C_INITIALIZED;
3931         mc->mc_flags &= ~C_EOF;
3932
3933         if (IS_LEAF2(mp)) {
3934                 key->mv_size = mc->mc_db->md_pad;
3935                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3936                 return MDB_SUCCESS;
3937         }
3938
3939         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3940                 mdb_xcursor_init1(mc, leaf);
3941         }
3942         if (data) {
3943                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3944                         if (op == MDB_SET || op == MDB_SET_RANGE) {
3945                                 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3946                         } else {
3947                                 int ex2, *ex2p;
3948                                 if (op == MDB_GET_BOTH) {
3949                                         ex2p = &ex2;
3950                                         ex2 = 0;
3951                                 } else {
3952                                         ex2p = NULL;
3953                                 }
3954                                 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3955                                 if (rc != MDB_SUCCESS)
3956                                         return rc;
3957                         }
3958                 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3959                         MDB_val d2;
3960                         if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3961                                 return rc;
3962                         rc = mc->mc_dbx->md_dcmp(data, &d2);
3963                         if (rc) {
3964                                 if (op == MDB_GET_BOTH || rc > 0)
3965                                         return MDB_NOTFOUND;
3966                         }
3967
3968                 } else {
3969                         if (mc->mc_xcursor)
3970                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3971                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3972                                 return rc;
3973                 }
3974         }
3975
3976         /* The key already matches in all other cases */
3977         if (op == MDB_SET_RANGE)
3978                 MDB_SET_KEY(leaf, key);
3979         DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3980
3981         return rc;
3982 }
3983
3984 /** Move the cursor to the first item in the database. */
3985 static int
3986 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3987 {
3988         int              rc;
3989         MDB_node        *leaf;
3990
3991         if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3992                 rc = mdb_page_search(mc, NULL, 0);
3993                 if (rc != MDB_SUCCESS)
3994                         return rc;
3995         }
3996         assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3997
3998         leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3999         mc->mc_flags |= C_INITIALIZED;
4000         mc->mc_flags &= ~C_EOF;
4001
4002         mc->mc_ki[mc->mc_top] = 0;
4003
4004         if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4005                 key->mv_size = mc->mc_db->md_pad;
4006                 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
4007                 return MDB_SUCCESS;
4008         }
4009
4010         if (data) {
4011                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4012                         mdb_xcursor_init1(mc, leaf);
4013                         rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4014                         if (rc)
4015                                 return rc;
4016                 } else {
4017                         if (mc->mc_xcursor)
4018                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4019                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4020                                 return rc;
4021                 }
4022         }
4023         MDB_SET_KEY(leaf, key);
4024         return MDB_SUCCESS;
4025 }
4026
4027 /** Move the cursor to the last item in the database. */
4028 static int
4029 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
4030 {
4031         int              rc;
4032         MDB_node        *leaf;
4033
4034         if (!(mc->mc_flags & C_EOF)) {
4035
4036         if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
4037                 MDB_val lkey;
4038
4039                 lkey.mv_size = MAXKEYSIZE+1;
4040                 lkey.mv_data = NULL;
4041                 rc = mdb_page_search(mc, &lkey, 0);
4042                 if (rc != MDB_SUCCESS)
4043                         return rc;
4044         }
4045         assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
4046
4047         mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
4048         mc->mc_flags |= C_INITIALIZED|C_EOF;
4049         }
4050         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4051
4052         if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4053                 key->mv_size = mc->mc_db->md_pad;
4054                 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
4055                 return MDB_SUCCESS;
4056         }
4057
4058         if (data) {
4059                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4060                         mdb_xcursor_init1(mc, leaf);
4061                         rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4062                         if (rc)
4063                                 return rc;
4064                 } else {
4065                         if (mc->mc_xcursor)
4066                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4067                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4068                                 return rc;
4069                 }
4070         }
4071
4072         MDB_SET_KEY(leaf, key);
4073         return MDB_SUCCESS;
4074 }
4075
4076 int
4077 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4078     MDB_cursor_op op)
4079 {
4080         int              rc;
4081         int              exact = 0;
4082
4083         assert(mc);
4084
4085         switch (op) {
4086         case MDB_GET_BOTH:
4087         case MDB_GET_BOTH_RANGE:
4088                 if (data == NULL || mc->mc_xcursor == NULL) {
4089                         rc = EINVAL;
4090                         break;
4091                 }
4092                 /* FALLTHRU */
4093         case MDB_SET:
4094         case MDB_SET_RANGE:
4095                 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4096                         rc = EINVAL;
4097                 } else if (op == MDB_SET_RANGE)
4098                         rc = mdb_cursor_set(mc, key, data, op, NULL);
4099                 else
4100                         rc = mdb_cursor_set(mc, key, data, op, &exact);
4101                 break;
4102         case MDB_GET_MULTIPLE:
4103                 if (data == NULL ||
4104                         !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
4105                         !(mc->mc_flags & C_INITIALIZED)) {
4106                         rc = EINVAL;
4107                         break;
4108                 }
4109                 rc = MDB_SUCCESS;
4110                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
4111                         (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
4112                         break;
4113                 goto fetchm;
4114         case MDB_NEXT_MULTIPLE:
4115                 if (data == NULL ||
4116                         !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
4117                         rc = EINVAL;
4118                         break;
4119                 }
4120                 if (!(mc->mc_flags & C_INITIALIZED))
4121                         rc = mdb_cursor_first(mc, key, data);
4122                 else
4123                         rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
4124                 if (rc == MDB_SUCCESS) {
4125                         if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
4126                                 MDB_cursor *mx;
4127 fetchm:
4128                                 mx = &mc->mc_xcursor->mx_cursor;
4129                                 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
4130                                         mx->mc_db->md_pad;
4131                                 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
4132                                 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
4133                         } else {
4134                                 rc = MDB_NOTFOUND;
4135                         }
4136                 }
4137                 break;
4138         case MDB_NEXT:
4139         case MDB_NEXT_DUP:
4140         case MDB_NEXT_NODUP:
4141                 if (!(mc->mc_flags & C_INITIALIZED))
4142                         rc = mdb_cursor_first(mc, key, data);
4143                 else
4144                         rc = mdb_cursor_next(mc, key, data, op);
4145                 break;
4146         case MDB_PREV:
4147         case MDB_PREV_DUP:
4148         case MDB_PREV_NODUP:
4149                 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF)) {
4150                         rc = mdb_cursor_last(mc, key, data);
4151                         mc->mc_flags &= ~C_EOF;
4152                 } else
4153                         rc = mdb_cursor_prev(mc, key, data, op);
4154                 break;
4155         case MDB_FIRST:
4156                 rc = mdb_cursor_first(mc, key, data);
4157                 break;
4158         case MDB_FIRST_DUP:
4159                 if (data == NULL ||
4160                         !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4161                         !(mc->mc_flags & C_INITIALIZED) ||
4162                         !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4163                         rc = EINVAL;
4164                         break;
4165                 }
4166                 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4167                 break;
4168         case MDB_LAST:
4169                 rc = mdb_cursor_last(mc, key, data);
4170                 break;
4171         case MDB_LAST_DUP:
4172                 if (data == NULL ||
4173                         !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4174                         !(mc->mc_flags & C_INITIALIZED) ||
4175                         !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4176                         rc = EINVAL;
4177                         break;
4178                 }
4179                 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4180                 break;
4181         default:
4182                 DPRINTF("unhandled/unimplemented cursor operation %u", op);
4183                 rc = EINVAL;
4184                 break;
4185         }
4186
4187         return rc;
4188 }
4189
4190 /** Touch all the pages in the cursor stack.
4191  *      Makes sure all the pages are writable, before attempting a write operation.
4192  * @param[in] mc The cursor to operate on.
4193  */
4194 static int
4195 mdb_cursor_touch(MDB_cursor *mc)
4196 {
4197         int rc;
4198
4199         if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
4200                 MDB_cursor mc2;
4201                 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4202                 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
4203                 if (rc)
4204                          return rc;
4205                 *mc->mc_dbflag = DB_DIRTY;
4206         }
4207         for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
4208                 rc = mdb_page_touch(mc);
4209                 if (rc)
4210                         return rc;
4211         }
4212         mc->mc_top = mc->mc_snum-1;
4213         return MDB_SUCCESS;
4214 }
4215
4216 int
4217 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4218     unsigned int flags)
4219 {
4220         MDB_node        *leaf = NULL;
4221         MDB_val xdata, *rdata, dkey;
4222         MDB_page        *fp;
4223         MDB_db dummy;
4224         int do_sub = 0, insert = 0;
4225         unsigned int mcount = 0;
4226         size_t nsize;
4227         int rc, rc2;
4228         MDB_pagebuf pbuf;
4229         char dbuf[MAXKEYSIZE+1];
4230         unsigned int nflags;
4231         DKBUF;
4232
4233         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4234                 return EACCES;
4235
4236         DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
4237                 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
4238
4239         dkey.mv_size = 0;
4240
4241         if (flags == MDB_CURRENT) {
4242                 if (!(mc->mc_flags & C_INITIALIZED))
4243                         return EINVAL;
4244                 rc = MDB_SUCCESS;
4245         } else if (mc->mc_db->md_root == P_INVALID) {
4246                 MDB_page *np;
4247                 /* new database, write a root leaf page */
4248                 DPUTS("allocating new root leaf page");
4249                 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
4250                         return ENOMEM;
4251                 }
4252                 mc->mc_snum = 0;
4253                 mdb_cursor_push(mc, np);
4254                 mc->mc_db->md_root = np->mp_pgno;
4255                 mc->mc_db->md_depth++;
4256                 *mc->mc_dbflag = DB_DIRTY;
4257                 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
4258                         == MDB_DUPFIXED)
4259                         np->mp_flags |= P_LEAF2;
4260                 mc->mc_flags |= C_INITIALIZED;
4261                 rc = MDB_NOTFOUND;
4262                 goto top;
4263         } else {
4264                 int exact = 0;
4265                 MDB_val d2;
4266                 if (flags & MDB_APPEND) {
4267                         MDB_val k2;
4268                         rc = mdb_cursor_last(mc, &k2, &d2);
4269                         if (rc == 0) {
4270                                 rc = mc->mc_dbx->md_cmp(key, &k2);
4271                                 if (rc > 0) {
4272                                         rc = MDB_NOTFOUND;
4273                                         mc->mc_ki[mc->mc_top]++;
4274                                 } else {
4275                                         rc = 0;
4276                                 }
4277                         }
4278                 } else {
4279                 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
4280                 }
4281                 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
4282                         DPRINTF("duplicate key [%s]", DKEY(key));
4283                         *data = d2;
4284                         return MDB_KEYEXIST;
4285                 }
4286                 if (rc && rc != MDB_NOTFOUND)
4287                         return rc;
4288         }
4289
4290         /* Cursor is positioned, now make sure all pages are writable */
4291         rc2 = mdb_cursor_touch(mc);
4292         if (rc2)
4293                 return rc2;
4294
4295 top:
4296         /* The key already exists */
4297         if (rc == MDB_SUCCESS) {
4298                 /* there's only a key anyway, so this is a no-op */
4299                 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4300                         unsigned int ksize = mc->mc_db->md_pad;
4301                         if (key->mv_size != ksize)
4302                                 return EINVAL;
4303                         if (flags == MDB_CURRENT) {
4304                                 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
4305                                 memcpy(ptr, key->mv_data, ksize);
4306                         }
4307                         return MDB_SUCCESS;
4308                 }
4309
4310                 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4311
4312                 /* DB has dups? */
4313                 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
4314                         /* Was a single item before, must convert now */
4315 more:
4316                         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4317                                 /* Just overwrite the current item */
4318                                 if (flags == MDB_CURRENT)
4319                                         goto current;
4320
4321                                 dkey.mv_size = NODEDSZ(leaf);
4322                                 dkey.mv_data = NODEDATA(leaf);
4323 #if UINT_MAX < SIZE_MAX
4324                                 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
4325 #ifdef MISALIGNED_OK
4326                                         mc->mc_dbx->md_dcmp = mdb_cmp_long;
4327 #else
4328                                         mc->mc_dbx->md_dcmp = mdb_cmp_cint;
4329 #endif
4330 #endif
4331                                 /* if data matches, ignore it */
4332                                 if (!mc->mc_dbx->md_dcmp(data, &dkey))
4333                                         return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
4334
4335                                 /* create a fake page for the dup items */
4336                                 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
4337                                 dkey.mv_data = dbuf;
4338                                 fp = (MDB_page *)&pbuf;
4339                                 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4340                                 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
4341                                 fp->mp_lower = PAGEHDRSZ;
4342                                 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
4343                                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4344                                         fp->mp_flags |= P_LEAF2;
4345                                         fp->mp_pad = data->mv_size;
4346                                         fp->mp_upper += 2 * data->mv_size;      /* leave space for 2 more */
4347                                 } else {
4348                                         fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
4349                                                 (dkey.mv_size & 1) + (data->mv_size & 1);
4350                                 }
4351                                 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4352                                 do_sub = 1;
4353                                 rdata = &xdata;
4354                                 xdata.mv_size = fp->mp_upper;
4355                                 xdata.mv_data = fp;
4356                                 flags |= F_DUPDATA;
4357                                 goto new_sub;
4358                         }
4359                         if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4360                                 /* See if we need to convert from fake page to subDB */
4361                                 MDB_page *mp;
4362                                 unsigned int offset;
4363                                 unsigned int i;
4364
4365                                 fp = NODEDATA(leaf);
4366                                 if (flags == MDB_CURRENT) {
4367 reuse:
4368                                         fp->mp_flags |= P_DIRTY;
4369                                         COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
4370                                         mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
4371                                         flags |= F_DUPDATA;
4372                                         goto put_sub;
4373                                 }
4374                                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4375                                         offset = fp->mp_pad;
4376                                         if (SIZELEFT(fp) >= offset)
4377                                                 goto reuse;
4378                                         offset *= 4;    /* space for 4 more */
4379                                 } else {
4380                                         offset = NODESIZE + sizeof(indx_t) + data->mv_size;
4381                                 }
4382                                 offset += offset & 1;
4383                                 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
4384                                         offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
4385                                                 MDB_MINKEYS) {
4386                                         /* yes, convert it */
4387                                         dummy.md_flags = 0;
4388                                         if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4389                                                 dummy.md_pad = fp->mp_pad;
4390                                                 dummy.md_flags = MDB_DUPFIXED;
4391                                                 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4392                                                         dummy.md_flags |= MDB_INTEGERKEY;
4393                                         }
4394                                         dummy.md_depth = 1;
4395                                         dummy.md_branch_pages = 0;
4396                                         dummy.md_leaf_pages = 1;
4397                                         dummy.md_overflow_pages = 0;
4398                                         dummy.md_entries = NUMKEYS(fp);
4399                                         rdata = &xdata;
4400                                         xdata.mv_size = sizeof(MDB_db);
4401                                         xdata.mv_data = &dummy;
4402                                         mp = mdb_page_alloc(mc, 1);
4403                                         if (!mp)
4404                                                 return ENOMEM;
4405                                         offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4406                                         flags |= F_DUPDATA|F_SUBDATA;
4407                                         dummy.md_root = mp->mp_pgno;
4408                                 } else {
4409                                         /* no, just grow it */
4410                                         rdata = &xdata;
4411                                         xdata.mv_size = NODEDSZ(leaf) + offset;
4412                                         xdata.mv_data = &pbuf;
4413                                         mp = (MDB_page *)&pbuf;
4414                                         mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4415                                         flags |= F_DUPDATA;
4416                                 }
4417                                 mp->mp_flags = fp->mp_flags | P_DIRTY;
4418                                 mp->mp_pad   = fp->mp_pad;
4419                                 mp->mp_lower = fp->mp_lower;
4420                                 mp->mp_upper = fp->mp_upper + offset;
4421                                 if (IS_LEAF2(fp)) {
4422                                         memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4423                                 } else {
4424                                         nsize = NODEDSZ(leaf) - fp->mp_upper;
4425                                         memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
4426                                         for (i=0; i<NUMKEYS(fp); i++)
4427                                                 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
4428                                 }
4429                                 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4430                                 do_sub = 1;
4431                                 goto new_sub;
4432                         }
4433                         /* data is on sub-DB, just store it */
4434                         flags |= F_DUPDATA|F_SUBDATA;
4435                         goto put_sub;
4436                 }
4437 current:
4438                 /* overflow page overwrites need special handling */
4439                 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4440                         MDB_page *omp;
4441                         pgno_t pg;
4442                         int ovpages, dpages;
4443
4444                         ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
4445                         dpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4446                         memcpy(&pg, NODEDATA(leaf), sizeof(pg));
4447                         mdb_page_get(mc->mc_txn, pg, &omp);
4448                         /* Is the ov page writable and large enough? */
4449                         if ((omp->mp_flags & P_DIRTY) && ovpages >= dpages) {
4450                                 /* yes, overwrite it. Note in this case we don't
4451                                  * bother to try shrinking the node if the new data
4452                                  * is smaller than the overflow threshold.
4453                                  */
4454                                 if (F_ISSET(flags, MDB_RESERVE))
4455                                         data->mv_data = METADATA(omp);
4456                                 else
4457                                         memcpy(METADATA(omp), data->mv_data, data->mv_size);
4458                                 goto done;
4459                         } else {
4460                                 /* no, free ovpages */
4461                                 int i;
4462                                 mc->mc_db->md_overflow_pages -= ovpages;
4463                                 for (i=0; i<ovpages; i++) {
4464                                         DPRINTF("freed ov page %zu", pg);
4465                                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
4466                                         pg++;
4467                                 }
4468                         }
4469                 } else if (NODEDSZ(leaf) == data->mv_size) {
4470                         /* same size, just replace it. Note that we could
4471                          * also reuse this node if the new data is smaller,
4472                          * but instead we opt to shrink the node in that case.
4473                          */
4474                         if (F_ISSET(flags, MDB_RESERVE))
4475                                 data->mv_data = NODEDATA(leaf);
4476                         else
4477                                 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4478                         goto done;
4479                 }
4480                 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4481                 mc->mc_db->md_entries--;
4482         } else {
4483                 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
4484                 insert = 1;
4485         }
4486
4487         rdata = data;
4488
4489 new_sub:
4490         nflags = flags & NODE_ADD_FLAGS;
4491         nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
4492         if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
4493                 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
4494                         nflags &= ~MDB_APPEND;
4495                 if (!insert)
4496                         nflags |= MDB_SPLIT_REPLACE;
4497                 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
4498         } else {
4499                 /* There is room already in this leaf page. */
4500                 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
4501                 if (rc == 0 && !do_sub && insert) {
4502                         /* Adjust other cursors pointing to mp */
4503                         MDB_cursor *m2, *m3;
4504                         MDB_dbi dbi = mc->mc_dbi;
4505                         unsigned i = mc->mc_top;
4506                         MDB_page *mp = mc->mc_pg[i];
4507
4508                         if (mc->mc_flags & C_SUB)
4509                                 dbi--;
4510
4511                         for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4512                                 if (mc->mc_flags & C_SUB)
4513                                         m3 = &m2->mc_xcursor->mx_cursor;
4514                                 else
4515                                         m3 = m2;
4516                                 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
4517                                 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
4518                                         m3->mc_ki[i]++;
4519                                 }
4520                         }
4521                 }
4522         }
4523
4524         if (rc != MDB_SUCCESS)
4525                 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4526         else {
4527                 /* Now store the actual data in the child DB. Note that we're
4528                  * storing the user data in the keys field, so there are strict
4529                  * size limits on dupdata. The actual data fields of the child
4530                  * DB are all zero size.
4531                  */
4532                 if (do_sub) {
4533                         int xflags;
4534 put_sub:
4535                         xdata.mv_size = 0;
4536                         xdata.mv_data = "";
4537                         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4538                         if (flags & MDB_CURRENT) {
4539                                 xflags = MDB_CURRENT;
4540                         } else {
4541                                 mdb_xcursor_init1(mc, leaf);
4542                                 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
4543                         }
4544                         /* converted, write the original data first */
4545                         if (dkey.mv_size) {
4546                                 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
4547                                 if (rc)
4548                                         return rc;
4549                                 {
4550                                         /* Adjust other cursors pointing to mp */
4551                                         MDB_cursor *m2;
4552                                         unsigned i = mc->mc_top;
4553                                         MDB_page *mp = mc->mc_pg[i];
4554
4555                                         for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4556                                                 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
4557                                                 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
4558                                                         mdb_xcursor_init1(m2, leaf);
4559                                                 }
4560                                         }
4561                                 }
4562                         }
4563                         if (flags & MDB_APPENDDUP)
4564                                 xflags |= MDB_APPEND;
4565                         rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
4566                         if (flags & F_SUBDATA) {
4567                                 void *db = NODEDATA(leaf);
4568                                 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4569                         }
4570                 }
4571                 /* sub-writes might have failed so check rc again.
4572                  * Don't increment count if we just replaced an existing item.
4573                  */
4574                 if (!rc && !(flags & MDB_CURRENT))
4575                         mc->mc_db->md_entries++;
4576                 if (flags & MDB_MULTIPLE) {
4577                         mcount++;
4578                         if (mcount < data[1].mv_size) {
4579                                 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
4580                                 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4581                                 goto more;
4582                         }
4583                 }
4584         }
4585 done:
4586         return rc;
4587 }
4588
4589 int
4590 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
4591 {
4592         MDB_node        *leaf;
4593         int rc;
4594
4595         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4596                 return EACCES;
4597
4598         if (!mc->mc_flags & C_INITIALIZED)
4599                 return EINVAL;
4600
4601         rc = mdb_cursor_touch(mc);
4602         if (rc)
4603                 return rc;
4604
4605         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4606
4607         if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4608                 if (flags != MDB_NODUPDATA) {
4609                         if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4610                                 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
4611                         }
4612                         rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
4613                         /* If sub-DB still has entries, we're done */
4614                         if (mc->mc_xcursor->mx_db.md_entries) {
4615                                 if (leaf->mn_flags & F_SUBDATA) {
4616                                         /* update subDB info */
4617                                         void *db = NODEDATA(leaf);
4618                                         memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4619                                 } else {
4620                                         /* shrink fake page */
4621                                         mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4622                                 }
4623                                 mc->mc_db->md_entries--;
4624                                 return rc;
4625                         }
4626                         /* otherwise fall thru and delete the sub-DB */
4627                 }
4628
4629                 if (leaf->mn_flags & F_SUBDATA) {
4630                         /* add all the child DB's pages to the free list */
4631                         rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
4632                         if (rc == MDB_SUCCESS) {
4633                                 mc->mc_db->md_entries -=
4634                                         mc->mc_xcursor->mx_db.md_entries;
4635                         }
4636                 }
4637         }
4638
4639         return mdb_cursor_del0(mc, leaf);
4640 }
4641
4642 /** Allocate and initialize new pages for a database.
4643  * @param[in] mc a cursor on the database being added to.
4644  * @param[in] flags flags defining what type of page is being allocated.
4645  * @param[in] num the number of pages to allocate. This is usually 1,
4646  * unless allocating overflow pages for a large record.
4647  * @return Address of a page, or NULL on failure.
4648  */
4649 static MDB_page *
4650 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
4651 {
4652         MDB_page        *np;
4653
4654         if ((np = mdb_page_alloc(mc, num)) == NULL)
4655                 return NULL;
4656         DPRINTF("allocated new mpage %zu, page size %u",
4657             np->mp_pgno, mc->mc_txn->mt_env->me_psize);
4658         np->mp_flags = flags | P_DIRTY;
4659         np->mp_lower = PAGEHDRSZ;
4660         np->mp_upper = mc->mc_txn->mt_env->me_psize;
4661
4662         if (IS_BRANCH(np))
4663                 mc->mc_db->md_branch_pages++;
4664         else if (IS_LEAF(np))
4665                 mc->mc_db->md_leaf_pages++;
4666         else if (IS_OVERFLOW(np)) {
4667                 mc->mc_db->md_overflow_pages += num;
4668                 np->mp_pages = num;
4669         }
4670
4671         return np;
4672 }
4673
4674 /** Calculate the size of a leaf node.
4675  * The size depends on the environment's page size; if a data item
4676  * is too large it will be put onto an overflow page and the node
4677  * size will only include the key and not the data. Sizes are always
4678  * rounded up to an even number of bytes, to guarantee 2-byte alignment
4679  * of the #MDB_node headers.
4680  * @param[in] env The environment handle.
4681  * @param[in] key The key for the node.
4682  * @param[in] data The data for the node.
4683  * @return The number of bytes needed to store the node.
4684  */
4685 static size_t
4686 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
4687 {
4688         size_t           sz;
4689
4690         sz = LEAFSIZE(key, data);
4691         if (sz >= env->me_psize / MDB_MINKEYS) {
4692                 /* put on overflow page */
4693                 sz -= data->mv_size - sizeof(pgno_t);
4694         }
4695         sz += sz & 1;
4696
4697         return sz + sizeof(indx_t);
4698 }
4699
4700 /** Calculate the size of a branch node.
4701  * The size should depend on the environment's page size but since
4702  * we currently don't support spilling large keys onto overflow
4703  * pages, it's simply the size of the #MDB_node header plus the
4704  * size of the key. Sizes are always rounded up to an even number
4705  * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
4706  * @param[in] env The environment handle.
4707  * @param[in] key The key for the node.
4708  * @return The number of bytes needed to store the node.
4709  */
4710 static size_t
4711 mdb_branch_size(MDB_env *env, MDB_val *key)
4712 {
4713         size_t           sz;
4714
4715         sz = INDXSIZE(key);
4716         if (sz >= env->me_psize / MDB_MINKEYS) {
4717                 /* put on overflow page */
4718                 /* not implemented */
4719                 /* sz -= key->size - sizeof(pgno_t); */
4720         }
4721
4722         return sz + sizeof(indx_t);
4723 }
4724
4725 /** Add a node to the page pointed to by the cursor.
4726  * @param[in] mc The cursor for this operation.
4727  * @param[in] indx The index on the page where the new node should be added.
4728  * @param[in] key The key for the new node.
4729  * @param[in] data The data for the new node, if any.
4730  * @param[in] pgno The page number, if adding a branch node.
4731  * @param[in] flags Flags for the node.
4732  * @return 0 on success, non-zero on failure. Possible errors are:
4733  * <ul>
4734  *      <li>ENOMEM - failed to allocate overflow pages for the node.
4735  *      <li>ENOSPC - there is insufficient room in the page. This error
4736  *      should never happen since all callers already calculate the
4737  *      page's free space before calling this function.
4738  * </ul>
4739  */
4740 static int
4741 mdb_node_add(MDB_cursor *mc, indx_t indx,
4742     MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
4743 {
4744         unsigned int     i;
4745         size_t           node_size = NODESIZE;
4746         indx_t           ofs;
4747         MDB_node        *node;
4748         MDB_page        *mp = mc->mc_pg[mc->mc_top];
4749         MDB_page        *ofp = NULL;            /* overflow page */
4750         DKBUF;
4751
4752         assert(mp->mp_upper >= mp->mp_lower);
4753
4754         DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
4755             IS_LEAF(mp) ? "leaf" : "branch",
4756                 IS_SUBP(mp) ? "sub-" : "",
4757             mp->mp_pgno, indx, data ? data->mv_size : 0,
4758                 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
4759
4760         if (IS_LEAF2(mp)) {
4761                 /* Move higher keys up one slot. */
4762                 int ksize = mc->mc_db->md_pad, dif;
4763                 char *ptr = LEAF2KEY(mp, indx, ksize);
4764                 dif = NUMKEYS(mp) - indx;
4765                 if (dif > 0)
4766                         memmove(ptr+ksize, ptr, dif*ksize);
4767                 /* insert new key */
4768                 memcpy(ptr, key->mv_data, ksize);
4769
4770                 /* Just using these for counting */
4771                 mp->mp_lower += sizeof(indx_t);
4772                 mp->mp_upper -= ksize - sizeof(indx_t);
4773                 return MDB_SUCCESS;
4774         }
4775
4776         if (key != NULL)
4777                 node_size += key->mv_size;
4778
4779         if (IS_LEAF(mp)) {
4780                 assert(data);
4781                 if (F_ISSET(flags, F_BIGDATA)) {
4782                         /* Data already on overflow page. */
4783                         node_size += sizeof(pgno_t);
4784                 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4785                         int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4786                         /* Put data on overflow page. */
4787                         DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
4788                             data->mv_size, node_size+data->mv_size);
4789                         node_size += sizeof(pgno_t);
4790                         if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
4791                                 return ENOMEM;
4792                         DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4793                         flags |= F_BIGDATA;
4794                 } else {
4795                         node_size += data->mv_size;
4796                 }
4797         }
4798         node_size += node_size & 1;
4799
4800         if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4801                 DPRINTF("not enough room in page %zu, got %u ptrs",
4802                     mp->mp_pgno, NUMKEYS(mp));
4803                 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4804                     mp->mp_upper - mp->mp_lower);
4805                 DPRINTF("node size = %zu", node_size);
4806                 return ENOSPC;
4807         }
4808
4809         /* Move higher pointers up one slot. */
4810         for (i = NUMKEYS(mp); i > indx; i--)
4811                 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4812
4813         /* Adjust free space offsets. */
4814         ofs = mp->mp_upper - node_size;
4815         assert(ofs >= mp->mp_lower + sizeof(indx_t));
4816         mp->mp_ptrs[indx] = ofs;
4817         mp->mp_upper = ofs;
4818         mp->mp_lower += sizeof(indx_t);
4819
4820         /* Write the node data. */
4821         node = NODEPTR(mp, indx);
4822         node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4823         node->mn_flags = flags;
4824         if (IS_LEAF(mp))
4825                 SETDSZ(node,data->mv_size);
4826         else
4827                 SETPGNO(node,pgno);
4828
4829         if (key)
4830                 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4831
4832         if (IS_LEAF(mp)) {
4833                 assert(key);
4834                 if (ofp == NULL) {
4835                         if (F_ISSET(flags, F_BIGDATA))
4836                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
4837                                     sizeof(pgno_t));
4838                         else if (F_ISSET(flags, MDB_RESERVE))
4839                                 data->mv_data = node->mn_data + key->mv_size;
4840                         else
4841                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
4842                                     data->mv_size);
4843                 } else {
4844                         memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4845                             sizeof(pgno_t));
4846                         if (F_ISSET(flags, MDB_RESERVE))
4847                                 data->mv_data = METADATA(ofp);
4848                         else
4849                                 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4850                 }
4851         }
4852
4853         return MDB_SUCCESS;
4854 }
4855
4856 /** Delete the specified node from a page.
4857  * @param[in] mp The page to operate on.
4858  * @param[in] indx The index of the node to delete.
4859  * @param[in] ksize The size of a node. Only used if the page is
4860  * part of a #MDB_DUPFIXED database.
4861  */
4862 static void
4863 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4864 {
4865         unsigned int     sz;
4866         indx_t           i, j, numkeys, ptr;
4867         MDB_node        *node;
4868         char            *base;
4869
4870 #if MDB_DEBUG
4871         {
4872         pgno_t pgno;
4873         COPY_PGNO(pgno, mp->mp_pgno);
4874         DPRINTF("delete node %u on %s page %zu", indx,
4875             IS_LEAF(mp) ? "leaf" : "branch", pgno);
4876         }
4877 #endif
4878         assert(indx < NUMKEYS(mp));
4879
4880         if (IS_LEAF2(mp)) {
4881                 int x = NUMKEYS(mp) - 1 - indx;
4882                 base = LEAF2KEY(mp, indx, ksize);
4883                 if (x)
4884                         memmove(base, base + ksize, x * ksize);
4885                 mp->mp_lower -= sizeof(indx_t);
4886                 mp->mp_upper += ksize - sizeof(indx_t);
4887                 return;
4888         }
4889
4890         node = NODEPTR(mp, indx);
4891         sz = NODESIZE + node->mn_ksize;
4892         if (IS_LEAF(mp)) {
4893                 if (F_ISSET(node->mn_flags, F_BIGDATA))
4894                         sz += sizeof(pgno_t);
4895                 else
4896                         sz += NODEDSZ(node);
4897         }
4898         sz += sz & 1;
4899
4900         ptr = mp->mp_ptrs[indx];
4901         numkeys = NUMKEYS(mp);
4902         for (i = j = 0; i < numkeys; i++) {
4903                 if (i != indx) {
4904                         mp->mp_ptrs[j] = mp->mp_ptrs[i];
4905                         if (mp->mp_ptrs[i] < ptr)
4906                                 mp->mp_ptrs[j] += sz;
4907                         j++;
4908                 }
4909         }
4910
4911         base = (char *)mp + mp->mp_upper;
4912         memmove(base + sz, base, ptr - mp->mp_upper);
4913
4914         mp->mp_lower -= sizeof(indx_t);
4915         mp->mp_upper += sz;
4916 }
4917
4918 /** Compact the main page after deleting a node on a subpage.
4919  * @param[in] mp The main page to operate on.
4920  * @param[in] indx The index of the subpage on the main page.
4921  */
4922 static void
4923 mdb_node_shrink(MDB_page *mp, indx_t indx)
4924 {
4925         MDB_node *node;
4926         MDB_page *sp, *xp;
4927         char *base;
4928         int osize, nsize;
4929         int delta;
4930         indx_t           i, numkeys, ptr;
4931
4932         node = NODEPTR(mp, indx);
4933         sp = (MDB_page *)NODEDATA(node);
4934         osize = NODEDSZ(node);
4935
4936         delta = sp->mp_upper - sp->mp_lower;
4937         SETDSZ(node, osize - delta);
4938         xp = (MDB_page *)((char *)sp + delta);
4939
4940         /* shift subpage upward */
4941         if (IS_LEAF2(sp)) {
4942                 nsize = NUMKEYS(sp) * sp->mp_pad;
4943                 memmove(METADATA(xp), METADATA(sp), nsize);
4944         } else {
4945                 int i;
4946                 nsize = osize - sp->mp_upper;
4947                 numkeys = NUMKEYS(sp);
4948                 for (i=numkeys-1; i>=0; i--)
4949                         xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4950         }
4951         xp->mp_upper = sp->mp_lower;
4952         xp->mp_lower = sp->mp_lower;
4953         xp->mp_flags = sp->mp_flags;
4954         xp->mp_pad = sp->mp_pad;
4955         COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
4956
4957         /* shift lower nodes upward */
4958         ptr = mp->mp_ptrs[indx];
4959         numkeys = NUMKEYS(mp);
4960         for (i = 0; i < numkeys; i++) {
4961                 if (mp->mp_ptrs[i] <= ptr)
4962                         mp->mp_ptrs[i] += delta;
4963         }
4964
4965         base = (char *)mp + mp->mp_upper;
4966         memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4967         mp->mp_upper += delta;
4968 }
4969
4970 /** Initial setup of a sorted-dups cursor.
4971  * Sorted duplicates are implemented as a sub-database for the given key.
4972  * The duplicate data items are actually keys of the sub-database.
4973  * Operations on the duplicate data items are performed using a sub-cursor
4974  * initialized when the sub-database is first accessed. This function does
4975  * the preliminary setup of the sub-cursor, filling in the fields that
4976  * depend only on the parent DB.
4977  * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4978  */
4979 static void
4980 mdb_xcursor_init0(MDB_cursor *mc)
4981 {
4982         MDB_xcursor *mx = mc->mc_xcursor;
4983
4984         mx->mx_cursor.mc_xcursor = NULL;
4985         mx->mx_cursor.mc_txn = mc->mc_txn;
4986         mx->mx_cursor.mc_db = &mx->mx_db;
4987         mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4988         mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4989         mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
4990         mx->mx_cursor.mc_snum = 0;
4991         mx->mx_cursor.mc_top = 0;
4992         mx->mx_cursor.mc_flags = C_SUB;
4993         mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4994         mx->mx_dbx.md_dcmp = NULL;
4995         mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4996 }
4997
4998 /** Final setup of a sorted-dups cursor.
4999  *      Sets up the fields that depend on the data from the main cursor.
5000  * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
5001  * @param[in] node The data containing the #MDB_db record for the
5002  * sorted-dup database.
5003  */
5004 static void
5005 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
5006 {
5007         MDB_xcursor *mx = mc->mc_xcursor;
5008
5009         if (node->mn_flags & F_SUBDATA) {
5010                 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
5011                 mx->mx_cursor.mc_pg[0] = 0;
5012                 mx->mx_cursor.mc_snum = 0;
5013                 mx->mx_cursor.mc_flags = C_SUB;
5014         } else {
5015                 MDB_page *fp = NODEDATA(node);
5016                 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
5017                 mx->mx_db.md_flags = 0;
5018                 mx->mx_db.md_depth = 1;
5019                 mx->mx_db.md_branch_pages = 0;
5020                 mx->mx_db.md_leaf_pages = 1;
5021                 mx->mx_db.md_overflow_pages = 0;
5022                 mx->mx_db.md_entries = NUMKEYS(fp);
5023                 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
5024                 mx->mx_cursor.mc_snum = 1;
5025                 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
5026                 mx->mx_cursor.mc_top = 0;
5027                 mx->mx_cursor.mc_pg[0] = fp;
5028                 mx->mx_cursor.mc_ki[0] = 0;
5029                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5030                         mx->mx_db.md_flags = MDB_DUPFIXED;
5031                         mx->mx_db.md_pad = fp->mp_pad;
5032                         if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5033                                 mx->mx_db.md_flags |= MDB_INTEGERKEY;
5034                 }
5035         }
5036         DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
5037                 mx->mx_db.md_root);
5038         mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
5039                 DB_DIRTY : 0;
5040         mx->mx_dbx.md_name.mv_data = NODEKEY(node);
5041         mx->mx_dbx.md_name.mv_size = node->mn_ksize;
5042 #if UINT_MAX < SIZE_MAX
5043         if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
5044 #ifdef MISALIGNED_OK
5045                 mx->mx_dbx.md_cmp = mdb_cmp_long;
5046 #else
5047                 mx->mx_dbx.md_cmp = mdb_cmp_cint;
5048 #endif
5049 #endif
5050 }
5051
5052 /** Initialize a cursor for a given transaction and database. */
5053 static void
5054 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
5055 {
5056         mc->mc_orig = NULL;
5057         mc->mc_dbi = dbi;
5058         mc->mc_txn = txn;
5059         mc->mc_db = &txn->mt_dbs[dbi];
5060         mc->mc_dbx = &txn->mt_dbxs[dbi];
5061         mc->mc_dbflag = &txn->mt_dbflags[dbi];
5062         mc->mc_snum = 0;
5063         mc->mc_top = 0;
5064         mc->mc_pg[0] = 0;
5065         mc->mc_flags = 0;
5066         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5067                 assert(mx != NULL);
5068                 mc->mc_xcursor = mx;
5069                 mdb_xcursor_init0(mc);
5070         } else {
5071                 mc->mc_xcursor = NULL;
5072         }
5073         if (*mc->mc_dbflag & DB_STALE) {
5074                 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
5075         }
5076 }
5077
5078 int
5079 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
5080 {
5081         MDB_cursor      *mc;
5082         MDB_xcursor     *mx = NULL;
5083         size_t size = sizeof(MDB_cursor);
5084
5085         if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs)
5086                 return EINVAL;
5087
5088         /* Allow read access to the freelist */
5089         if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
5090                 return EINVAL;
5091
5092         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
5093                 size += sizeof(MDB_xcursor);
5094
5095         if ((mc = malloc(size)) != NULL) {
5096                 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5097                         mx = (MDB_xcursor *)(mc + 1);
5098                 }
5099                 mdb_cursor_init(mc, txn, dbi, mx);
5100                 if (txn->mt_cursors) {
5101                         mc->mc_next = txn->mt_cursors[dbi];
5102                         txn->mt_cursors[dbi] = mc;
5103                 }
5104                 mc->mc_flags |= C_ALLOCD;
5105         } else {
5106                 return ENOMEM;
5107         }
5108
5109         *ret = mc;
5110
5111         return MDB_SUCCESS;
5112 }
5113
5114 /* Return the count of duplicate data items for the current key */
5115 int
5116 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
5117 {
5118         MDB_node        *leaf;
5119
5120         if (mc == NULL || countp == NULL)
5121                 return EINVAL;
5122
5123         if (!(mc->mc_db->md_flags & MDB_DUPSORT))
5124                 return EINVAL;
5125
5126         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5127         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5128                 *countp = 1;
5129         } else {
5130                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
5131                         return EINVAL;
5132
5133                 *countp = mc->mc_xcursor->mx_db.md_entries;
5134         }
5135         return MDB_SUCCESS;
5136 }
5137
5138 void
5139 mdb_cursor_close(MDB_cursor *mc)
5140 {
5141         if (mc != NULL) {
5142                 /* remove from txn, if tracked */
5143                 if (mc->mc_txn->mt_cursors) {
5144                         MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
5145                         while (*prev && *prev != mc) prev = &(*prev)->mc_next;
5146                         if (*prev == mc)
5147                                 *prev = mc->mc_next;
5148                 }
5149                 if (mc->mc_flags & C_ALLOCD)
5150                         free(mc);
5151         }
5152 }
5153
5154 MDB_txn *
5155 mdb_cursor_txn(MDB_cursor *mc)
5156 {
5157         if (!mc) return NULL;
5158         return mc->mc_txn;
5159 }
5160
5161 MDB_dbi
5162 mdb_cursor_dbi(MDB_cursor *mc)
5163 {
5164         if (!mc) return 0;
5165         return mc->mc_dbi;
5166 }
5167
5168 /** Replace the key for a node with a new key.
5169  * @param[in] mp The page containing the node to operate on.
5170  * @param[in] indx The index of the node to operate on.
5171  * @param[in] key The new key to use.
5172  * @return 0 on success, non-zero on failure.
5173  */
5174 static int
5175 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
5176 {
5177         MDB_node                *node;
5178         char                    *base;
5179         size_t                   len;
5180         int                      delta, delta0;
5181         indx_t                   ptr, i, numkeys;
5182         DKBUF;
5183
5184         node = NODEPTR(mp, indx);
5185         ptr = mp->mp_ptrs[indx];
5186 #if MDB_DEBUG
5187         {
5188                 MDB_val k2;
5189                 char kbuf2[(MAXKEYSIZE*2+1)];
5190                 k2.mv_data = NODEKEY(node);
5191                 k2.mv_size = node->mn_ksize;
5192                 DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %zu",
5193                         indx, ptr,
5194                         mdb_dkey(&k2, kbuf2),
5195                         DKEY(key),
5196                         mp->mp_pgno);
5197         }
5198 #endif
5199
5200         delta0 = delta = key->mv_size - node->mn_ksize;
5201
5202         /* Must be 2-byte aligned. If new key is
5203          * shorter by 1, the shift will be skipped.
5204          */
5205         delta += (delta & 1);
5206         if (delta) {
5207                 if (delta > 0 && SIZELEFT(mp) < delta) {
5208                         DPRINTF("OUCH! Not enough room, delta = %d", delta);
5209                         return ENOSPC;
5210                 }
5211
5212                 numkeys = NUMKEYS(mp);
5213                 for (i = 0; i < numkeys; i++) {
5214                         if (mp->mp_ptrs[i] <= ptr)
5215                                 mp->mp_ptrs[i] -= delta;
5216                 }
5217
5218                 base = (char *)mp + mp->mp_upper;
5219                 len = ptr - mp->mp_upper + NODESIZE;
5220                 memmove(base - delta, base, len);
5221                 mp->mp_upper -= delta;
5222
5223                 node = NODEPTR(mp, indx);
5224         }
5225
5226         /* But even if no shift was needed, update ksize */
5227         if (delta0)
5228                 node->mn_ksize = key->mv_size;
5229
5230         if (key->mv_size)
5231                 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
5232
5233         return MDB_SUCCESS;
5234 }
5235
5236 /** Move a node from csrc to cdst.
5237  */
5238 static int
5239 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
5240 {
5241         int                      rc;
5242         MDB_node                *srcnode;
5243         MDB_val          key, data;
5244         pgno_t  srcpg;
5245         unsigned short flags;
5246
5247         DKBUF;
5248
5249         /* Mark src and dst as dirty. */
5250         if ((rc = mdb_page_touch(csrc)) ||
5251             (rc = mdb_page_touch(cdst)))
5252                 return rc;
5253
5254         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5255                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);        /* fake */
5256                 key.mv_size = csrc->mc_db->md_pad;
5257                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5258                 data.mv_size = 0;
5259                 data.mv_data = NULL;
5260                 srcpg = 0;
5261                 flags = 0;
5262         } else {
5263                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
5264                 assert(!((long)srcnode&1));
5265                 srcpg = NODEPGNO(srcnode);
5266                 flags = srcnode->mn_flags;
5267                 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5268                         unsigned int snum = csrc->mc_snum;
5269                         MDB_node *s2;
5270                         /* must find the lowest key below src */
5271                         mdb_page_search_root(csrc, NULL, 0);
5272                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5273                                 key.mv_size = csrc->mc_db->md_pad;
5274                                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5275                         } else {
5276                                 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5277                                 key.mv_size = NODEKSZ(s2);
5278                                 key.mv_data = NODEKEY(s2);
5279                         }
5280                         csrc->mc_snum = snum--;
5281                         csrc->mc_top = snum;
5282                 } else {
5283                         key.mv_size = NODEKSZ(srcnode);
5284                         key.mv_data = NODEKEY(srcnode);
5285                 }
5286                 data.mv_size = NODEDSZ(srcnode);
5287                 data.mv_data = NODEDATA(srcnode);
5288         }
5289         if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
5290                 unsigned int snum = cdst->mc_snum;
5291                 MDB_node *s2;
5292                 MDB_val bkey;
5293                 /* must find the lowest key below dst */
5294                 mdb_page_search_root(cdst, NULL, 0);
5295                 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
5296                         bkey.mv_size = cdst->mc_db->md_pad;
5297                         bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
5298                 } else {
5299                         s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5300                         bkey.mv_size = NODEKSZ(s2);
5301                         bkey.mv_data = NODEKEY(s2);
5302                 }
5303                 cdst->mc_snum = snum--;
5304                 cdst->mc_top = snum;
5305                 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &bkey);
5306         }
5307
5308         DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
5309             IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
5310             csrc->mc_ki[csrc->mc_top],
5311                 DKEY(&key),
5312             csrc->mc_pg[csrc->mc_top]->mp_pgno,
5313             cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
5314
5315         /* Add the node to the destination page.
5316          */
5317         rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
5318         if (rc != MDB_SUCCESS)
5319                 return rc;
5320
5321         /* Delete the node from the source page.
5322          */
5323         mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5324
5325         {
5326                 /* Adjust other cursors pointing to mp */
5327                 MDB_cursor *m2, *m3;
5328                 MDB_dbi dbi = csrc->mc_dbi;
5329                 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
5330
5331                 if (csrc->mc_flags & C_SUB)
5332                         dbi--;
5333
5334                 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5335                         if (m2 == csrc) continue;
5336                         if (csrc->mc_flags & C_SUB)
5337                                 m3 = &m2->mc_xcursor->mx_cursor;
5338                         else
5339                                 m3 = m2;
5340                         if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
5341                                 csrc->mc_ki[csrc->mc_top]) {
5342                                 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
5343                                 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
5344                         }
5345                 }
5346         }
5347
5348         /* Update the parent separators.
5349          */
5350         if (csrc->mc_ki[csrc->mc_top] == 0) {
5351                 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
5352                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5353                                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5354                         } else {
5355                                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5356                                 key.mv_size = NODEKSZ(srcnode);
5357                                 key.mv_data = NODEKEY(srcnode);
5358                         }
5359                         DPRINTF("update separator for source page %zu to [%s]",
5360                                 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
5361                         if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
5362                                 &key)) != MDB_SUCCESS)
5363                                 return rc;
5364                 }
5365                 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5366                         MDB_val  nullkey;
5367                         nullkey.mv_size = 0;
5368                         rc = mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey);
5369                         assert(rc == MDB_SUCCESS);
5370                 }
5371         }
5372
5373         if (cdst->mc_ki[cdst->mc_top] == 0) {
5374                 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
5375                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5376                                 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
5377                         } else {
5378                                 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5379                                 key.mv_size = NODEKSZ(srcnode);
5380                                 key.mv_data = NODEKEY(srcnode);
5381                         }
5382                         DPRINTF("update separator for destination page %zu to [%s]",
5383                                 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
5384                         if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
5385                                 &key)) != MDB_SUCCESS)
5386                                 return rc;
5387                 }
5388                 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
5389                         MDB_val  nullkey;
5390                         nullkey.mv_size = 0;
5391                         rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey);
5392                         assert(rc == MDB_SUCCESS);
5393                 }
5394         }
5395
5396         return MDB_SUCCESS;
5397 }
5398
5399 /** Merge one page into another.
5400  *  The nodes from the page pointed to by \b csrc will
5401  *      be copied to the page pointed to by \b cdst and then
5402  *      the \b csrc page will be freed.
5403  * @param[in] csrc Cursor pointing to the source page.
5404  * @param[in] cdst Cursor pointing to the destination page.
5405  */
5406 static int
5407 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
5408 {
5409         int                      rc;
5410         indx_t                   i, j;
5411         MDB_node                *srcnode;
5412         MDB_val          key, data;
5413         unsigned        nkeys;
5414
5415         DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
5416                 cdst->mc_pg[cdst->mc_top]->mp_pgno);
5417
5418         assert(csrc->mc_snum > 1);      /* can't merge root page */
5419         assert(cdst->mc_snum > 1);
5420
5421         /* Mark dst as dirty. */
5422         if ((rc = mdb_page_touch(cdst)))
5423                 return rc;
5424
5425         /* Move all nodes from src to dst.
5426          */
5427         j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
5428         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5429                 key.mv_size = csrc->mc_db->md_pad;
5430                 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
5431                 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5432                         rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
5433                         if (rc != MDB_SUCCESS)
5434                                 return rc;
5435                         key.mv_data = (char *)key.mv_data + key.mv_size;
5436                 }
5437         } else {
5438                 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5439                         srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
5440                         if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5441                                 unsigned int snum = csrc->mc_snum;
5442                                 MDB_node *s2;
5443                                 /* must find the lowest key below src */
5444                                 mdb_page_search_root(csrc, NULL, 0);
5445                                 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5446                                         key.mv_size = csrc->mc_db->md_pad;
5447                                         key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5448                                 } else {
5449                                         s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5450                                         key.mv_size = NODEKSZ(s2);
5451                                         key.mv_data = NODEKEY(s2);
5452                                 }
5453                                 csrc->mc_snum = snum--;
5454                                 csrc->mc_top = snum;
5455                         } else {
5456                                 key.mv_size = srcnode->mn_ksize;
5457                                 key.mv_data = NODEKEY(srcnode);
5458                         }
5459
5460                         data.mv_size = NODEDSZ(srcnode);
5461                         data.mv_data = NODEDATA(srcnode);
5462                         rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
5463                         if (rc != MDB_SUCCESS)
5464                                 return rc;
5465                 }
5466         }
5467
5468         DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
5469             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);
5470
5471         /* Unlink the src page from parent and add to free list.
5472          */
5473         mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
5474         if (csrc->mc_ki[csrc->mc_top-1] == 0) {
5475                 key.mv_size = 0;
5476                 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
5477                         return rc;
5478         }
5479
5480         mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
5481         if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
5482                 csrc->mc_db->md_leaf_pages--;
5483         else
5484                 csrc->mc_db->md_branch_pages--;
5485         {
5486                 /* Adjust other cursors pointing to mp */
5487                 MDB_cursor *m2, *m3;
5488                 MDB_dbi dbi = csrc->mc_dbi;
5489                 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
5490
5491                 if (csrc->mc_flags & C_SUB)
5492                         dbi--;
5493
5494                 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5495                         if (csrc->mc_flags & C_SUB)
5496                                 m3 = &m2->mc_xcursor->mx_cursor;
5497                         else
5498                                 m3 = m2;
5499                         if (m3 == csrc) continue;
5500                         if (m3->mc_snum < csrc->mc_snum) continue;
5501                         if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
5502                                 m3->mc_pg[csrc->mc_top] = mp;
5503                                 m3->mc_ki[csrc->mc_top] += nkeys;
5504                         }
5505                 }
5506         }
5507         mdb_cursor_pop(csrc);
5508
5509         return mdb_rebalance(csrc);
5510 }
5511
5512 /** Copy the contents of a cursor.
5513  * @param[in] csrc The cursor to copy from.
5514  * @param[out] cdst The cursor to copy to.
5515  */
5516 static void
5517 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
5518 {
5519         unsigned int i;
5520
5521         cdst->mc_txn = csrc->mc_txn;
5522         cdst->mc_dbi = csrc->mc_dbi;
5523         cdst->mc_db  = csrc->mc_db;
5524         cdst->mc_dbx = csrc->mc_dbx;
5525         cdst->mc_snum = csrc->mc_snum;
5526         cdst->mc_top = csrc->mc_top;
5527         cdst->mc_flags = csrc->mc_flags;
5528
5529         for (i=0; i<csrc->mc_snum; i++) {
5530                 cdst->mc_pg[i] = csrc->mc_pg[i];
5531                 cdst->mc_ki[i] = csrc->mc_ki[i];
5532         }
5533 }
5534
5535 /** Rebalance the tree after a delete operation.
5536  * @param[in] mc Cursor pointing to the page where rebalancing
5537  * should begin.
5538  * @return 0 on success, non-zero on failure.
5539  */
5540 static int
5541 mdb_rebalance(MDB_cursor *mc)
5542 {
5543         MDB_node        *node;
5544         int rc;
5545         unsigned int ptop;
5546         MDB_cursor      mn;
5547
5548 #if MDB_DEBUG
5549         {
5550         pgno_t pgno;
5551         COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5552         DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
5553             IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
5554             pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
5555         }
5556 #endif
5557
5558         if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
5559 #if MDB_DEBUG
5560                 pgno_t pgno;
5561                 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5562                 DPRINTF("no need to rebalance page %zu, above fill threshold",
5563                     pgno);
5564 #endif
5565                 return MDB_SUCCESS;
5566         }
5567
5568         if (mc->mc_snum < 2) {
5569                 MDB_page *mp = mc->mc_pg[0];
5570                 if (NUMKEYS(mp) == 0) {
5571                         DPUTS("tree is completely empty");
5572                         mc->mc_db->md_root = P_INVALID;
5573                         mc->mc_db->md_depth = 0;
5574                         mc->mc_db->md_leaf_pages = 0;
5575                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5576                         mc->mc_snum = 0;
5577                         mc->mc_top = 0;
5578                         {
5579                                 /* Adjust other cursors pointing to mp */
5580                                 MDB_cursor *m2, *m3;
5581                                 MDB_dbi dbi = mc->mc_dbi;
5582
5583                                 if (mc->mc_flags & C_SUB)
5584                                         dbi--;
5585
5586                                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5587                                         if (m2 == mc) continue;
5588                                         if (mc->mc_flags & C_SUB)
5589                                                 m3 = &m2->mc_xcursor->mx_cursor;
5590                                         else
5591                                                 m3 = m2;
5592                                         if (m3->mc_snum < mc->mc_snum) continue;
5593                                         if (m3->mc_pg[0] == mp) {
5594                                                 m3->mc_snum = 0;
5595                                                 m3->mc_top = 0;
5596                                         }
5597                                 }
5598                         }
5599                 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
5600                         DPUTS("collapsing root page!");
5601                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5602                         mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
5603                         if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
5604                                 &mc->mc_pg[0])))
5605                                 return rc;
5606                         mc->mc_db->md_depth--;
5607                         mc->mc_db->md_branch_pages--;
5608                         {
5609                                 /* Adjust other cursors pointing to mp */
5610                                 MDB_cursor *m2, *m3;
5611                                 MDB_dbi dbi = mc->mc_dbi;
5612
5613                                 if (mc->mc_flags & C_SUB)
5614                                         dbi--;
5615
5616                                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5617                                         if (m2 == mc) continue;
5618                                         if (mc->mc_flags & C_SUB)
5619                                                 m3 = &m2->mc_xcursor->mx_cursor;
5620                                         else
5621                                                 m3 = m2;
5622                                         if (m3->mc_snum < mc->mc_snum) continue;
5623                                         if (m3->mc_pg[0] == mp) {
5624                                                 m3->mc_pg[0] = mc->mc_pg[0];
5625                                         }
5626                                 }
5627                         }
5628                 } else
5629                         DPUTS("root page doesn't need rebalancing");
5630                 return MDB_SUCCESS;
5631         }
5632
5633         /* The parent (branch page) must have at least 2 pointers,
5634          * otherwise the tree is invalid.
5635          */
5636         ptop = mc->mc_top-1;
5637         assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
5638
5639         /* Leaf page fill factor is below the threshold.
5640          * Try to move keys from left or right neighbor, or
5641          * merge with a neighbor page.
5642          */
5643
5644         /* Find neighbors.
5645          */
5646         mdb_cursor_copy(mc, &mn);
5647         mn.mc_xcursor = NULL;
5648
5649         if (mc->mc_ki[ptop] == 0) {
5650                 /* We're the leftmost leaf in our parent.
5651                  */
5652                 DPUTS("reading right neighbor");
5653                 mn.mc_ki[ptop]++;
5654                 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5655                 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5656                         return rc;
5657                 mn.mc_ki[mn.mc_top] = 0;
5658                 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
5659         } else {
5660                 /* There is at least one neighbor to the left.
5661                  */
5662                 DPUTS("reading left neighbor");
5663                 mn.mc_ki[ptop]--;
5664                 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5665                 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5666                         return rc;
5667                 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
5668                 mc->mc_ki[mc->mc_top] = 0;
5669         }
5670
5671         DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
5672             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);
5673
5674         /* If the neighbor page is above threshold and has at least two
5675          * keys, move one key from it.
5676          *
5677          * Otherwise we should try to merge them.
5678          */
5679         if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
5680                 return mdb_node_move(&mn, mc);
5681         else { /* FIXME: if (has_enough_room()) */
5682                 mc->mc_flags &= ~C_INITIALIZED;
5683                 if (mc->mc_ki[ptop] == 0)
5684                         return mdb_page_merge(&mn, mc);
5685                 else
5686                         return mdb_page_merge(mc, &mn);
5687         }
5688 }
5689
5690 /** Complete a delete operation started by #mdb_cursor_del(). */
5691 static int
5692 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
5693 {
5694         int rc;
5695
5696         /* add overflow pages to free list */
5697         if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5698                 int i, ovpages;
5699                 pgno_t pg;
5700
5701                 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5702                 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5703                 mc->mc_db->md_overflow_pages -= ovpages;
5704                 for (i=0; i<ovpages; i++) {
5705                         DPRINTF("freed ov page %zu", pg);
5706                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5707                         pg++;
5708                 }
5709         }
5710         mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
5711         mc->mc_db->md_entries--;
5712         rc = mdb_rebalance(mc);
5713         if (rc != MDB_SUCCESS)
5714                 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5715
5716         return rc;
5717 }
5718
5719 int
5720 mdb_del(MDB_txn *txn, MDB_dbi dbi,
5721     MDB_val *key, MDB_val *data)
5722 {
5723         MDB_cursor mc;
5724         MDB_xcursor mx;
5725         MDB_cursor_op op;
5726         MDB_val rdata, *xdata;
5727         int              rc, exact;
5728         DKBUF;
5729
5730         assert(key != NULL);
5731
5732         DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
5733
5734         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5735                 return EINVAL;
5736
5737         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5738                 return EACCES;
5739         }
5740
5741         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5742                 return EINVAL;
5743         }
5744
5745         mdb_cursor_init(&mc, txn, dbi, &mx);
5746
5747         exact = 0;
5748         if (data) {
5749                 op = MDB_GET_BOTH;
5750                 rdata = *data;
5751                 xdata = &rdata;
5752         } else {
5753                 op = MDB_SET;
5754                 xdata = NULL;
5755         }
5756         rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
5757         if (rc == 0)
5758                 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
5759         return rc;
5760 }
5761
5762 /** Split a page and insert a new node.
5763  * @param[in,out] mc Cursor pointing to the page and desired insertion index.
5764  * The cursor will be updated to point to the actual page and index where
5765  * the node got inserted after the split.
5766  * @param[in] newkey The key for the newly inserted node.
5767  * @param[in] newdata The data for the newly inserted node.
5768  * @param[in] newpgno The page number, if the new node is a branch node.
5769  * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
5770  * @return 0 on success, non-zero on failure.
5771  */
5772 static int
5773 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
5774         unsigned int nflags)
5775 {
5776         unsigned int flags;
5777         int              rc = MDB_SUCCESS, ins_new = 0, new_root = 0, newpos = 1, did_split = 0;
5778         indx_t           newindx;
5779         pgno_t           pgno = 0;
5780         unsigned int     i, j, split_indx, nkeys, pmax;
5781         MDB_node        *node;
5782         MDB_val  sepkey, rkey, xdata, *rdata = &xdata;
5783         MDB_page        *copy;
5784         MDB_page        *mp, *rp, *pp;
5785         unsigned int ptop;
5786         MDB_cursor      mn;
5787         DKBUF;
5788
5789         mp = mc->mc_pg[mc->mc_top];
5790         newindx = mc->mc_ki[mc->mc_top];
5791
5792         DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
5793             IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
5794             DKEY(newkey), mc->mc_ki[mc->mc_top]);
5795
5796         /* Create a right sibling. */
5797         if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
5798                 return ENOMEM;
5799         DPRINTF("new right sibling: page %zu", rp->mp_pgno);
5800
5801         if (mc->mc_snum < 2) {
5802                 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
5803                         return ENOMEM;
5804                 /* shift current top to make room for new parent */
5805                 mc->mc_pg[1] = mc->mc_pg[0];
5806                 mc->mc_ki[1] = mc->mc_ki[0];
5807                 mc->mc_pg[0] = pp;
5808                 mc->mc_ki[0] = 0;
5809                 mc->mc_db->md_root = pp->mp_pgno;
5810                 DPRINTF("root split! new root = %zu", pp->mp_pgno);
5811                 mc->mc_db->md_depth++;
5812                 new_root = 1;
5813
5814                 /* Add left (implicit) pointer. */
5815                 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
5816                         /* undo the pre-push */
5817                         mc->mc_pg[0] = mc->mc_pg[1];
5818                         mc->mc_ki[0] = mc->mc_ki[1];
5819                         mc->mc_db->md_root = mp->mp_pgno;
5820                         mc->mc_db->md_depth--;
5821                         return rc;
5822                 }
5823                 mc->mc_snum = 2;
5824                 mc->mc_top = 1;
5825                 ptop = 0;
5826         } else {
5827                 ptop = mc->mc_top-1;
5828                 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
5829         }
5830
5831         mc->mc_flags |= C_SPLITTING;
5832         mdb_cursor_copy(mc, &mn);
5833         mn.mc_pg[mn.mc_top] = rp;
5834         mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
5835
5836         if (nflags & MDB_APPEND) {
5837                 mn.mc_ki[mn.mc_top] = 0;
5838                 sepkey = *newkey;
5839                 split_indx = newindx;
5840                 nkeys = 0;
5841                 goto newsep;
5842         }
5843
5844         nkeys = NUMKEYS(mp);
5845         split_indx = (nkeys + 1) / 2;
5846         if (newindx < split_indx)
5847                 newpos = 0;
5848
5849         if (IS_LEAF2(rp)) {
5850                 char *split, *ins;
5851                 int x;
5852                 unsigned int lsize, rsize, ksize;
5853                 /* Move half of the keys to the right sibling */
5854                 copy = NULL;
5855                 x = mc->mc_ki[mc->mc_top] - split_indx;
5856                 ksize = mc->mc_db->md_pad;
5857                 split = LEAF2KEY(mp, split_indx, ksize);
5858                 rsize = (nkeys - split_indx) * ksize;
5859                 lsize = (nkeys - split_indx) * sizeof(indx_t);
5860                 mp->mp_lower -= lsize;
5861                 rp->mp_lower += lsize;
5862                 mp->mp_upper += rsize - lsize;
5863                 rp->mp_upper -= rsize - lsize;
5864                 sepkey.mv_size = ksize;
5865                 if (newindx == split_indx) {
5866                         sepkey.mv_data = newkey->mv_data;
5867                 } else {
5868                         sepkey.mv_data = split;
5869                 }
5870                 if (x<0) {
5871                         ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
5872                         memcpy(rp->mp_ptrs, split, rsize);
5873                         sepkey.mv_data = rp->mp_ptrs;
5874                         memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
5875                         memcpy(ins, newkey->mv_data, ksize);
5876                         mp->mp_lower += sizeof(indx_t);
5877                         mp->mp_upper -= ksize - sizeof(indx_t);
5878                 } else {
5879                         if (x)
5880                                 memcpy(rp->mp_ptrs, split, x * ksize);
5881                         ins = LEAF2KEY(rp, x, ksize);
5882                         memcpy(ins, newkey->mv_data, ksize);
5883                         memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
5884                         rp->mp_lower += sizeof(indx_t);
5885                         rp->mp_upper -= ksize - sizeof(indx_t);
5886                         mc->mc_ki[mc->mc_top] = x;
5887                         mc->mc_pg[mc->mc_top] = rp;
5888                 }
5889                 goto newsep;
5890         }
5891
5892         /* For leaf pages, check the split point based on what
5893          * fits where, since otherwise mdb_node_add can fail.
5894          *
5895          * This check is only needed when the data items are
5896          * relatively large, such that being off by one will
5897          * make the difference between success or failure.
5898          * When the size of the data items is much smaller than
5899          * one-half of a page, this check is irrelevant.
5900          */
5901         if (IS_LEAF(mp)) {
5902                 unsigned int psize, nsize;
5903                 /* Maximum free space in an empty page */
5904                 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
5905                 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
5906                 if ((nkeys < 20) || (nsize > pmax/4)) {
5907                         if (newindx <= split_indx) {
5908                                 psize = nsize;
5909                                 newpos = 0;
5910                                 for (i=0; i<split_indx; i++) {
5911                                         node = NODEPTR(mp, i);
5912                                         psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5913                                         if (F_ISSET(node->mn_flags, F_BIGDATA))
5914                                                 psize += sizeof(pgno_t);
5915                                         else
5916                                                 psize += NODEDSZ(node);
5917                                         psize += psize & 1;
5918                                         if (psize > pmax) {
5919                                                 if (i == split_indx - 1 && newindx == split_indx)
5920                                                         newpos = 1;
5921                                                 else
5922                                                         split_indx = i;
5923                                                 break;
5924                                         }
5925                                 }
5926                         } else {
5927                                 psize = nsize;
5928                                 for (i=nkeys-1; i>=split_indx; i--) {
5929                                         node = NODEPTR(mp, i);
5930                                         psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5931                                         if (F_ISSET(node->mn_flags, F_BIGDATA))
5932                                                 psize += sizeof(pgno_t);
5933                                         else
5934                                                 psize += NODEDSZ(node);
5935                                         psize += psize & 1;
5936                                         if (psize > pmax) {
5937                                                 split_indx = i+1;
5938                                                 break;
5939                                         }
5940                                 }
5941                         }
5942                 }
5943         }
5944
5945         /* First find the separating key between the split pages.
5946          * The case where newindx == split_indx is ambiguous; the
5947          * new item could go to the new page or stay on the original
5948          * page. If newpos == 1 it goes to the new page.
5949          */
5950         if (newindx == split_indx && newpos) {
5951                 sepkey.mv_size = newkey->mv_size;
5952                 sepkey.mv_data = newkey->mv_data;
5953         } else {
5954                 node = NODEPTR(mp, split_indx);
5955                 sepkey.mv_size = node->mn_ksize;
5956                 sepkey.mv_data = NODEKEY(node);
5957         }
5958
5959 newsep:
5960         DPRINTF("separator is [%s]", DKEY(&sepkey));
5961
5962         /* Copy separator key to the parent.
5963          */
5964         if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
5965                 mn.mc_snum--;
5966                 mn.mc_top--;
5967                 did_split = 1;
5968                 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
5969
5970                 /* root split? */
5971                 if (mn.mc_snum == mc->mc_snum) {
5972                         mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
5973                         mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
5974                         mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
5975                         mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
5976                         mc->mc_snum++;
5977                         mc->mc_top++;
5978                         ptop++;
5979                 }
5980                 /* Right page might now have changed parent.
5981                  * Check if left page also changed parent.
5982                  */
5983                 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
5984                     mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
5985                         for (i=0; i<ptop; i++) {
5986                                 mc->mc_pg[i] = mn.mc_pg[i];
5987                                 mc->mc_ki[i] = mn.mc_ki[i];
5988                         }
5989                         mc->mc_pg[ptop] = mn.mc_pg[ptop];
5990                         mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
5991                 }
5992         } else {
5993                 mn.mc_top--;
5994                 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
5995                 mn.mc_top++;
5996         }
5997         mc->mc_flags ^= C_SPLITTING;
5998         if (rc != MDB_SUCCESS) {
5999                 return rc;
6000         }
6001         if (nflags & MDB_APPEND) {
6002                 mc->mc_pg[mc->mc_top] = rp;
6003                 mc->mc_ki[mc->mc_top] = 0;
6004                 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
6005                 if (rc)
6006                         return rc;
6007                 for (i=0; i<mc->mc_top; i++)
6008                         mc->mc_ki[i] = mn.mc_ki[i];
6009                 goto done;
6010         }
6011         if (IS_LEAF2(rp)) {
6012                 goto done;
6013         }
6014
6015         /* Move half of the keys to the right sibling. */
6016
6017         /* grab a page to hold a temporary copy */
6018         copy = mdb_page_malloc(mc);
6019         if (copy == NULL)
6020                 return ENOMEM;
6021
6022         copy->mp_pgno  = mp->mp_pgno;
6023         copy->mp_flags = mp->mp_flags;
6024         copy->mp_lower = PAGEHDRSZ;
6025         copy->mp_upper = mc->mc_txn->mt_env->me_psize;
6026         mc->mc_pg[mc->mc_top] = copy;
6027         for (i = j = 0; i <= nkeys; j++) {
6028                 if (i == split_indx) {
6029                 /* Insert in right sibling. */
6030                 /* Reset insert index for right sibling. */
6031                         if (i != newindx || (newpos ^ ins_new)) {
6032                                 j = 0;
6033                                 mc->mc_pg[mc->mc_top] = rp;
6034                         }
6035                 }
6036
6037                 if (i == newindx && !ins_new) {
6038                         /* Insert the original entry that caused the split. */
6039                         rkey.mv_data = newkey->mv_data;
6040                         rkey.mv_size = newkey->mv_size;
6041                         if (IS_LEAF(mp)) {
6042                                 rdata = newdata;
6043                         } else
6044                                 pgno = newpgno;
6045                         flags = nflags;
6046
6047                         ins_new = 1;
6048
6049                         /* Update index for the new key. */
6050                         mc->mc_ki[mc->mc_top] = j;
6051                 } else if (i == nkeys) {
6052                         break;
6053                 } else {
6054                         node = NODEPTR(mp, i);
6055                         rkey.mv_data = NODEKEY(node);
6056                         rkey.mv_size = node->mn_ksize;
6057                         if (IS_LEAF(mp)) {
6058                                 xdata.mv_data = NODEDATA(node);
6059                                 xdata.mv_size = NODEDSZ(node);
6060                                 rdata = &xdata;
6061                         } else
6062                                 pgno = NODEPGNO(node);
6063                         flags = node->mn_flags;
6064
6065                         i++;
6066                 }
6067
6068                 if (!IS_LEAF(mp) && j == 0) {
6069                         /* First branch index doesn't need key data. */
6070                         rkey.mv_size = 0;
6071                 }
6072
6073                 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
6074                 if (rc) break;
6075         }
6076
6077         nkeys = NUMKEYS(copy);
6078         for (i=0; i<nkeys; i++)
6079                 mp->mp_ptrs[i] = copy->mp_ptrs[i];
6080         mp->mp_lower = copy->mp_lower;
6081         mp->mp_upper = copy->mp_upper;
6082         memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
6083                 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
6084
6085         /* reset back to original page */
6086         if (newindx < split_indx || (!newpos && newindx == split_indx)) {
6087                 mc->mc_pg[mc->mc_top] = mp;
6088                 if (nflags & MDB_RESERVE) {
6089                         node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6090                         if (!(node->mn_flags & F_BIGDATA))
6091                                 newdata->mv_data = NODEDATA(node);
6092                 }
6093         } else {
6094                 mc->mc_ki[ptop]++;
6095         }
6096
6097         /* return tmp page to freelist */
6098         copy->mp_next = mc->mc_txn->mt_env->me_dpages;
6099         VGMEMP_FREE(mc->mc_txn->mt_env, copy);
6100         mc->mc_txn->mt_env->me_dpages = copy;
6101 done:
6102         {
6103                 /* Adjust other cursors pointing to mp */
6104                 MDB_cursor *m2, *m3;
6105                 MDB_dbi dbi = mc->mc_dbi;
6106                 int fixup = NUMKEYS(mp);
6107
6108                 if (mc->mc_flags & C_SUB)
6109                         dbi--;
6110
6111                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6112                         if (m2 == mc) continue;
6113                         if (mc->mc_flags & C_SUB)
6114                                 m3 = &m2->mc_xcursor->mx_cursor;
6115                         else
6116                                 m3 = m2;
6117                         if (!(m3->mc_flags & C_INITIALIZED))
6118                                 continue;
6119                         if (m3->mc_flags & C_SPLITTING)
6120                                 continue;
6121                         if (new_root) {
6122                                 int k;
6123                                 /* root split */
6124                                 for (k=m3->mc_top; k>=0; k--) {
6125                                         m3->mc_ki[k+1] = m3->mc_ki[k];
6126                                         m3->mc_pg[k+1] = m3->mc_pg[k];
6127                                 }
6128                                 if (m3->mc_ki[0] >= split_indx) {
6129                                         m3->mc_ki[0] = 1;
6130                                 } else {
6131                                         m3->mc_ki[0] = 0;
6132                                 }
6133                                 m3->mc_pg[0] = mc->mc_pg[0];
6134                                 m3->mc_snum++;
6135                                 m3->mc_top++;
6136                         }
6137                         if (m3->mc_pg[mc->mc_top] == mp) {
6138                                 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
6139                                         m3->mc_ki[mc->mc_top]++;
6140                                 if (m3->mc_ki[mc->mc_top] >= fixup) {
6141                                         m3->mc_pg[mc->mc_top] = rp;
6142                                         m3->mc_ki[mc->mc_top] -= fixup;
6143                                         m3->mc_ki[ptop] = mn.mc_ki[ptop];
6144                                 }
6145                         } else if (!did_split && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
6146                                 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
6147                                 m3->mc_ki[ptop]++;
6148                         }
6149                 }
6150         }
6151         return rc;
6152 }
6153
6154 int
6155 mdb_put(MDB_txn *txn, MDB_dbi dbi,
6156     MDB_val *key, MDB_val *data, unsigned int flags)
6157 {
6158         MDB_cursor mc;
6159         MDB_xcursor mx;
6160
6161         assert(key != NULL);
6162         assert(data != NULL);
6163
6164         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6165                 return EINVAL;
6166
6167         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
6168                 return EACCES;
6169         }
6170
6171         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
6172                 return EINVAL;
6173         }
6174
6175         if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
6176                 return EINVAL;
6177
6178         mdb_cursor_init(&mc, txn, dbi, &mx);
6179         return mdb_cursor_put(&mc, key, data, flags);
6180 }
6181
6182 /** Only a subset of the @ref mdb_env flags can be changed
6183  *      at runtime. Changing other flags requires closing the environment
6184  *      and re-opening it with the new flags.
6185  */
6186 #define CHANGEABLE      (MDB_NOSYNC|MDB_NOMETASYNC)
6187 int
6188 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
6189 {
6190         if ((flag & CHANGEABLE) != flag)
6191                 return EINVAL;
6192         if (onoff)
6193                 env->me_flags |= flag;
6194         else
6195                 env->me_flags &= ~flag;
6196         return MDB_SUCCESS;
6197 }
6198
6199 int
6200 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
6201 {
6202         if (!env || !arg)
6203                 return EINVAL;
6204
6205         *arg = env->me_flags;
6206         return MDB_SUCCESS;
6207 }
6208
6209 int
6210 mdb_env_get_path(MDB_env *env, const char **arg)
6211 {
6212         if (!env || !arg)
6213                 return EINVAL;
6214
6215         *arg = env->me_path;
6216         return MDB_SUCCESS;
6217 }
6218
6219 /** Common code for #mdb_stat() and #mdb_env_stat().
6220  * @param[in] env the environment to operate in.
6221  * @param[in] db the #MDB_db record containing the stats to return.
6222  * @param[out] arg the address of an #MDB_stat structure to receive the stats.
6223  * @return 0, this function always succeeds.
6224  */
6225 static int
6226 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
6227 {
6228         arg->ms_psize = env->me_psize;
6229         arg->ms_depth = db->md_depth;
6230         arg->ms_branch_pages = db->md_branch_pages;
6231         arg->ms_leaf_pages = db->md_leaf_pages;
6232         arg->ms_overflow_pages = db->md_overflow_pages;
6233         arg->ms_entries = db->md_entries;
6234
6235         return MDB_SUCCESS;
6236 }
6237 int
6238 mdb_env_stat(MDB_env *env, MDB_stat *arg)
6239 {
6240         int toggle;
6241
6242         if (env == NULL || arg == NULL)
6243                 return EINVAL;
6244
6245         toggle = mdb_env_pick_meta(env);
6246
6247         return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
6248 }
6249
6250 /** Set the default comparison functions for a database.
6251  * Called immediately after a database is opened to set the defaults.
6252  * The user can then override them with #mdb_set_compare() or
6253  * #mdb_set_dupsort().
6254  * @param[in] txn A transaction handle returned by #mdb_txn_begin()
6255  * @param[in] dbi A database handle returned by #mdb_open()
6256  */
6257 static void
6258 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
6259 {
6260         uint16_t f = txn->mt_dbs[dbi].md_flags;
6261
6262         txn->mt_dbxs[dbi].md_cmp =
6263                 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
6264                 (f & MDB_INTEGERKEY) ? mdb_cmp_cint  : mdb_cmp_memn;
6265
6266         txn->mt_dbxs[dbi].md_dcmp =
6267                 !(f & MDB_DUPSORT) ? 0 :
6268                 ((f & MDB_INTEGERDUP)
6269                  ? ((f & MDB_DUPFIXED)   ? mdb_cmp_int   : mdb_cmp_cint)
6270                  : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
6271 }
6272
6273 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
6274 {
6275         MDB_val key, data;
6276         MDB_dbi i;
6277         MDB_cursor mc;
6278         int rc, dbflag, exact;
6279         unsigned int unused = 0;
6280         size_t len;
6281
6282         if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
6283                 mdb_default_cmp(txn, FREE_DBI);
6284         }
6285
6286         /* main DB? */
6287         if (!name) {
6288                 *dbi = MAIN_DBI;
6289                 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
6290                         txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
6291                 mdb_default_cmp(txn, MAIN_DBI);
6292                 return MDB_SUCCESS;
6293         }
6294
6295         if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
6296                 mdb_default_cmp(txn, MAIN_DBI);
6297         }
6298
6299         /* Is the DB already open? */
6300         len = strlen(name);
6301         for (i=2; i<txn->mt_numdbs; i++) {
6302                 if (!txn->mt_dbxs[i].md_name.mv_size) {
6303                         /* Remember this free slot */
6304                         if (!unused) unused = i;
6305                         continue;
6306                 }
6307                 if (len == txn->mt_dbxs[i].md_name.mv_size &&
6308                         !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
6309                         *dbi = i;
6310                         return MDB_SUCCESS;
6311                 }
6312         }
6313
6314         /* If no free slot and max hit, fail */
6315         if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
6316                 return ENFILE;
6317
6318         /* Find the DB info */
6319         dbflag = 0;
6320         exact = 0;
6321         key.mv_size = len;
6322         key.mv_data = (void *)name;
6323         mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
6324         rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
6325         if (rc == MDB_SUCCESS) {
6326                 /* make sure this is actually a DB */
6327                 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
6328                 if (!(node->mn_flags & F_SUBDATA))
6329                         return EINVAL;
6330         } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
6331                 /* Create if requested */
6332                 MDB_db dummy;
6333                 data.mv_size = sizeof(MDB_db);
6334                 data.mv_data = &dummy;
6335                 memset(&dummy, 0, sizeof(dummy));
6336                 dummy.md_root = P_INVALID;
6337                 dummy.md_flags = flags & 0xffff;
6338                 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
6339                 dbflag = DB_DIRTY;
6340         }
6341
6342         /* OK, got info, add to table */
6343         if (rc == MDB_SUCCESS) {
6344                 unsigned int slot = unused ? unused : txn->mt_numdbs;
6345                 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
6346                 txn->mt_dbxs[slot].md_name.mv_size = len;
6347                 txn->mt_dbxs[slot].md_rel = NULL;
6348                 txn->mt_dbflags[slot] = dbflag;
6349                 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
6350                 *dbi = slot;
6351                 txn->mt_env->me_dbflags[slot] = txn->mt_dbs[slot].md_flags;
6352                 mdb_default_cmp(txn, slot);
6353                 if (!unused) {
6354                         txn->mt_numdbs++;
6355                         txn->mt_env->me_numdbs++;
6356                 }
6357         }
6358
6359         return rc;
6360 }
6361
6362 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
6363 {
6364         if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
6365                 return EINVAL;
6366
6367         return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
6368 }
6369
6370 void mdb_close(MDB_env *env, MDB_dbi dbi)
6371 {
6372         char *ptr;
6373         if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
6374                 return;
6375         ptr = env->me_dbxs[dbi].md_name.mv_data;
6376         env->me_dbxs[dbi].md_name.mv_data = NULL;
6377         env->me_dbxs[dbi].md_name.mv_size = 0;
6378         free(ptr);
6379 }
6380
6381 /** Add all the DB's pages to the free list.
6382  * @param[in] mc Cursor on the DB to free.
6383  * @param[in] subs non-Zero to check for sub-DBs in this DB.
6384  * @return 0 on success, non-zero on failure.
6385  */
6386 static int
6387 mdb_drop0(MDB_cursor *mc, int subs)
6388 {
6389         int rc;
6390
6391         rc = mdb_page_search(mc, NULL, 0);
6392         if (rc == MDB_SUCCESS) {
6393                 MDB_node *ni;
6394                 MDB_cursor mx;
6395                 unsigned int i;
6396
6397                 /* LEAF2 pages have no nodes, cannot have sub-DBs */
6398                 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
6399                         mdb_cursor_pop(mc);
6400
6401                 mdb_cursor_copy(mc, &mx);
6402                 while (mc->mc_snum > 0) {
6403                         if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
6404                                 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
6405                                         ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
6406                                         if (ni->mn_flags & F_SUBDATA) {
6407                                                 mdb_xcursor_init1(mc, ni);
6408                                                 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6409                                                 if (rc)
6410                                                         return rc;
6411                                         }
6412                                 }
6413                         } else {
6414                                 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
6415                                         pgno_t pg;
6416                                         ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
6417                                         pg = NODEPGNO(ni);
6418                                         /* free it */
6419                                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
6420                                 }
6421                         }
6422                         if (!mc->mc_top)
6423                                 break;
6424                         rc = mdb_cursor_sibling(mc, 1);
6425                         if (rc) {
6426                                 /* no more siblings, go back to beginning
6427                                  * of previous level. (stack was already popped
6428                                  * by mdb_cursor_sibling)
6429                                  */
6430                                 for (i=1; i<mc->mc_top; i++)
6431                                         mc->mc_pg[i] = mx.mc_pg[i];
6432                         }
6433                 }
6434                 /* free it */
6435                 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
6436                         mc->mc_db->md_root);
6437         }
6438         return 0;
6439 }
6440
6441 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
6442 {
6443         MDB_cursor *mc;
6444         int rc;
6445
6446         if (!txn || !dbi || dbi >= txn->mt_numdbs)
6447                 return EINVAL;
6448
6449         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6450                 return EACCES;
6451
6452         rc = mdb_cursor_open(txn, dbi, &mc);
6453         if (rc)
6454                 return rc;
6455
6456         rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
6457         if (rc)
6458                 goto leave;
6459
6460         /* Can't delete the main DB */
6461         if (del && dbi > MAIN_DBI) {
6462                 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
6463                 if (!rc)
6464                         mdb_close(txn->mt_env, dbi);
6465         } else {
6466                 txn->mt_dbflags[dbi] |= DB_DIRTY;
6467                 txn->mt_dbs[dbi].md_depth = 0;
6468                 txn->mt_dbs[dbi].md_branch_pages = 0;
6469                 txn->mt_dbs[dbi].md_leaf_pages = 0;
6470                 txn->mt_dbs[dbi].md_overflow_pages = 0;
6471                 txn->mt_dbs[dbi].md_entries = 0;
6472                 txn->mt_dbs[dbi].md_root = P_INVALID;
6473         }
6474 leave:
6475         mdb_cursor_close(mc);
6476         return rc;
6477 }
6478
6479 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6480 {
6481         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6482                 return EINVAL;
6483
6484         txn->mt_dbxs[dbi].md_cmp = cmp;
6485         return MDB_SUCCESS;
6486 }
6487
6488 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6489 {
6490         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6491                 return EINVAL;
6492
6493         txn->mt_dbxs[dbi].md_dcmp = cmp;
6494         return MDB_SUCCESS;
6495 }
6496
6497 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
6498 {
6499         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6500                 return EINVAL;
6501
6502         txn->mt_dbxs[dbi].md_rel = rel;
6503         return MDB_SUCCESS;
6504 }
6505
6506 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
6507 {
6508         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6509                 return EINVAL;
6510
6511         txn->mt_dbxs[dbi].md_relctx = ctx;
6512         return MDB_SUCCESS;
6513 }
6514
6515 /** @} */