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