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