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