]> git.sur5r.net Git - openldap/blob - libraries/libmdb/mdb.c
Merge branch 'mdb.master' of ssh://git-master.openldap.org/~git/git/openldap
[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          *      The \b md_dirty flag is not read-only, but only a write
695          *      transaction can ever update it, and only write transactions
696          *      need to worry about it.
697          */
698 typedef struct MDB_dbx {
699         MDB_val         md_name;                /**< name of the database */
700         MDB_cmp_func    *md_cmp;        /**< function for comparing keys */
701         MDB_cmp_func    *md_dcmp;       /**< function for comparing data items */
702         MDB_rel_func    *md_rel;        /**< user relocate function */
703         void            *md_relctx;             /**< user-provided context for md_rel */
704         MDB_dbi md_parent;                      /**< parent DB of a sub-DB */
705         unsigned int    md_dirty;       /**< TRUE if DB was written in this txn */
706 } MDB_dbx;
707
708         /** A database transaction.
709          *      Every operation requires a transaction handle.
710          */
711 struct MDB_txn {
712         pgno_t          mt_next_pgno;   /**< next unallocated page */
713         /** The ID of this transaction. IDs are integers incrementing from 1.
714          *      Only committed write transactions increment the ID. If a transaction
715          *      aborts, the ID may be re-used by the next writer.
716          */
717         txnid_t         mt_txnid;
718         MDB_env         *mt_env;                /**< the DB environment */
719         /** The list of pages that became unused during this transaction.
720          *      This is an #IDL.
721          */
722         pgno_t          *mt_free_pgs;
723         union {
724                 ID2L    dirty_list;     /**< modified pages */
725                 MDB_reader      *reader;        /**< this thread's slot in the reader table */
726         } mt_u;
727         /** Array of records for each DB known in the environment. */
728         MDB_dbx         *mt_dbxs;
729         /** Array of MDB_db records for each known DB */
730         MDB_db          *mt_dbs;
731         /**     Number of DB records in use. This number only ever increments;
732          *      we don't decrement it when individual DB handles are closed.
733          */
734         MDB_dbi         mt_numdbs;
735
736 /** @defgroup mdb_txn   Transaction Flags
737  *      @ingroup internal
738  *      @{
739  */
740 #define MDB_TXN_RDONLY          0x01            /**< read-only transaction */
741 #define MDB_TXN_ERROR           0x02            /**< an error has occurred */
742 /** @} */
743         unsigned int    mt_flags;               /**< @ref mdb_txn */
744         /** Tracks which of the two meta pages was used at the start
745          *      of this transaction.
746          */
747         unsigned int    mt_toggle;
748 };
749
750 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
751  * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
752  * raise this on a 64 bit machine.
753  */
754 #define CURSOR_STACK             32
755
756 struct MDB_xcursor;
757
758         /** Cursors are used for all DB operations */
759 struct MDB_cursor {
760         /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
761         struct MDB_xcursor      *mc_xcursor;
762         /** The transaction that owns this cursor */
763         MDB_txn         *mc_txn;
764         /** The database handle this cursor operates on */
765         MDB_dbi         mc_dbi;
766         /** The database record for this cursor */
767         MDB_db          *mc_db;
768         /** The database auxiliary record for this cursor */
769         MDB_dbx         *mc_dbx;
770         unsigned short  mc_snum;        /**< number of pushed pages */
771         unsigned short  mc_top;         /**< index of top page, mc_snum-1 */
772 /** @defgroup mdb_cursor        Cursor Flags
773  *      @ingroup internal
774  *      Cursor state flags.
775  *      @{
776  */
777 #define C_INITIALIZED   0x01    /**< cursor has been initialized and is valid */
778 #define C_EOF   0x02                    /**< No more data */
779 /** @} */
780         unsigned int    mc_flags;       /**< @ref mdb_cursor */
781         MDB_page        *mc_pg[CURSOR_STACK];   /**< stack of pushed pages */
782         indx_t          mc_ki[CURSOR_STACK];    /**< stack of page indices */
783 };
784
785         /** Context for sorted-dup records.
786          *      We could have gone to a fully recursive design, with arbitrarily
787          *      deep nesting of sub-databases. But for now we only handle these
788          *      levels - main DB, optional sub-DB, sorted-duplicate DB.
789          */
790 typedef struct MDB_xcursor {
791         /** A sub-cursor for traversing the Dup DB */
792         MDB_cursor mx_cursor;
793         /** The database record for this Dup DB */
794         MDB_db  mx_db;
795         /**     The auxiliary DB record for this Dup DB */
796         MDB_dbx mx_dbx;
797 } MDB_xcursor;
798
799         /** A set of pages freed by an earlier transaction. */
800 typedef struct MDB_oldpages {
801         /** Usually we only read one record from the FREEDB at a time, but
802          *      in case we read more, this will chain them together.
803          */
804         struct MDB_oldpages *mo_next;
805         /**     The ID of the transaction in which these pages were freed. */
806         txnid_t         mo_txnid;
807         /** An #IDL of the pages */
808         pgno_t          mo_pages[1];    /* dynamic */
809 } MDB_oldpages;
810
811         /** The database environment. */
812 struct MDB_env {
813         HANDLE          me_fd;          /**< The main data file */
814         HANDLE          me_lfd;         /**< The lock file */
815         HANDLE          me_mfd;                 /**< just for writing the meta pages */
816         /** Failed to update the meta page. Probably an I/O error. */
817 #define MDB_FATAL_ERROR 0x80000000U
818         uint32_t        me_flags;               /**< @ref mdb_env */
819         uint32_t        me_extrapad;    /**< unused for now */
820         unsigned int    me_maxreaders;  /**< size of the reader table */
821         MDB_dbi         me_numdbs;              /**< number of DBs opened */
822         MDB_dbi         me_maxdbs;              /**< size of the DB table */
823         char            *me_path;               /**< path to the DB files */
824         char            *me_map;                /**< the memory map of the data file */
825         MDB_txninfo     *me_txns;               /**< the memory map of the lock file */
826         MDB_meta        *me_metas[2];   /**< pointers to the two meta pages */
827         MDB_txn         *me_txn;                /**< current write transaction */
828         size_t          me_mapsize;             /**< size of the data memory map */
829         off_t           me_size;                /**< current file size */
830         pgno_t          me_maxpg;               /**< me_mapsize / me_psize */
831         unsigned int    me_psize;       /**< size of a page, from #GET_PAGESIZE */
832         unsigned int    me_db_toggle;   /**< which DB table is current */
833         MDB_dbx         *me_dbxs;               /**< array of static DB info */
834         MDB_db          *me_dbs[2];             /**< two arrays of MDB_db info */
835         MDB_oldpages *me_pghead;        /**< list of old page records */
836         pthread_key_t   me_txkey;       /**< thread-key for readers */
837         MDB_page        *me_dpages;             /**< list of malloc'd blocks for re-use */
838         /** IDL of pages that became unused in a write txn */
839         pgno_t          me_free_pgs[MDB_IDL_UM_SIZE];
840         /** ID2L of pages that were written during a write txn */
841         ID2                     me_dirty_list[MDB_IDL_UM_SIZE];
842         /** rwlock for the DB tables, if #LAZY_LOCKS is false */
843         LAZY_RWLOCK_DEF(me_dblock)
844 #ifdef _WIN32
845         HANDLE          me_rmutex;              /* Windows mutexes don't reside in shared mem */
846         HANDLE          me_wmutex;
847 #endif
848 #ifdef __APPLE__
849         sem_t           *me_rmutex;             /* Apple doesn't support shared mutexes */
850         sem_t           *me_wmutex;
851 #endif
852 };
853         /** max number of pages to commit in one writev() call */
854 #define MDB_COMMIT_PAGES         64
855
856 static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
857 static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
858 static int              mdb_page_touch(MDB_cursor *mc);
859
860 static int  mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
861 static int  mdb_page_search_root(MDB_cursor *mc,
862                             MDB_val *key, int modify);
863 static int  mdb_page_search(MDB_cursor *mc,
864                             MDB_val *key, int modify);
865 static int      mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
866 static int      mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
867                                 pgno_t newpgno);
868
869 static int  mdb_env_read_header(MDB_env *env, MDB_meta *meta);
870 static int  mdb_env_read_meta(MDB_env *env, int *which);
871 static int  mdb_env_write_meta(MDB_txn *txn);
872
873 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
874 static int  mdb_node_add(MDB_cursor *mc, indx_t indx,
875                             MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags);
876 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
877 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
878 static int      mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
879 static int  mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
880 static size_t   mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
881 static size_t   mdb_branch_size(MDB_env *env, MDB_val *key);
882
883 static int      mdb_rebalance(MDB_cursor *mc);
884 static int      mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
885
886 static void     mdb_cursor_pop(MDB_cursor *mc);
887 static int      mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
888
889 static int      mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
890 static int      mdb_cursor_sibling(MDB_cursor *mc, int move_right);
891 static int      mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
892 static int      mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
893 static int      mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
894                                 int *exactp);
895 static int      mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
896 static int      mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
897
898 static void     mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
899 static void     mdb_xcursor_init0(MDB_cursor *mc);
900 static void     mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
901
902 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
903
904 /** @cond */
905 static MDB_cmp_func     mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
906 /** @endcond */
907
908 #ifdef _WIN32
909 static SECURITY_DESCRIPTOR mdb_null_sd;
910 static SECURITY_ATTRIBUTES mdb_all_sa;
911 static int mdb_sec_inited;
912 #endif
913
914 /** Return the library version info. */
915 char *
916 mdb_version(int *major, int *minor, int *patch)
917 {
918         if (major) *major = MDB_VERSION_MAJOR;
919         if (minor) *minor = MDB_VERSION_MINOR;
920         if (patch) *patch = MDB_VERSION_PATCH;
921         return MDB_VERSION_STRING;
922 }
923
924 /** Table of descriptions for MDB @ref errors */
925 static char *const mdb_errstr[] = {
926         "MDB_KEYEXIST: Key/data pair already exists",
927         "MDB_NOTFOUND: No matching key/data pair found",
928         "MDB_PAGE_NOTFOUND: Requested page not found",
929         "MDB_CORRUPTED: Located page was wrong type",
930         "MDB_PANIC: Update of meta page failed",
931         "MDB_VERSION_MISMATCH: Database environment version mismatch"
932 };
933
934 char *
935 mdb_strerror(int err)
936 {
937         if (!err)
938                 return ("Successful return: 0");
939
940         if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
941                 return mdb_errstr[err - MDB_KEYEXIST];
942
943         return strerror(err);
944 }
945
946 #if DEBUG
947 /** Display a key in hexadecimal and return the address of the result.
948  * @param[in] key the key to display
949  * @param[in] buf the buffer to write into. Should always be #DKBUF.
950  * @return The key in hexadecimal form.
951  */
952 char *
953 mdb_dkey(MDB_val *key, char *buf)
954 {
955         char *ptr = buf;
956         unsigned char *c = key->mv_data;
957         unsigned int i;
958         if (key->mv_size > MAXKEYSIZE)
959                 return "MAXKEYSIZE";
960         /* may want to make this a dynamic check: if the key is mostly
961          * printable characters, print it as-is instead of converting to hex.
962          */
963 #if 1
964         for (i=0; i<key->mv_size; i++)
965                 ptr += sprintf(ptr, "%02x", *c++);
966 #else
967         sprintf(buf, "%.*s", key->mv_size, key->mv_data);
968 #endif
969         return buf;
970 }
971 #endif
972
973 int
974 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
975 {
976         return txn->mt_dbxs[dbi].md_cmp(a, b);
977 }
978
979 int
980 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
981 {
982         if (txn->mt_dbxs[dbi].md_dcmp)
983                 return txn->mt_dbxs[dbi].md_dcmp(a, b);
984         else
985                 return EINVAL;  /* too bad you can't distinguish this from a valid result */
986 }
987
988 /** Allocate pages for writing.
989  * If there are free pages available from older transactions, they
990  * will be re-used first. Otherwise a new page will be allocated.
991  * @param[in] mc cursor A cursor handle identifying the transaction and
992  *      database for which we are allocating.
993  * @param[in] num the number of pages to allocate.
994  * @return Address of the allocated page(s). Requests for multiple pages
995  *  will always be satisfied by a single contiguous chunk of memory.
996  */
997 static MDB_page *
998 mdb_page_alloc(MDB_cursor *mc, int num)
999 {
1000         MDB_txn *txn = mc->mc_txn;
1001         MDB_page *np;
1002         pgno_t pgno = P_INVALID;
1003         ID2 mid;
1004
1005         if (txn->mt_txnid > 2) {
1006
1007                 if (!txn->mt_env->me_pghead && mc->mc_dbi != FREE_DBI &&
1008                         txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1009                         /* See if there's anything in the free DB */
1010                         MDB_cursor m2;
1011                         MDB_node *leaf;
1012                         txnid_t *kptr, oldest;
1013
1014                         mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1015                         mdb_page_search(&m2, NULL, 0);
1016                         leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1017                         kptr = (txnid_t *)NODEKEY(leaf);
1018
1019                         {
1020                                 unsigned int i;
1021                                 oldest = txn->mt_txnid - 1;
1022                                 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
1023                                         txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
1024                                         if (mr && mr < oldest)
1025                                                 oldest = mr;
1026                                 }
1027                         }
1028
1029                         if (oldest > *kptr) {
1030                                 /* It's usable, grab it.
1031                                  */
1032                                 MDB_oldpages *mop;
1033                                 MDB_val data;
1034                                 pgno_t *idl;
1035
1036                                 mdb_node_read(txn, leaf, &data);
1037                                 idl = (ID *) data.mv_data;
1038                                 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1039                                 mop->mo_next = txn->mt_env->me_pghead;
1040                                 mop->mo_txnid = *kptr;
1041                                 txn->mt_env->me_pghead = mop;
1042                                 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1043
1044 #if DEBUG > 1
1045                                 {
1046                                         unsigned int i;
1047                                         DPRINTF("IDL read txn %zu root %zu num %zu",
1048                                                 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1049                                         for (i=0; i<idl[0]; i++) {
1050                                                 DPRINTF("IDL %zu", idl[i+1]);
1051                                         }
1052                                 }
1053 #endif
1054                                 /* drop this IDL from the DB */
1055                                 m2.mc_ki[m2.mc_top] = 0;
1056                                 m2.mc_flags = C_INITIALIZED;
1057                                 mdb_cursor_del(&m2, 0);
1058                         }
1059                 }
1060                 if (txn->mt_env->me_pghead) {
1061                         MDB_oldpages *mop = txn->mt_env->me_pghead;
1062                         if (num > 1) {
1063                                 /* FIXME: For now, always use fresh pages. We
1064                                  * really ought to search the free list for a
1065                                  * contiguous range.
1066                                  */
1067                                 ;
1068                         } else {
1069                                 /* peel pages off tail, so we only have to truncate the list */
1070                                 pgno = MDB_IDL_LAST(mop->mo_pages);
1071                                 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1072                                         mop->mo_pages[2]++;
1073                                         if (mop->mo_pages[2] > mop->mo_pages[1])
1074                                                 mop->mo_pages[0] = 0;
1075                                 } else {
1076                                         mop->mo_pages[0]--;
1077                                 }
1078                                 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1079                                         txn->mt_env->me_pghead = mop->mo_next;
1080                                         free(mop);
1081                                 }
1082                         }
1083                 }
1084         }
1085
1086         if (pgno == P_INVALID) {
1087                 /* DB size is maxed out */
1088                 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1089                         assert(txn->mt_next_pgno + num < txn->mt_env->me_maxpg);
1090                         return NULL;
1091                 }
1092         }
1093         if (txn->mt_env->me_dpages && num == 1) {
1094                 np = txn->mt_env->me_dpages;
1095                 txn->mt_env->me_dpages = np->mp_next;
1096         } else {
1097                 if ((np = malloc(txn->mt_env->me_psize * num )) == NULL)
1098                         return NULL;
1099         }
1100         if (pgno == P_INVALID) {
1101                 np->mp_pgno = txn->mt_next_pgno;
1102                 txn->mt_next_pgno += num;
1103         } else {
1104                 np->mp_pgno = pgno;
1105         }
1106         mid.mid = np->mp_pgno;
1107         mid.mptr = np;
1108         mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1109
1110         return np;
1111 }
1112
1113 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1114  * @param[in] mc cursor pointing to the page to be touched
1115  * @return 0 on success, non-zero on failure.
1116  */
1117 static int
1118 mdb_page_touch(MDB_cursor *mc)
1119 {
1120         MDB_page *mp = mc->mc_pg[mc->mc_top];
1121         pgno_t  pgno;
1122
1123         if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1124                 MDB_page *np;
1125                 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1126                         return ENOMEM;
1127                 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1128                 assert(mp->mp_pgno != np->mp_pgno);
1129                 mdb_midl_append(mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1130                 pgno = np->mp_pgno;
1131                 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1132                 mp = np;
1133                 mp->mp_pgno = pgno;
1134                 mp->mp_flags |= P_DIRTY;
1135
1136                 mc->mc_pg[mc->mc_top] = mp;
1137                 /** If this page has a parent, update the parent to point to
1138                  * this new page.
1139                  */
1140                 if (mc->mc_top)
1141                         SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1142         }
1143         return 0;
1144 }
1145
1146 int
1147 mdb_env_sync(MDB_env *env, int force)
1148 {
1149         int rc = 0;
1150         if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1151                 if (fdatasync(env->me_fd))
1152                         rc = ErrCode();
1153         }
1154         return rc;
1155 }
1156
1157 static inline void
1158 mdb_txn_reset0(MDB_txn *txn);
1159
1160 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1161  * @param[in] txn the transaction handle to initialize
1162  * @return 0 on success, non-zero on failure. This can only
1163  * fail for read-only transactions, and then only if the
1164  * reader table is full.
1165  */
1166 static inline int
1167 mdb_txn_renew0(MDB_txn *txn)
1168 {
1169         MDB_env *env = txn->mt_env;
1170
1171         if (txn->mt_flags & MDB_TXN_RDONLY) {
1172                 MDB_reader *r = pthread_getspecific(env->me_txkey);
1173                 if (!r) {
1174                         unsigned int i;
1175                         pid_t pid = getpid();
1176                         pthread_t tid = pthread_self();
1177
1178                         LOCK_MUTEX_R(env);
1179                         for (i=0; i<env->me_txns->mti_numreaders; i++)
1180                                 if (env->me_txns->mti_readers[i].mr_pid == 0)
1181                                         break;
1182                         if (i == env->me_maxreaders) {
1183                                 UNLOCK_MUTEX_R(env);
1184                                 return ENOMEM;
1185                         }
1186                         env->me_txns->mti_readers[i].mr_pid = pid;
1187                         env->me_txns->mti_readers[i].mr_tid = tid;
1188                         if (i >= env->me_txns->mti_numreaders)
1189                                 env->me_txns->mti_numreaders = i+1;
1190                         UNLOCK_MUTEX_R(env);
1191                         r = &env->me_txns->mti_readers[i];
1192                         pthread_setspecific(env->me_txkey, r);
1193                 }
1194                 txn->mt_txnid = env->me_txns->mti_txnid;
1195                 txn->mt_toggle = env->me_txns->mti_me_toggle;
1196                 r->mr_txnid = txn->mt_txnid;
1197                 txn->mt_u.reader = r;
1198         } else {
1199                 LOCK_MUTEX_W(env);
1200
1201                 txn->mt_txnid = env->me_txns->mti_txnid+1;
1202                 txn->mt_toggle = env->me_txns->mti_me_toggle;
1203                 txn->mt_u.dirty_list = env->me_dirty_list;
1204                 txn->mt_u.dirty_list[0].mid = 0;
1205                 txn->mt_free_pgs = env->me_free_pgs;
1206                 txn->mt_free_pgs[0] = 0;
1207                 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1208                 env->me_txn = txn;
1209         }
1210
1211         /* Copy the DB arrays */
1212         LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1213         txn->mt_numdbs = env->me_numdbs;
1214         txn->mt_dbxs = env->me_dbxs;    /* mostly static anyway */
1215         memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1216         if (txn->mt_numdbs > 2)
1217                 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1218                         (txn->mt_numdbs - 2) * sizeof(MDB_db));
1219         LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1220
1221         return MDB_SUCCESS;
1222 }
1223
1224 int
1225 mdb_txn_renew(MDB_txn *txn)
1226 {
1227         int rc;
1228
1229         if (!txn)
1230                 return EINVAL;
1231
1232         if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1233                 DPUTS("environment had fatal error, must shutdown!");
1234                 return MDB_PANIC;
1235         }
1236
1237         rc = mdb_txn_renew0(txn);
1238         if (rc == MDB_SUCCESS) {
1239                 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1240                         txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1241                         (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1242         }
1243         return rc;
1244 }
1245
1246 int
1247 mdb_txn_begin(MDB_env *env, unsigned int flags, MDB_txn **ret)
1248 {
1249         MDB_txn *txn;
1250         int rc;
1251
1252         if (env->me_flags & MDB_FATAL_ERROR) {
1253                 DPUTS("environment had fatal error, must shutdown!");
1254                 return MDB_PANIC;
1255         }
1256         if ((txn = calloc(1, sizeof(MDB_txn) + env->me_maxdbs * sizeof(MDB_db))) == NULL) {
1257                 DPRINTF("calloc: %s", strerror(ErrCode()));
1258                 return ENOMEM;
1259         }
1260         txn->mt_dbs = (MDB_db *)(txn+1);
1261         if (flags & MDB_RDONLY) {
1262                 txn->mt_flags |= MDB_TXN_RDONLY;
1263         }
1264         txn->mt_env = env;
1265
1266         rc = mdb_txn_renew0(txn);
1267         if (rc)
1268                 free(txn);
1269         else {
1270                 *ret = txn;
1271                 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1272                         txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1273                         (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1274         }
1275
1276         return rc;
1277 }
1278
1279 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1280  * @param[in] txn the transaction handle to reset
1281  */
1282 static inline void
1283 mdb_txn_reset0(MDB_txn *txn)
1284 {
1285         MDB_env *env = txn->mt_env;
1286
1287         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1288                 txn->mt_u.reader->mr_txnid = 0;
1289         } else {
1290                 MDB_oldpages *mop;
1291                 MDB_page *dp;
1292                 MDB_dbi dbi;
1293                 unsigned int i;
1294
1295                 /* return all dirty pages to dpage list */
1296                 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1297                         dp = txn->mt_u.dirty_list[i].mptr;
1298                         if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1299                                 dp->mp_next = txn->mt_env->me_dpages;
1300                                 txn->mt_env->me_dpages = dp;
1301                         } else {
1302                                 /* large pages just get freed directly */
1303                                 free(dp);
1304                         }
1305                 }
1306
1307                 while ((mop = txn->mt_env->me_pghead)) {
1308                         txn->mt_env->me_pghead = mop->mo_next;
1309                         free(mop);
1310                 }
1311
1312                 env->me_txn = NULL;
1313                 for (dbi=2; dbi<env->me_numdbs; dbi++)
1314                         env->me_dbxs[dbi].md_dirty = 0;
1315                 /* The writer mutex was locked in mdb_txn_begin. */
1316                 UNLOCK_MUTEX_W(env);
1317         }
1318 }
1319
1320 void
1321 mdb_txn_reset(MDB_txn *txn)
1322 {
1323         if (txn == NULL)
1324                 return;
1325
1326         DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1327                 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1328                 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1329
1330         mdb_txn_reset0(txn);
1331 }
1332
1333 void
1334 mdb_txn_abort(MDB_txn *txn)
1335 {
1336         if (txn == NULL)
1337                 return;
1338
1339         DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1340                 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1341                 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1342
1343         mdb_txn_reset0(txn);
1344         free(txn);
1345 }
1346
1347 int
1348 mdb_txn_commit(MDB_txn *txn)
1349 {
1350         int              n, done;
1351         unsigned int i;
1352         ssize_t          rc;
1353         off_t            size;
1354         MDB_page        *dp;
1355         MDB_env *env;
1356         pgno_t  next;
1357         MDB_cursor mc;
1358
1359         assert(txn != NULL);
1360         assert(txn->mt_env != NULL);
1361
1362         env = txn->mt_env;
1363
1364         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1365                 mdb_txn_abort(txn);
1366                 return MDB_SUCCESS;
1367         }
1368
1369         if (txn != env->me_txn) {
1370                 DPUTS("attempt to commit unknown transaction");
1371                 mdb_txn_abort(txn);
1372                 return EINVAL;
1373         }
1374
1375         if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1376                 DPUTS("error flag is set, can't commit");
1377                 mdb_txn_abort(txn);
1378                 return EINVAL;
1379         }
1380
1381         if (!txn->mt_u.dirty_list[0].mid)
1382                 goto done;
1383
1384         DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1385             txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1386
1387         mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1388
1389         /* should only be one record now */
1390         if (env->me_pghead) {
1391                 /* make sure first page of freeDB is touched and on freelist */
1392                 mdb_page_search(&mc, NULL, 1);
1393         }
1394         /* save to free list */
1395         if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1396                 MDB_val key, data;
1397                 pgno_t i;
1398
1399                 /* make sure last page of freeDB is touched and on freelist */
1400                 key.mv_size = MAXKEYSIZE+1;
1401                 key.mv_data = NULL;
1402                 mdb_page_search(&mc, &key, 1);
1403
1404                 mdb_midl_sort(txn->mt_free_pgs);
1405 #if DEBUG > 1
1406                 {
1407                         unsigned int i;
1408                         ID *idl = txn->mt_free_pgs;
1409                         DPRINTF("IDL write txn %zu root %zu num %zu",
1410                                 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1411                         for (i=0; i<idl[0]; i++) {
1412                                 DPRINTF("IDL %zu", idl[i+1]);
1413                         }
1414                 }
1415 #endif
1416                 /* write to last page of freeDB */
1417                 key.mv_size = sizeof(pgno_t);
1418                 key.mv_data = &txn->mt_txnid;
1419                 data.mv_data = txn->mt_free_pgs;
1420                 /* The free list can still grow during this call,
1421                  * despite the pre-emptive touches above. So check
1422                  * and make sure the entire thing got written.
1423                  */
1424                 do {
1425                         i = txn->mt_free_pgs[0];
1426                         data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1427                         rc = mdb_cursor_put(&mc, &key, &data, 0);
1428                         if (rc) {
1429                                 mdb_txn_abort(txn);
1430                                 return rc;
1431                         }
1432                 } while (i != txn->mt_free_pgs[0]);
1433         }
1434         /* should only be one record now */
1435         if (env->me_pghead) {
1436                 MDB_val key, data;
1437                 MDB_oldpages *mop;
1438
1439                 mop = env->me_pghead;
1440                 key.mv_size = sizeof(pgno_t);
1441                 key.mv_data = &mop->mo_txnid;
1442                 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1443                 data.mv_data = mop->mo_pages;
1444                 mdb_cursor_put(&mc, &key, &data, 0);
1445                 free(env->me_pghead);
1446                 env->me_pghead = NULL;
1447         }
1448
1449         /* Update DB root pointers. Their pages have already been
1450          * touched so this is all in-place and cannot fail.
1451          */
1452         {
1453                 MDB_dbi i;
1454                 MDB_val data;
1455                 data.mv_size = sizeof(MDB_db);
1456
1457                 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
1458                 for (i = 2; i < txn->mt_numdbs; i++) {
1459                         if (txn->mt_dbxs[i].md_dirty) {
1460                                 data.mv_data = &txn->mt_dbs[i];
1461                                 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1462                         }
1463                 }
1464         }
1465
1466         /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1467          */
1468         next = 0;
1469         i = 1;
1470         do {
1471 #ifdef _WIN32
1472                 /* Windows actually supports scatter/gather I/O, but only on
1473                  * unbuffered file handles. Since we're relying on the OS page
1474                  * cache for all our data, that's self-defeating. So we just
1475                  * write pages one at a time. We use the ov structure to set
1476                  * the write offset, to at least save the overhead of a Seek
1477                  * system call.
1478                  */
1479                 OVERLAPPED ov;
1480                 memset(&ov, 0, sizeof(ov));
1481                 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1482                         size_t wsize;
1483                         dp = txn->mt_u.dirty_list[i].mptr;
1484                         DPRINTF("committing page %zu", dp->mp_pgno);
1485                         size = dp->mp_pgno * env->me_psize;
1486                         ov.Offset = size & 0xffffffff;
1487                         ov.OffsetHigh = size >> 16;
1488                         ov.OffsetHigh >>= 16;
1489                         /* clear dirty flag */
1490                         dp->mp_flags &= ~P_DIRTY;
1491                         wsize = env->me_psize;
1492                         if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1493                         rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1494                         if (!rc) {
1495                                 n = ErrCode();
1496                                 DPRINTF("WriteFile: %d", n);
1497                                 mdb_txn_abort(txn);
1498                                 return n;
1499                         }
1500                 }
1501                 done = 1;
1502 #else
1503                 struct iovec     iov[MDB_COMMIT_PAGES];
1504                 n = 0;
1505                 done = 1;
1506                 size = 0;
1507                 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1508                         dp = txn->mt_u.dirty_list[i].mptr;
1509                         if (dp->mp_pgno != next) {
1510                                 if (n) {
1511                                         DPRINTF("committing %u dirty pages", n);
1512                                         rc = writev(env->me_fd, iov, n);
1513                                         if (rc != size) {
1514                                                 n = ErrCode();
1515                                                 if (rc > 0)
1516                                                         DPUTS("short write, filesystem full?");
1517                                                 else
1518                                                         DPRINTF("writev: %s", strerror(n));
1519                                                 mdb_txn_abort(txn);
1520                                                 return n;
1521                                         }
1522                                         n = 0;
1523                                         size = 0;
1524                                 }
1525                                 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
1526                                 next = dp->mp_pgno;
1527                         }
1528                         DPRINTF("committing page %zu", dp->mp_pgno);
1529                         iov[n].iov_len = env->me_psize;
1530                         if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
1531                         iov[n].iov_base = dp;
1532                         size += iov[n].iov_len;
1533                         next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
1534                         /* clear dirty flag */
1535                         dp->mp_flags &= ~P_DIRTY;
1536                         if (++n >= MDB_COMMIT_PAGES) {
1537                                 done = 0;
1538                                 i++;
1539                                 break;
1540                         }
1541                 }
1542
1543                 if (n == 0)
1544                         break;
1545
1546                 DPRINTF("committing %u dirty pages", n);
1547                 rc = writev(env->me_fd, iov, n);
1548                 if (rc != size) {
1549                         n = ErrCode();
1550                         if (rc > 0)
1551                                 DPUTS("short write, filesystem full?");
1552                         else
1553                                 DPRINTF("writev: %s", strerror(n));
1554                         mdb_txn_abort(txn);
1555                         return n;
1556                 }
1557 #endif
1558         } while (!done);
1559
1560         /* Drop the dirty pages.
1561          */
1562         for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1563                 dp = txn->mt_u.dirty_list[i].mptr;
1564                 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1565                         dp->mp_next = txn->mt_env->me_dpages;
1566                         txn->mt_env->me_dpages = dp;
1567                 } else {
1568                         free(dp);
1569                 }
1570                 txn->mt_u.dirty_list[i].mid = 0;
1571         }
1572         txn->mt_u.dirty_list[0].mid = 0;
1573
1574         if ((n = mdb_env_sync(env, 0)) != 0 ||
1575             (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1576                 mdb_txn_abort(txn);
1577                 return n;
1578         }
1579
1580 done:
1581         env->me_txn = NULL;
1582         /* update the DB tables */
1583         {
1584                 int toggle = !env->me_db_toggle;
1585                 MDB_db *ip, *jp;
1586                 MDB_dbi i;
1587
1588                 ip = &env->me_dbs[toggle][2];
1589                 jp = &txn->mt_dbs[2];
1590                 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1591                 for (i = 2; i < txn->mt_numdbs; i++) {
1592                         if (ip->md_root != jp->md_root)
1593                                 *ip = *jp;
1594                         ip++; jp++;
1595                 }
1596
1597                 for (i = 2; i < txn->mt_numdbs; i++) {
1598                         if (txn->mt_dbxs[i].md_dirty)
1599                                 txn->mt_dbxs[i].md_dirty = 0;
1600                 }
1601                 env->me_db_toggle = toggle;
1602                 env->me_numdbs = txn->mt_numdbs;
1603                 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1604         }
1605
1606         UNLOCK_MUTEX_W(env);
1607         free(txn);
1608
1609         return MDB_SUCCESS;
1610 }
1611
1612 /** Read the environment parameters of a DB environment before
1613  * mapping it into memory.
1614  * @param[in] env the environment handle
1615  * @param[out] meta address of where to store the meta information
1616  * @return 0 on success, non-zero on failure.
1617  */
1618 static int
1619 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1620 {
1621         char             page[PAGESIZE];
1622         MDB_page        *p;
1623         MDB_meta        *m;
1624         int              rc, err;
1625
1626         /* We don't know the page size yet, so use a minimum value.
1627          */
1628
1629 #ifdef _WIN32
1630         if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1631 #else
1632         if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1633 #endif
1634         {
1635                 return ENOENT;
1636         }
1637         else if (rc != PAGESIZE) {
1638                 err = ErrCode();
1639                 if (rc > 0)
1640                         err = EINVAL;
1641                 DPRINTF("read: %s", strerror(err));
1642                 return err;
1643         }
1644
1645         p = (MDB_page *)page;
1646
1647         if (!F_ISSET(p->mp_flags, P_META)) {
1648                 DPRINTF("page %zu not a meta page", p->mp_pgno);
1649                 return EINVAL;
1650         }
1651
1652         m = METADATA(p);
1653         if (m->mm_magic != MDB_MAGIC) {
1654                 DPUTS("meta has invalid magic");
1655                 return EINVAL;
1656         }
1657
1658         if (m->mm_version != MDB_VERSION) {
1659                 DPRINTF("database is version %u, expected version %u",
1660                     m->mm_version, MDB_VERSION);
1661                 return MDB_VERSION_MISMATCH;
1662         }
1663
1664         memcpy(meta, m, sizeof(*m));
1665         return 0;
1666 }
1667
1668 /** Write the environment parameters of a freshly created DB environment.
1669  * @param[in] env the environment handle
1670  * @param[out] meta address of where to store the meta information
1671  * @return 0 on success, non-zero on failure.
1672  */
1673 static int
1674 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1675 {
1676         MDB_page *p, *q;
1677         MDB_meta *m;
1678         int rc;
1679         unsigned int     psize;
1680
1681         DPUTS("writing new meta page");
1682
1683         GET_PAGESIZE(psize);
1684
1685         meta->mm_magic = MDB_MAGIC;
1686         meta->mm_version = MDB_VERSION;
1687         meta->mm_psize = psize;
1688         meta->mm_last_pg = 1;
1689         meta->mm_flags = env->me_flags & 0xffff;
1690         meta->mm_flags |= MDB_INTEGERKEY;
1691         meta->mm_dbs[0].md_root = P_INVALID;
1692         meta->mm_dbs[1].md_root = P_INVALID;
1693
1694         p = calloc(2, psize);
1695         p->mp_pgno = 0;
1696         p->mp_flags = P_META;
1697
1698         m = METADATA(p);
1699         memcpy(m, meta, sizeof(*meta));
1700
1701         q = (MDB_page *)((char *)p + psize);
1702
1703         q->mp_pgno = 1;
1704         q->mp_flags = P_META;
1705
1706         m = METADATA(q);
1707         memcpy(m, meta, sizeof(*meta));
1708
1709 #ifdef _WIN32
1710         {
1711                 DWORD len;
1712                 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
1713                 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
1714         }
1715 #else
1716         rc = write(env->me_fd, p, psize * 2);
1717         rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
1718 #endif
1719         free(p);
1720         return rc;
1721 }
1722
1723 /** Update the environment info to commit a transaction.
1724  * @param[in] txn the transaction that's being committed
1725  * @return 0 on success, non-zero on failure.
1726  */
1727 static int
1728 mdb_env_write_meta(MDB_txn *txn)
1729 {
1730         MDB_env *env;
1731         MDB_meta        meta, metab;
1732         off_t off;
1733         int rc, len, toggle;
1734         char *ptr;
1735 #ifdef _WIN32
1736         OVERLAPPED ov;
1737 #endif
1738
1739         assert(txn != NULL);
1740         assert(txn->mt_env != NULL);
1741
1742         toggle = !txn->mt_toggle;
1743         DPRINTF("writing meta page %d for root page %zu",
1744                 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1745
1746         env = txn->mt_env;
1747
1748         metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1749         metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1750
1751         ptr = (char *)&meta;
1752         off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1753         len = sizeof(MDB_meta) - off;
1754
1755         ptr += off;
1756         meta.mm_dbs[0] = txn->mt_dbs[0];
1757         meta.mm_dbs[1] = txn->mt_dbs[1];
1758         meta.mm_last_pg = txn->mt_next_pgno - 1;
1759         meta.mm_txnid = txn->mt_txnid;
1760
1761         if (toggle)
1762                 off += env->me_psize;
1763         off += PAGEHDRSZ;
1764
1765         /* Write to the SYNC fd */
1766 #ifdef _WIN32
1767         {
1768                 memset(&ov, 0, sizeof(ov));
1769                 ov.Offset = off;
1770                 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
1771         }
1772 #else
1773         rc = pwrite(env->me_mfd, ptr, len, off);
1774 #endif
1775         if (rc != len) {
1776                 int r2;
1777                 rc = ErrCode();
1778                 DPUTS("write failed, disk error?");
1779                 /* On a failure, the pagecache still contains the new data.
1780                  * Write some old data back, to prevent it from being used.
1781                  * Use the non-SYNC fd; we know it will fail anyway.
1782                  */
1783                 meta.mm_last_pg = metab.mm_last_pg;
1784                 meta.mm_txnid = metab.mm_txnid;
1785 #ifdef _WIN32
1786                 WriteFile(env->me_fd, ptr, len, NULL, &ov);
1787 #else
1788                 r2 = pwrite(env->me_fd, ptr, len, off);
1789 #endif
1790                 env->me_flags |= MDB_FATAL_ERROR;
1791                 return rc;
1792         }
1793         /* Memory ordering issues are irrelevant; since the entire writer
1794          * is wrapped by wmutex, all of these changes will become visible
1795          * after the wmutex is unlocked. Since the DB is multi-version,
1796          * readers will get consistent data regardless of how fresh or
1797          * how stale their view of these values is.
1798          */
1799         LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
1800         txn->mt_env->me_txns->mti_me_toggle = toggle;
1801         txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
1802         LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
1803
1804         return MDB_SUCCESS;
1805 }
1806
1807 /** Check both meta pages to see which one is newer.
1808  * @param[in] env the environment handle
1809  * @param[out] which address of where to store the meta toggle ID
1810  * @return 0 on success, non-zero on failure.
1811  */
1812 static int
1813 mdb_env_read_meta(MDB_env *env, int *which)
1814 {
1815         int toggle = 0;
1816
1817         assert(env != NULL);
1818
1819         if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1820                 toggle = 1;
1821
1822         DPRINTF("Using meta page %d", toggle);
1823         *which = toggle;
1824
1825         return MDB_SUCCESS;
1826 }
1827
1828 int
1829 mdb_env_create(MDB_env **env)
1830 {
1831         MDB_env *e;
1832
1833         e = calloc(1, sizeof(MDB_env));
1834         if (!e)
1835                 return ENOMEM;
1836
1837         e->me_maxreaders = DEFAULT_READERS;
1838         e->me_maxdbs = 2;
1839         e->me_fd = INVALID_HANDLE_VALUE;
1840         e->me_lfd = INVALID_HANDLE_VALUE;
1841         e->me_mfd = INVALID_HANDLE_VALUE;
1842         *env = e;
1843         return MDB_SUCCESS;
1844 }
1845
1846 int
1847 mdb_env_set_mapsize(MDB_env *env, size_t size)
1848 {
1849         if (env->me_map)
1850                 return EINVAL;
1851         env->me_mapsize = size;
1852         return MDB_SUCCESS;
1853 }
1854
1855 int
1856 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
1857 {
1858         if (env->me_map)
1859                 return EINVAL;
1860         env->me_maxdbs = dbs;
1861         return MDB_SUCCESS;
1862 }
1863
1864 int
1865 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
1866 {
1867         if (env->me_map || readers < 1)
1868                 return EINVAL;
1869         env->me_maxreaders = readers;
1870         return MDB_SUCCESS;
1871 }
1872
1873 int
1874 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
1875 {
1876         if (!env || !readers)
1877                 return EINVAL;
1878         *readers = env->me_maxreaders;
1879         return MDB_SUCCESS;
1880 }
1881
1882 /** Further setup required for opening an MDB environment
1883  */
1884 static int
1885 mdb_env_open2(MDB_env *env, unsigned int flags)
1886 {
1887         int i, newenv = 0, toggle;
1888         MDB_meta meta;
1889         MDB_page *p;
1890
1891         env->me_flags = flags;
1892
1893         memset(&meta, 0, sizeof(meta));
1894
1895         if ((i = mdb_env_read_header(env, &meta)) != 0) {
1896                 if (i != ENOENT)
1897                         return i;
1898                 DPUTS("new mdbenv");
1899                 newenv = 1;
1900         }
1901
1902         if (!env->me_mapsize) {
1903                 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1904         }
1905
1906 #ifdef _WIN32
1907         {
1908                 HANDLE mh;
1909                 LONG sizelo, sizehi;
1910                 sizelo = env->me_mapsize & 0xffffffff;
1911                 sizehi = env->me_mapsize >> 16;         /* pointless on WIN32, only needed on W64 */
1912                 sizehi >>= 16;
1913                 /* Windows won't create mappings for zero length files.
1914                  * Just allocate the maxsize right now.
1915                  */
1916                 if (newenv) {
1917                         SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
1918                         if (!SetEndOfFile(env->me_fd))
1919                                 return ErrCode();
1920                         SetFilePointer(env->me_fd, 0, NULL, 0);
1921                 }
1922                 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
1923                         sizehi, sizelo, NULL);
1924                 if (!mh)
1925                         return ErrCode();
1926                 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
1927                         meta.mm_address);
1928                 CloseHandle(mh);
1929                 if (!env->me_map)
1930                         return ErrCode();
1931         }
1932 #else
1933         i = MAP_SHARED;
1934         if (meta.mm_address && (flags & MDB_FIXEDMAP))
1935                 i |= MAP_FIXED;
1936         env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1937                 env->me_fd, 0);
1938         if (env->me_map == MAP_FAILED)
1939                 return ErrCode();
1940 #endif
1941
1942         if (newenv) {
1943                 meta.mm_mapsize = env->me_mapsize;
1944                 if (flags & MDB_FIXEDMAP)
1945                         meta.mm_address = env->me_map;
1946                 i = mdb_env_init_meta(env, &meta);
1947                 if (i != MDB_SUCCESS) {
1948                         munmap(env->me_map, env->me_mapsize);
1949                         return i;
1950                 }
1951         }
1952         env->me_psize = meta.mm_psize;
1953
1954         env->me_maxpg = env->me_mapsize / env->me_psize;
1955
1956         p = (MDB_page *)env->me_map;
1957         env->me_metas[0] = METADATA(p);
1958         env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1959
1960         if ((i = mdb_env_read_meta(env, &toggle)) != 0)
1961                 return i;
1962
1963         DPRINTF("opened database version %u, pagesize %u",
1964             env->me_metas[toggle]->mm_version, env->me_psize);
1965         DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
1966         DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
1967         DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
1968         DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
1969         DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
1970         DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
1971
1972         return MDB_SUCCESS;
1973 }
1974
1975 #ifndef _WIN32
1976 /** Release a reader thread's slot in the reader lock table.
1977  *      This function is called automatically when a thread exits.
1978  *      Windows doesn't support destructor callbacks for thread-specific storage,
1979  *      so this function is not compiled there.
1980  * @param[in] ptr This points to the slot in the reader lock table.
1981  */
1982 static void
1983 mdb_env_reader_dest(void *ptr)
1984 {
1985         MDB_reader *reader = ptr;
1986
1987         reader->mr_txnid = 0;
1988         reader->mr_pid = 0;
1989         reader->mr_tid = 0;
1990 }
1991 #endif
1992
1993 /** Downgrade the exclusive lock on the region back to shared */
1994 static void
1995 mdb_env_share_locks(MDB_env *env)
1996 {
1997         int toggle = 0;
1998
1999         if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2000                 toggle = 1;
2001         env->me_txns->mti_me_toggle = toggle;
2002         env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2003
2004 #ifdef _WIN32
2005         {
2006                 OVERLAPPED ov;
2007                 /* First acquire a shared lock. The Unlock will
2008                  * then release the existing exclusive lock.
2009                  */
2010                 memset(&ov, 0, sizeof(ov));
2011                 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2012                 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2013         }
2014 #else
2015         {
2016                 struct flock lock_info;
2017                 /* The shared lock replaces the existing lock */
2018                 memset((void *)&lock_info, 0, sizeof(lock_info));
2019                 lock_info.l_type = F_RDLCK;
2020                 lock_info.l_whence = SEEK_SET;
2021                 lock_info.l_start = 0;
2022                 lock_info.l_len = 1;
2023                 fcntl(env->me_lfd, F_SETLK, &lock_info);
2024         }
2025 #endif
2026 }
2027 #if defined(_WIN32) || defined(__APPLE__)
2028 /*
2029  * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2030  *
2031  * @(#) $Revision: 5.1 $
2032  * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2033  * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2034  *
2035  *        http://www.isthe.com/chongo/tech/comp/fnv/index.html
2036  *
2037  ***
2038  *
2039  * Please do not copyright this code.  This code is in the public domain.
2040  *
2041  * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2042  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2043  * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2044  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2045  * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2046  * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2047  * PERFORMANCE OF THIS SOFTWARE.
2048  *
2049  * By:
2050  *      chongo <Landon Curt Noll> /\oo/\
2051  *        http://www.isthe.com/chongo/
2052  *
2053  * Share and Enjoy!     :-)
2054  */
2055
2056 typedef unsigned long long      mdb_hash_t;
2057 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2058
2059 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2060  * @param[in] str string to hash
2061  * @param[in] hval      initial value for hash
2062  * @return 64 bit hash
2063  *
2064  * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2065  *       hval arg on the first call.
2066  */
2067 static inline mdb_hash_t
2068 mdb_hash_str(char *str, mdb_hash_t hval)
2069 {
2070         unsigned char *s = (unsigned char *)str;        /* unsigned string */
2071         /*
2072          * FNV-1a hash each octet of the string
2073          */
2074         while (*s) {
2075                 /* xor the bottom with the current octet */
2076                 hval ^= (mdb_hash_t)*s++;
2077
2078                 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2079                 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2080                         (hval << 7) + (hval << 8) + (hval << 40);
2081         }
2082         /* return our new hash value */
2083         return hval;
2084 }
2085
2086 /** Hash the string and output the hash in hex.
2087  * @param[in] str string to hash
2088  * @param[out] hexbuf an array of 17 chars to hold the hash
2089  */
2090 static void
2091 mdb_hash_hex(char *str, char *hexbuf)
2092 {
2093         int i;
2094         mdb_hash_t h = mdb_hash_str(str, MDB_HASH_INIT);
2095         for (i=0; i<8; i++) {
2096                 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2097                 h >>= 8;
2098         }
2099 }
2100 #endif
2101
2102 /** Open and/or initialize the lock region for the environment.
2103  * @param[in] env The MDB environment.
2104  * @param[in] lpath The pathname of the file used for the lock region.
2105  * @param[in] mode The Unix permissions for the file, if we create it.
2106  * @param[out] excl Set to true if we got an exclusive lock on the region.
2107  * @return 0 on success, non-zero on failure.
2108  */
2109 static int
2110 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2111 {
2112         int rc;
2113         off_t size, rsize;
2114
2115         *excl = 0;
2116
2117 #ifdef _WIN32
2118         if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2119                 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2120                 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2121                 rc = ErrCode();
2122                 return rc;
2123         }
2124         /* Try to get exclusive lock. If we succeed, then
2125          * nobody is using the lock region and we should initialize it.
2126          */
2127         {
2128                 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2129                         *excl = 1;
2130                 } else {
2131                         OVERLAPPED ov;
2132                         memset(&ov, 0, sizeof(ov));
2133                         if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2134                                 rc = ErrCode();
2135                                 goto fail;
2136                         }
2137                 }
2138         }
2139         size = GetFileSize(env->me_lfd, NULL);
2140 #else
2141         if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2142                 rc = ErrCode();
2143                 return rc;
2144         }
2145         /* Try to get exclusive lock. If we succeed, then
2146          * nobody is using the lock region and we should initialize it.
2147          */
2148         {
2149                 struct flock lock_info;
2150                 memset((void *)&lock_info, 0, sizeof(lock_info));
2151                 lock_info.l_type = F_WRLCK;
2152                 lock_info.l_whence = SEEK_SET;
2153                 lock_info.l_start = 0;
2154                 lock_info.l_len = 1;
2155                 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2156                 if (rc == 0) {
2157                         *excl = 1;
2158                 } else {
2159                         lock_info.l_type = F_RDLCK;
2160                         rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2161                         if (rc) {
2162                                 rc = ErrCode();
2163                                 goto fail;
2164                         }
2165                 }
2166         }
2167         size = lseek(env->me_lfd, 0, SEEK_END);
2168 #endif
2169         rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2170         if (size < rsize && *excl) {
2171 #ifdef _WIN32
2172                 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2173                 if (!SetEndOfFile(env->me_lfd)) {
2174                         rc = ErrCode();
2175                         goto fail;
2176                 }
2177 #else
2178                 if (ftruncate(env->me_lfd, rsize) != 0) {
2179                         rc = ErrCode();
2180                         goto fail;
2181                 }
2182 #endif
2183         } else {
2184                 rsize = size;
2185                 size = rsize - sizeof(MDB_txninfo);
2186                 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2187         }
2188 #ifdef _WIN32
2189         {
2190                 HANDLE mh;
2191                 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2192                         0, 0, NULL);
2193                 if (!mh) {
2194                         rc = ErrCode();
2195                         goto fail;
2196                 }
2197                 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2198                 CloseHandle(mh);
2199                 if (!env->me_txns) {
2200                         rc = ErrCode();
2201                         goto fail;
2202                 }
2203         }
2204 #else
2205         env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2206                 env->me_lfd, 0);
2207         if (env->me_txns == MAP_FAILED) {
2208                 rc = ErrCode();
2209                 goto fail;
2210         }
2211 #endif
2212         if (*excl) {
2213 #ifdef _WIN32
2214                 char hexbuf[17];
2215                 if (!mdb_sec_inited) {
2216                         InitializeSecurityDescriptor(&mdb_null_sd,
2217                                 SECURITY_DESCRIPTOR_REVISION);
2218                         SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2219                         mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2220                         mdb_all_sa.bInheritHandle = FALSE;
2221                         mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2222                         mdb_sec_inited = 1;
2223                 }
2224                 mdb_hash_hex(lpath, hexbuf);
2225                 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2226                 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2227                 if (!env->me_rmutex) {
2228                         rc = ErrCode();
2229                         goto fail;
2230                 }
2231                 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2232                 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2233                 if (!env->me_wmutex) {
2234                         rc = ErrCode();
2235                         goto fail;
2236                 }
2237 #else   /* _WIN32 */
2238 #ifdef __APPLE__
2239                 char hexbuf[17];
2240                 mdb_hash_hex(lpath, hexbuf);
2241                 sprintf(env->me_txns->mti_rmname, "MDBr%s", hexbuf);
2242                 if (sem_unlink(env->me_txns->mti_rmname)) {
2243                         rc = ErrCode();
2244                         if (rc != ENOENT && rc != EINVAL)
2245                                 goto fail;
2246                 }
2247                 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2248                 if (!env->me_rmutex) {
2249                         rc = ErrCode();
2250                         goto fail;
2251                 }
2252                 sprintf(env->me_txns->mti_wmname, "MDBw%s", hexbuf);
2253                 if (sem_unlink(env->me_txns->mti_wmname)) {
2254                         rc = ErrCode();
2255                         if (rc != ENOENT && rc != EINVAL)
2256                                 goto fail;
2257                 }
2258                 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2259                 if (!env->me_wmutex) {
2260                         rc = ErrCode();
2261                         goto fail;
2262                 }
2263 #else   /* __APPLE__ */
2264                 pthread_mutexattr_t mattr;
2265
2266                 pthread_mutexattr_init(&mattr);
2267                 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2268                 if (rc) {
2269                         goto fail;
2270                 }
2271                 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2272                 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2273 #endif  /* __APPLE__ */
2274 #endif  /* _WIN32 */
2275                 env->me_txns->mti_version = MDB_VERSION;
2276                 env->me_txns->mti_magic = MDB_MAGIC;
2277                 env->me_txns->mti_txnid = 0;
2278                 env->me_txns->mti_numreaders = 0;
2279                 env->me_txns->mti_me_toggle = 0;
2280
2281         } else {
2282                 if (env->me_txns->mti_magic != MDB_MAGIC) {
2283                         DPUTS("lock region has invalid magic");
2284                         rc = EINVAL;
2285                         goto fail;
2286                 }
2287                 if (env->me_txns->mti_version != MDB_VERSION) {
2288                         DPRINTF("lock region is version %u, expected version %u",
2289                                 env->me_txns->mti_version, MDB_VERSION);
2290                         rc = MDB_VERSION_MISMATCH;
2291                         goto fail;
2292                 }
2293                 rc = ErrCode();
2294                 if (rc != EACCES && rc != EAGAIN) {
2295                         goto fail;
2296                 }
2297 #ifdef _WIN32
2298                 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2299                 if (!env->me_rmutex) {
2300                         rc = ErrCode();
2301                         goto fail;
2302                 }
2303                 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2304                 if (!env->me_wmutex) {
2305                         rc = ErrCode();
2306                         goto fail;
2307                 }
2308 #endif
2309 #ifdef __APPLE__
2310                 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2311                 if (!env->me_rmutex) {
2312                         rc = ErrCode();
2313                         goto fail;
2314                 }
2315                 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2316                 if (!env->me_wmutex) {
2317                         rc = ErrCode();
2318                         goto fail;
2319                 }
2320 #endif
2321         }
2322         return MDB_SUCCESS;
2323
2324 fail:
2325         close(env->me_lfd);
2326         env->me_lfd = INVALID_HANDLE_VALUE;
2327         return rc;
2328
2329 }
2330
2331         /** The name of the lock file in the DB environment */
2332 #define LOCKNAME        "/lock.mdb"
2333         /** The name of the data file in the DB environment */
2334 #define DATANAME        "/data.mdb"
2335 int
2336 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2337 {
2338         int             oflags, rc, len, excl;
2339         char *lpath, *dpath;
2340
2341         len = strlen(path);
2342         lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
2343         if (!lpath)
2344                 return ENOMEM;
2345         dpath = lpath + len + sizeof(LOCKNAME);
2346         sprintf(lpath, "%s" LOCKNAME, path);
2347         sprintf(dpath, "%s" DATANAME, path);
2348
2349         rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2350         if (rc)
2351                 goto leave;
2352
2353 #ifdef _WIN32
2354         if (F_ISSET(flags, MDB_RDONLY)) {
2355                 oflags = GENERIC_READ;
2356                 len = OPEN_EXISTING;
2357         } else {
2358                 oflags = GENERIC_READ|GENERIC_WRITE;
2359                 len = OPEN_ALWAYS;
2360         }
2361         mode = FILE_ATTRIBUTE_NORMAL;
2362         if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2363                         NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2364                 rc = ErrCode();
2365                 goto leave;
2366         }
2367 #else
2368         if (F_ISSET(flags, MDB_RDONLY))
2369                 oflags = O_RDONLY;
2370         else
2371                 oflags = O_RDWR | O_CREAT;
2372
2373         if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2374                 rc = ErrCode();
2375                 goto leave;
2376         }
2377 #endif
2378
2379         if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2380                 /* synchronous fd for meta writes */
2381 #ifdef _WIN32
2382                 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2383                         mode |= FILE_FLAG_WRITE_THROUGH;
2384                 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2385                         NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2386                         rc = ErrCode();
2387                         goto leave;
2388                 }
2389 #else
2390                 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2391                         oflags |= MDB_DSYNC;
2392                 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2393                         rc = ErrCode();
2394                         goto leave;
2395                 }
2396 #endif
2397                 env->me_path = strdup(path);
2398                 DPRINTF("opened dbenv %p", (void *) env);
2399                 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2400                 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2401                 if (excl)
2402                         mdb_env_share_locks(env);
2403                 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2404                 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2405                 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2406                 env->me_numdbs = 2;
2407         }
2408
2409 leave:
2410         if (rc) {
2411                 if (env->me_fd != INVALID_HANDLE_VALUE) {
2412                         close(env->me_fd);
2413                         env->me_fd = INVALID_HANDLE_VALUE;
2414                 }
2415                 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2416                         close(env->me_lfd);
2417                         env->me_lfd = INVALID_HANDLE_VALUE;
2418                 }
2419         }
2420         free(lpath);
2421         return rc;
2422 }
2423
2424 void
2425 mdb_env_close(MDB_env *env)
2426 {
2427         MDB_page *dp;
2428
2429         if (env == NULL)
2430                 return;
2431
2432         while (env->me_dpages) {
2433                 dp = env->me_dpages;
2434                 env->me_dpages = dp->mp_next;
2435                 free(dp);
2436         }
2437
2438         free(env->me_dbs[1]);
2439         free(env->me_dbs[0]);
2440         free(env->me_dbxs);
2441         free(env->me_path);
2442
2443         LAZY_RWLOCK_DESTROY(&env->me_dblock);
2444         pthread_key_delete(env->me_txkey);
2445
2446         if (env->me_map) {
2447                 munmap(env->me_map, env->me_mapsize);
2448         }
2449         close(env->me_mfd);
2450         close(env->me_fd);
2451         if (env->me_txns) {
2452                 pid_t pid = getpid();
2453                 unsigned int i;
2454                 for (i=0; i<env->me_txns->mti_numreaders; i++)
2455                         if (env->me_txns->mti_readers[i].mr_pid == pid)
2456                                 env->me_txns->mti_readers[i].mr_pid = 0;
2457                 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2458         }
2459         close(env->me_lfd);
2460         free(env);
2461 }
2462
2463 /** Compare two items pointing at aligned size_t's */
2464 static int
2465 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
2466 {
2467         return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
2468                 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
2469 }
2470
2471 /** Compare two items pointing at aligned int's */
2472 static int
2473 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
2474 {
2475         return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
2476                 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
2477 }
2478
2479 /** Compare two items pointing at ints of unknown alignment.
2480  *      Nodes and keys are guaranteed to be 2-byte aligned.
2481  */
2482 static int
2483 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
2484 {
2485 #if BYTE_ORDER == LITTLE_ENDIAN
2486         unsigned short *u, *c;
2487         int x;
2488
2489         u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
2490         c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
2491         do {
2492                 x = *--u - *--c;
2493         } while(!x && u > (unsigned short *)a->mv_data);
2494         return x;
2495 #else
2496         return memcmp(a->mv_data, b->mv_data, a->mv_size);
2497 #endif
2498 }
2499
2500 /** Compare two items lexically */
2501 static int
2502 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
2503 {
2504         int diff;
2505         ssize_t len_diff;
2506         unsigned int len;
2507
2508         len = a->mv_size;
2509         len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2510         if (len_diff > 0) {
2511                 len = b->mv_size;
2512                 len_diff = 1;
2513         }
2514
2515         diff = memcmp(a->mv_data, b->mv_data, len);
2516         return diff ? diff : len_diff<0 ? -1 : len_diff;
2517 }
2518
2519 /** Compare two items in reverse byte order */
2520 static int
2521 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
2522 {
2523         const unsigned char     *p1, *p2, *p1_lim;
2524         ssize_t len_diff;
2525         int diff;
2526
2527         p1_lim = (const unsigned char *)a->mv_data;
2528         p1 = (const unsigned char *)a->mv_data + a->mv_size;
2529         p2 = (const unsigned char *)b->mv_data + b->mv_size;
2530
2531         len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2532         if (len_diff > 0) {
2533                 p1_lim += len_diff;
2534                 len_diff = 1;
2535         }
2536
2537         while (p1 > p1_lim) {
2538                 diff = *--p1 - *--p2;
2539                 if (diff)
2540                         return diff;
2541         }
2542         return len_diff<0 ? -1 : len_diff;
2543 }
2544
2545 /** Search for key within a page, using binary search.
2546  * Returns the smallest entry larger or equal to the key.
2547  * If exactp is non-null, stores whether the found entry was an exact match
2548  * in *exactp (1 or 0).
2549  * Updates the cursor index with the index of the found entry.
2550  * If no entry larger or equal to the key is found, returns NULL.
2551  */
2552 static MDB_node *
2553 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
2554 {
2555         unsigned int     i = 0, nkeys;
2556         int              low, high;
2557         int              rc = 0;
2558         MDB_page *mp = mc->mc_pg[mc->mc_top];
2559         MDB_node        *node = NULL;
2560         MDB_val  nodekey;
2561         MDB_cmp_func *cmp;
2562         DKBUF;
2563
2564         nkeys = NUMKEYS(mp);
2565
2566         DPRINTF("searching %u keys in %s %spage %zu",
2567             nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
2568             mp->mp_pgno);
2569
2570         assert(nkeys > 0);
2571
2572         low = IS_LEAF(mp) ? 0 : 1;
2573         high = nkeys - 1;
2574         cmp = mc->mc_dbx->md_cmp;
2575
2576         /* Branch pages have no data, so if using integer keys,
2577          * alignment is guaranteed. Use faster mdb_cmp_int.
2578          */
2579         if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
2580                 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
2581                         cmp = mdb_cmp_long;
2582                 else
2583                         cmp = mdb_cmp_int;
2584         }
2585
2586         if (IS_LEAF2(mp)) {
2587                 nodekey.mv_size = mc->mc_db->md_pad;
2588                 node = NODEPTR(mp, 0);  /* fake */
2589                 while (low <= high) {
2590                         i = (low + high) >> 1;
2591                         nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2592                         rc = cmp(key, &nodekey);
2593                         DPRINTF("found leaf index %u [%s], rc = %i",
2594                             i, DKEY(&nodekey), rc);
2595                         if (rc == 0)
2596                                 break;
2597                         if (rc > 0)
2598                                 low = i + 1;
2599                         else
2600                                 high = i - 1;
2601                 }
2602         } else {
2603                 while (low <= high) {
2604                         i = (low + high) >> 1;
2605
2606                         node = NODEPTR(mp, i);
2607                         nodekey.mv_size = NODEKSZ(node);
2608                         nodekey.mv_data = NODEKEY(node);
2609
2610                         rc = cmp(key, &nodekey);
2611 #if DEBUG
2612                         if (IS_LEAF(mp))
2613                                 DPRINTF("found leaf index %u [%s], rc = %i",
2614                                     i, DKEY(&nodekey), rc);
2615                         else
2616                                 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
2617                                     i, DKEY(&nodekey), NODEPGNO(node), rc);
2618 #endif
2619                         if (rc == 0)
2620                                 break;
2621                         if (rc > 0)
2622                                 low = i + 1;
2623                         else
2624                                 high = i - 1;
2625                 }
2626         }
2627
2628         if (rc > 0) {   /* Found entry is less than the key. */
2629                 i++;    /* Skip to get the smallest entry larger than key. */
2630                 if (!IS_LEAF2(mp))
2631                         node = NODEPTR(mp, i);
2632         }
2633         if (exactp)
2634                 *exactp = (rc == 0);
2635         /* store the key index */
2636         mc->mc_ki[mc->mc_top] = i;
2637         if (i >= nkeys)
2638                 /* There is no entry larger or equal to the key. */
2639                 return NULL;
2640
2641         /* nodeptr is fake for LEAF2 */
2642         return node;
2643 }
2644
2645 /** Pop a page off the top of the cursor's stack. */
2646 static void
2647 mdb_cursor_pop(MDB_cursor *mc)
2648 {
2649         MDB_page        *top;
2650
2651         if (mc->mc_snum) {
2652                 top = mc->mc_pg[mc->mc_top];
2653                 mc->mc_snum--;
2654                 if (mc->mc_snum)
2655                         mc->mc_top--;
2656
2657                 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
2658                         mc->mc_dbi, (void *) mc);
2659         }
2660 }
2661
2662 /** Push a page onto the top of the cursor's stack. */
2663 static int
2664 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
2665 {
2666         DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
2667                 mc->mc_dbi, (void *) mc);
2668
2669         if (mc->mc_snum >= CURSOR_STACK) {
2670                 assert(mc->mc_snum < CURSOR_STACK);
2671                 return ENOMEM;
2672         }
2673
2674         mc->mc_top = mc->mc_snum++;
2675         mc->mc_pg[mc->mc_top] = mp;
2676         mc->mc_ki[mc->mc_top] = 0;
2677
2678         return MDB_SUCCESS;
2679 }
2680
2681 /** Find the address of the page corresponding to a given page number.
2682  * @param[in] txn the transaction for this access.
2683  * @param[in] pgno the page number for the page to retrieve.
2684  * @param[out] ret address of a pointer where the page's address will be stored.
2685  * @return 0 on success, non-zero on failure.
2686  */
2687 static int
2688 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
2689 {
2690         MDB_page *p = NULL;
2691
2692         if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
2693                 unsigned x;
2694                 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
2695                 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
2696                         p = txn->mt_u.dirty_list[x].mptr;
2697                 }
2698         }
2699         if (!p) {
2700                 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
2701                         p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
2702         }
2703         *ret = p;
2704         if (!p) {
2705                 DPRINTF("page %zu not found", pgno);
2706                 assert(p != NULL);
2707         }
2708         return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
2709 }
2710
2711 /** Search for the page a given key should be in.
2712  * Pushes parent pages on the cursor stack. This function continues a
2713  * search on a cursor that has already been initialized. (Usually by
2714  * #mdb_page_search() but also by #mdb_node_move().)
2715  * @param[in,out] mc the cursor for this operation.
2716  * @param[in] key the key to search for. If NULL, search for the lowest
2717  * page. (This is used by #mdb_cursor_first().)
2718  * @param[in] modify If true, visited pages are updated with new page numbers.
2719  * @return 0 on success, non-zero on failure.
2720  */
2721 static int
2722 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
2723 {
2724         MDB_page        *mp = mc->mc_pg[mc->mc_top];
2725         DKBUF;
2726         int rc;
2727
2728
2729         while (IS_BRANCH(mp)) {
2730                 MDB_node        *node;
2731                 indx_t          i;
2732
2733                 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
2734                 assert(NUMKEYS(mp) > 1);
2735                 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
2736
2737                 if (key == NULL)        /* Initialize cursor to first page. */
2738                         i = 0;
2739                 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
2740                                                         /* cursor to last page */
2741                         i = NUMKEYS(mp)-1;
2742                 } else {
2743                         int      exact;
2744                         node = mdb_node_search(mc, key, &exact);
2745                         if (node == NULL)
2746                                 i = NUMKEYS(mp) - 1;
2747                         else {
2748                                 i = mc->mc_ki[mc->mc_top];
2749                                 if (!exact) {
2750                                         assert(i > 0);
2751                                         i--;
2752                                 }
2753                         }
2754                 }
2755
2756                 if (key)
2757                         DPRINTF("following index %u for key [%s]",
2758                             i, DKEY(key));
2759                 assert(i < NUMKEYS(mp));
2760                 node = NODEPTR(mp, i);
2761
2762                 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
2763                         return rc;
2764
2765                 mc->mc_ki[mc->mc_top] = i;
2766                 if ((rc = mdb_cursor_push(mc, mp)))
2767                         return rc;
2768
2769                 if (modify) {
2770                         if ((rc = mdb_page_touch(mc)) != 0)
2771                                 return rc;
2772                         mp = mc->mc_pg[mc->mc_top];
2773                 }
2774         }
2775
2776         if (!IS_LEAF(mp)) {
2777                 DPRINTF("internal error, index points to a %02X page!?",
2778                     mp->mp_flags);
2779                 return MDB_CORRUPTED;
2780         }
2781
2782         DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
2783             key ? DKEY(key) : NULL);
2784
2785         return MDB_SUCCESS;
2786 }
2787
2788 /** Search for the page a given key should be in.
2789  * Pushes parent pages on the cursor stack. This function just sets up
2790  * the search; it finds the root page for \b mc's database and sets this
2791  * as the root of the cursor's stack. Then #mdb_page_search_root() is
2792  * called to complete the search.
2793  * @param[in,out] mc the cursor for this operation.
2794  * @param[in] key the key to search for. If NULL, search for the lowest
2795  * page. (This is used by #mdb_cursor_first().)
2796  * @param[in] modify If true, visited pages are updated with new page numbers.
2797  * @return 0 on success, non-zero on failure.
2798  */
2799 static int
2800 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
2801 {
2802         int              rc;
2803         pgno_t           root;
2804
2805         /* Make sure the txn is still viable, then find the root from
2806          * the txn's db table.
2807          */
2808         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
2809                 DPUTS("transaction has failed, must abort");
2810                 return EINVAL;
2811         } else
2812                 root = mc->mc_db->md_root;
2813
2814         if (root == P_INVALID) {                /* Tree is empty. */
2815                 DPUTS("tree is empty");
2816                 return MDB_NOTFOUND;
2817         }
2818
2819         if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
2820                 return rc;
2821
2822         mc->mc_snum = 1;
2823         mc->mc_top = 0;
2824
2825         DPRINTF("db %u root page %zu has flags 0x%X",
2826                 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
2827
2828         if (modify) {
2829                 /* For sub-databases, update main root first */
2830                 if (mc->mc_dbi > MAIN_DBI && !mc->mc_dbx->md_dirty) {
2831                         MDB_cursor mc2;
2832                         mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
2833                         rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
2834                         if (rc)
2835                                 return rc;
2836                         mc->mc_dbx->md_dirty = 1;
2837                 }
2838                 if (!F_ISSET(mc->mc_pg[0]->mp_flags, P_DIRTY)) {
2839                         if ((rc = mdb_page_touch(mc)))
2840                                 return rc;
2841                         mc->mc_db->md_root = mc->mc_pg[0]->mp_pgno;
2842                 }
2843         }
2844
2845         return mdb_page_search_root(mc, key, modify);
2846 }
2847
2848 /** Return the data associated with a given node.
2849  * @param[in] txn The transaction for this operation.
2850  * @param[in] leaf The node being read.
2851  * @param[out] data Updated to point to the node's data.
2852  * @return 0 on success, non-zero on failure.
2853  */
2854 static int
2855 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
2856 {
2857         MDB_page        *omp;           /* overflow page */
2858         pgno_t           pgno;
2859         int rc;
2860
2861         if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2862                 data->mv_size = NODEDSZ(leaf);
2863                 data->mv_data = NODEDATA(leaf);
2864                 return MDB_SUCCESS;
2865         }
2866
2867         /* Read overflow data.
2868          */
2869         data->mv_size = NODEDSZ(leaf);
2870         memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
2871         if ((rc = mdb_page_get(txn, pgno, &omp))) {
2872                 DPRINTF("read overflow page %zu failed", pgno);
2873                 return rc;
2874         }
2875         data->mv_data = METADATA(omp);
2876
2877         return MDB_SUCCESS;
2878 }
2879
2880 int
2881 mdb_get(MDB_txn *txn, MDB_dbi dbi,
2882     MDB_val *key, MDB_val *data)
2883 {
2884         MDB_cursor      mc;
2885         MDB_xcursor     mx;
2886         int exact = 0;
2887         DKBUF;
2888
2889         assert(key);
2890         assert(data);
2891         DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
2892
2893         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2894                 return EINVAL;
2895
2896         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2897                 return EINVAL;
2898         }
2899
2900         mdb_cursor_init(&mc, txn, dbi, &mx);
2901         return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
2902 }
2903
2904 /** Find a sibling for a page.
2905  * Replaces the page at the top of the cursor's stack with the
2906  * specified sibling, if one exists.
2907  * @param[in] mc The cursor for this operation.
2908  * @param[in] move_right Non-zero if the right sibling is requested,
2909  * otherwise the left sibling.
2910  * @return 0 on success, non-zero on failure.
2911  */
2912 static int
2913 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
2914 {
2915         int              rc;
2916         MDB_node        *indx;
2917         MDB_page        *mp;
2918
2919         if (mc->mc_snum < 2) {
2920                 return MDB_NOTFOUND;            /* root has no siblings */
2921         }
2922
2923         mdb_cursor_pop(mc);
2924         DPRINTF("parent page is page %zu, index %u",
2925                 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
2926
2927         if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
2928                        : (mc->mc_ki[mc->mc_top] == 0)) {
2929                 DPRINTF("no more keys left, moving to %s sibling",
2930                     move_right ? "right" : "left");
2931                 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
2932                         return rc;
2933         } else {
2934                 if (move_right)
2935                         mc->mc_ki[mc->mc_top]++;
2936                 else
2937                         mc->mc_ki[mc->mc_top]--;
2938                 DPRINTF("just moving to %s index key %u",
2939                     move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
2940         }
2941         assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
2942
2943         indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
2944         if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
2945                 return rc;;
2946
2947         mdb_cursor_push(mc, mp);
2948
2949         return MDB_SUCCESS;
2950 }
2951
2952 /** Move the cursor to the next data item. */
2953 static int
2954 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2955 {
2956         MDB_page        *mp;
2957         MDB_node        *leaf;
2958         int rc;
2959
2960         if (mc->mc_flags & C_EOF) {
2961                 return MDB_NOTFOUND;
2962         }
2963
2964         assert(mc->mc_flags & C_INITIALIZED);
2965
2966         mp = mc->mc_pg[mc->mc_top];
2967
2968         if (mc->mc_db->md_flags & MDB_DUPSORT) {
2969                 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2970                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2971                         if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2972                                 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2973                                 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2974                                         return rc;
2975                         }
2976                 } else {
2977                         mc->mc_xcursor->mx_cursor.mc_flags = 0;
2978                         if (op == MDB_NEXT_DUP)
2979                                 return MDB_NOTFOUND;
2980                 }
2981         }
2982
2983         DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
2984
2985         if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
2986                 DPUTS("=====> move to next sibling page");
2987                 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
2988                         mc->mc_flags |= C_EOF;
2989                         mc->mc_flags &= ~C_INITIALIZED;
2990                         return MDB_NOTFOUND;
2991                 }
2992                 mp = mc->mc_pg[mc->mc_top];
2993                 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
2994         } else
2995                 mc->mc_ki[mc->mc_top]++;
2996
2997         DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
2998             mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
2999
3000         if (IS_LEAF2(mp)) {
3001                 key->mv_size = mc->mc_db->md_pad;
3002                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3003                 return MDB_SUCCESS;
3004         }
3005
3006         assert(IS_LEAF(mp));
3007         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3008
3009         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3010                 mdb_xcursor_init1(mc, leaf);
3011         }
3012         if (data) {
3013                 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3014                         return rc;
3015
3016                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3017                         rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3018                         if (rc != MDB_SUCCESS)
3019                                 return rc;
3020                 }
3021         }
3022
3023         MDB_SET_KEY(leaf, key);
3024         return MDB_SUCCESS;
3025 }
3026
3027 /** Move the cursor to the previous data item. */
3028 static int
3029 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3030 {
3031         MDB_page        *mp;
3032         MDB_node        *leaf;
3033         int rc;
3034
3035         assert(mc->mc_flags & C_INITIALIZED);
3036
3037         mp = mc->mc_pg[mc->mc_top];
3038
3039         if (mc->mc_db->md_flags & MDB_DUPSORT) {
3040                 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3041                 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3042                         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3043                                 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3044                                 if (op != MDB_PREV || rc == MDB_SUCCESS)
3045                                         return rc;
3046                         } else {
3047                                 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3048                                 if (op == MDB_PREV_DUP)
3049                                         return MDB_NOTFOUND;
3050                         }
3051                 }
3052         }
3053
3054         DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3055
3056         if (mc->mc_ki[mc->mc_top] == 0)  {
3057                 DPUTS("=====> move to prev sibling page");
3058                 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3059                         mc->mc_flags &= ~C_INITIALIZED;
3060                         return MDB_NOTFOUND;
3061                 }
3062                 mp = mc->mc_pg[mc->mc_top];
3063                 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3064                 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3065         } else
3066                 mc->mc_ki[mc->mc_top]--;
3067
3068         mc->mc_flags &= ~C_EOF;
3069
3070         DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3071             mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3072
3073         if (IS_LEAF2(mp)) {
3074                 key->mv_size = mc->mc_db->md_pad;
3075                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3076                 return MDB_SUCCESS;
3077         }
3078
3079         assert(IS_LEAF(mp));
3080         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3081
3082         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3083                 mdb_xcursor_init1(mc, leaf);
3084         }
3085         if (data) {
3086                 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3087                         return rc;
3088
3089                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3090                         rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3091                         if (rc != MDB_SUCCESS)
3092                                 return rc;
3093                 }
3094         }
3095
3096         MDB_SET_KEY(leaf, key);
3097         return MDB_SUCCESS;
3098 }
3099
3100 /** Set the cursor on a specific data item. */
3101 static int
3102 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3103     MDB_cursor_op op, int *exactp)
3104 {
3105         int              rc;
3106         MDB_page        *mp;
3107         MDB_node        *leaf;
3108         DKBUF;
3109
3110         assert(mc);
3111         assert(key);
3112         assert(key->mv_size > 0);
3113
3114         /* See if we're already on the right page */
3115         if (mc->mc_flags & C_INITIALIZED) {
3116                 MDB_val nodekey;
3117
3118                 mp = mc->mc_pg[mc->mc_top];
3119                 if (!NUMKEYS(mp)) {
3120                         mc->mc_ki[mc->mc_top] = 0;
3121                         return MDB_NOTFOUND;
3122                 }
3123                 if (mp->mp_flags & P_LEAF2) {
3124                         nodekey.mv_size = mc->mc_db->md_pad;
3125                         nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3126                 } else {
3127                         leaf = NODEPTR(mp, 0);
3128                         MDB_SET_KEY(leaf, &nodekey);
3129                 }
3130                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3131                 if (rc == 0) {
3132                         /* Probably happens rarely, but first node on the page
3133                          * was the one we wanted.
3134                          */
3135                         mc->mc_ki[mc->mc_top] = 0;
3136                         leaf = NODEPTR(mp, 0);
3137                         if (exactp)
3138                                 *exactp = 1;
3139                         goto set1;
3140                 }
3141                 if (rc > 0) {
3142                         unsigned int i;
3143                         unsigned int nkeys = NUMKEYS(mp);
3144                         if (nkeys > 1) {
3145                                 if (mp->mp_flags & P_LEAF2) {
3146                                         nodekey.mv_data = LEAF2KEY(mp,
3147                                                  nkeys-1, nodekey.mv_size);
3148                                 } else {
3149                                         leaf = NODEPTR(mp, nkeys-1);
3150                                         MDB_SET_KEY(leaf, &nodekey);
3151                                 }
3152                                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3153                                 if (rc == 0) {
3154                                         /* last node was the one we wanted */
3155                                         mc->mc_ki[mc->mc_top] = nkeys-1;
3156                                         leaf = NODEPTR(mp, nkeys-1);
3157                                         if (exactp)
3158                                                 *exactp = 1;
3159                                         goto set1;
3160                                 }
3161                                 if (rc < 0) {
3162                                         /* This is definitely the right page, skip search_page */
3163                                         rc = 0;
3164                                         goto set2;
3165                                 }
3166                         }
3167                         /* If any parents have right-sibs, search.
3168                          * Otherwise, there's nothing further.
3169                          */
3170                         for (i=0; i<mc->mc_top; i++)
3171                                 if (mc->mc_ki[i] <
3172                                         NUMKEYS(mc->mc_pg[i])-1)
3173                                         break;
3174                         if (i == mc->mc_top) {
3175                                 /* There are no other pages */
3176                                 mc->mc_ki[mc->mc_top] = nkeys;
3177                                 return MDB_NOTFOUND;
3178                         }
3179                 }
3180                 if (!mc->mc_top) {
3181                         /* There are no other pages */
3182                         mc->mc_ki[mc->mc_top] = 0;
3183                         return MDB_NOTFOUND;
3184                 }
3185         }
3186
3187         rc = mdb_page_search(mc, key, 0);
3188         if (rc != MDB_SUCCESS)
3189                 return rc;
3190
3191         mp = mc->mc_pg[mc->mc_top];
3192         assert(IS_LEAF(mp));
3193
3194 set2:
3195         leaf = mdb_node_search(mc, key, exactp);
3196         if (exactp != NULL && !*exactp) {
3197                 /* MDB_SET specified and not an exact match. */
3198                 return MDB_NOTFOUND;
3199         }
3200
3201         if (leaf == NULL) {
3202                 DPUTS("===> inexact leaf not found, goto sibling");
3203                 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3204                         return rc;              /* no entries matched */
3205                 mp = mc->mc_pg[mc->mc_top];
3206                 assert(IS_LEAF(mp));
3207                 leaf = NODEPTR(mp, 0);
3208         }
3209
3210 set1:
3211         mc->mc_flags |= C_INITIALIZED;
3212         mc->mc_flags &= ~C_EOF;
3213
3214         if (IS_LEAF2(mp)) {
3215                 key->mv_size = mc->mc_db->md_pad;
3216                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3217                 return MDB_SUCCESS;
3218         }
3219
3220         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3221                 mdb_xcursor_init1(mc, leaf);
3222         }
3223         if (data) {
3224                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3225                         if (op == MDB_SET || op == MDB_SET_RANGE) {
3226                                 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3227                         } else {
3228                                 int ex2, *ex2p;
3229                                 if (op == MDB_GET_BOTH) {
3230                                         ex2p = &ex2;
3231                                         ex2 = 0;
3232                                 } else {
3233                                         ex2p = NULL;
3234                                 }
3235                                 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3236                                 if (rc != MDB_SUCCESS)
3237                                         return rc;
3238                         }
3239                 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3240                         MDB_val d2;
3241                         if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3242                                 return rc;
3243                         rc = mc->mc_dbx->md_dcmp(data, &d2);
3244                         if (rc) {
3245                                 if (op == MDB_GET_BOTH || rc > 0)
3246                                         return MDB_NOTFOUND;
3247                         }
3248
3249                 } else {
3250                         if (mc->mc_xcursor)
3251                                 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3252                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3253                                 return rc;
3254                 }
3255         }
3256
3257         /* The key already matches in all other cases */
3258         if (op == MDB_SET_RANGE)
3259                 MDB_SET_KEY(leaf, key);
3260         DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3261
3262         return rc;
3263 }
3264
3265 /** Move the cursor to the first item in the database. */
3266 static int
3267 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3268 {
3269         int              rc;
3270         MDB_node        *leaf;
3271
3272         if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3273                 rc = mdb_page_search(mc, NULL, 0);
3274                 if (rc != MDB_SUCCESS)
3275                         return rc;
3276         }
3277         assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3278
3279         leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3280         mc->mc_flags |= C_INITIALIZED;
3281         mc->mc_flags &= ~C_EOF;
3282
3283         mc->mc_ki[mc->mc_top] = 0;
3284
3285         if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3286                 key->mv_size = mc->mc_db->md_pad;
3287                 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3288                 return MDB_SUCCESS;
3289         }
3290
3291         if (data) {
3292                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3293                         mdb_xcursor_init1(mc, leaf);
3294                         rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3295                         if (rc)
3296                                 return rc;
3297                 } else {
3298                         if (mc->mc_xcursor)
3299                                 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3300                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3301                                 return rc;
3302                 }
3303         }
3304         MDB_SET_KEY(leaf, key);
3305         return MDB_SUCCESS;
3306 }
3307
3308 /** Move the cursor to the last item in the database. */
3309 static int
3310 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3311 {
3312         int              rc;
3313         MDB_node        *leaf;
3314         MDB_val lkey;
3315
3316         lkey.mv_size = MAXKEYSIZE+1;
3317         lkey.mv_data = NULL;
3318
3319         if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3320                 rc = mdb_page_search(mc, &lkey, 0);
3321                 if (rc != MDB_SUCCESS)
3322                         return rc;
3323         }
3324         assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3325
3326         leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3327         mc->mc_flags |= C_INITIALIZED;
3328         mc->mc_flags &= ~C_EOF;
3329
3330         mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3331
3332         if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3333                 key->mv_size = mc->mc_db->md_pad;
3334                 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3335                 return MDB_SUCCESS;
3336         }
3337
3338         if (data) {
3339                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3340                         mdb_xcursor_init1(mc, leaf);
3341                         rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3342                         if (rc)
3343                                 return rc;
3344                 } else {
3345                         if (mc->mc_xcursor)
3346                                 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3347                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3348                                 return rc;
3349                 }
3350         }
3351
3352         MDB_SET_KEY(leaf, key);
3353         return MDB_SUCCESS;
3354 }
3355
3356 int
3357 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3358     MDB_cursor_op op)
3359 {
3360         int              rc;
3361         int              exact = 0;
3362
3363         assert(mc);
3364
3365         switch (op) {
3366         case MDB_GET_BOTH:
3367         case MDB_GET_BOTH_RANGE:
3368                 if (data == NULL || mc->mc_xcursor == NULL) {
3369                         rc = EINVAL;
3370                         break;
3371                 }
3372                 /* FALLTHRU */
3373         case MDB_SET:
3374         case MDB_SET_RANGE:
3375                 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3376                         rc = EINVAL;
3377                 } else if (op == MDB_SET_RANGE)
3378                         rc = mdb_cursor_set(mc, key, data, op, NULL);
3379                 else
3380                         rc = mdb_cursor_set(mc, key, data, op, &exact);
3381                 break;
3382         case MDB_GET_MULTIPLE:
3383                 if (data == NULL ||
3384                         !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
3385                         !(mc->mc_flags & C_INITIALIZED)) {
3386                         rc = EINVAL;
3387                         break;
3388                 }
3389                 rc = MDB_SUCCESS;
3390                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3391                         (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3392                         break;
3393                 goto fetchm;
3394         case MDB_NEXT_MULTIPLE:
3395                 if (data == NULL ||
3396                         !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
3397                         rc = EINVAL;
3398                         break;
3399                 }
3400                 if (!(mc->mc_flags & C_INITIALIZED))
3401                         rc = mdb_cursor_first(mc, key, data);
3402                 else
3403                         rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3404                 if (rc == MDB_SUCCESS) {
3405                         if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3406                                 MDB_cursor *mx;
3407 fetchm:
3408                                 mx = &mc->mc_xcursor->mx_cursor;
3409                                 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3410                                         mx->mc_db->md_pad;
3411                                 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3412                                 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3413                         } else {
3414                                 rc = MDB_NOTFOUND;
3415                         }
3416                 }
3417                 break;
3418         case MDB_NEXT:
3419         case MDB_NEXT_DUP:
3420         case MDB_NEXT_NODUP:
3421                 if (!(mc->mc_flags & C_INITIALIZED))
3422                         rc = mdb_cursor_first(mc, key, data);
3423                 else
3424                         rc = mdb_cursor_next(mc, key, data, op);
3425                 break;
3426         case MDB_PREV:
3427         case MDB_PREV_DUP:
3428         case MDB_PREV_NODUP:
3429                 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3430                         rc = mdb_cursor_last(mc, key, data);
3431                 else
3432                         rc = mdb_cursor_prev(mc, key, data, op);
3433                 break;
3434         case MDB_FIRST:
3435                 rc = mdb_cursor_first(mc, key, data);
3436                 break;
3437         case MDB_FIRST_DUP:
3438                 if (data == NULL ||
3439                         !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3440                         !(mc->mc_flags & C_INITIALIZED) ||
3441                         !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3442                         rc = EINVAL;
3443                         break;
3444                 }
3445                 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3446                 break;
3447         case MDB_LAST:
3448                 rc = mdb_cursor_last(mc, key, data);
3449                 break;
3450         case MDB_LAST_DUP:
3451                 if (data == NULL ||
3452                         !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3453                         !(mc->mc_flags & C_INITIALIZED) ||
3454                         !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3455                         rc = EINVAL;
3456                         break;
3457                 }
3458                 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3459                 break;
3460         default:
3461                 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3462                 rc = EINVAL;
3463                 break;
3464         }
3465
3466         return rc;
3467 }
3468
3469 /** Touch all the pages in the cursor stack.
3470  *      Makes sure all the pages are writable, before attempting a write operation.
3471  * @param[in] mc The cursor to operate on.
3472  */
3473 static int
3474 mdb_cursor_touch(MDB_cursor *mc)
3475 {
3476         int rc;
3477
3478         if (mc->mc_dbi > MAIN_DBI && !mc->mc_dbx->md_dirty) {
3479                 MDB_cursor mc2;
3480                 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3481                 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
3482                 if (rc)
3483                          return rc;
3484                 mc->mc_dbx->md_dirty = 1;
3485         }
3486         for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3487                 if (!F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) {
3488                         rc = mdb_page_touch(mc);
3489                         if (rc)
3490                                 return rc;
3491                         if (!mc->mc_top) {
3492                                 mc->mc_db->md_root =
3493                                         mc->mc_pg[mc->mc_top]->mp_pgno;
3494                         }
3495                 }
3496         }
3497         mc->mc_top = mc->mc_snum-1;
3498         return MDB_SUCCESS;
3499 }
3500
3501 int
3502 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3503     unsigned int flags)
3504 {
3505         MDB_node        *leaf;
3506         MDB_val xdata, *rdata, dkey;
3507         MDB_page        *fp;
3508         MDB_db dummy;
3509         int do_sub = 0;
3510         size_t nsize;
3511         int rc, rc2;
3512         char pbuf[PAGESIZE];
3513         char dbuf[MAXKEYSIZE+1];
3514         DKBUF;
3515
3516         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3517                 return EACCES;
3518
3519         DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3520                 mc->mc_dbi, DKEY(key), key->mv_size, data->mv_size);
3521
3522         dkey.mv_size = 0;
3523
3524         if (flags == MDB_CURRENT) {
3525                 if (!(mc->mc_flags & C_INITIALIZED))
3526                         return EINVAL;
3527                 rc = MDB_SUCCESS;
3528         } else if (mc->mc_db->md_root == P_INVALID) {
3529                 MDB_page *np;
3530                 /* new database, write a root leaf page */
3531                 DPUTS("allocating new root leaf page");
3532                 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
3533                         return ENOMEM;
3534                 }
3535                 mc->mc_snum = 0;
3536                 mdb_cursor_push(mc, np);
3537                 mc->mc_db->md_root = np->mp_pgno;
3538                 mc->mc_db->md_depth++;
3539                 mc->mc_dbx->md_dirty = 1;
3540                 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3541                         == MDB_DUPFIXED)
3542                         np->mp_flags |= P_LEAF2;
3543                 mc->mc_flags |= C_INITIALIZED;
3544                 rc = MDB_NOTFOUND;
3545                 goto top;
3546         } else {
3547                 int exact = 0;
3548                 MDB_val d2;
3549                 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3550                 if (flags == MDB_NOOVERWRITE && rc == 0) {
3551                         DPRINTF("duplicate key [%s]", DKEY(key));
3552                         *data = d2;
3553                         return MDB_KEYEXIST;
3554                 }
3555                 if (rc && rc != MDB_NOTFOUND)
3556                         return rc;
3557         }
3558
3559         /* Cursor is positioned, now make sure all pages are writable */
3560         rc2 = mdb_cursor_touch(mc);
3561         if (rc2)
3562                 return rc2;
3563
3564 top:
3565         /* The key already exists */
3566         if (rc == MDB_SUCCESS) {
3567                 /* there's only a key anyway, so this is a no-op */
3568                 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3569                         unsigned int ksize = mc->mc_db->md_pad;
3570                         if (key->mv_size != ksize)
3571                                 return EINVAL;
3572                         if (flags == MDB_CURRENT) {
3573                                 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
3574                                 memcpy(ptr, key->mv_data, ksize);
3575                         }
3576                         return MDB_SUCCESS;
3577                 }
3578
3579                 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3580
3581                 /* DB has dups? */
3582                 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
3583                         /* Was a single item before, must convert now */
3584                         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3585                                 /* Just overwrite the current item */
3586                                 if (flags == MDB_CURRENT)
3587                                         goto current;
3588
3589                                 /* create a fake page for the dup items */
3590                                 dkey.mv_size = NODEDSZ(leaf);
3591                                 dkey.mv_data = NODEDATA(leaf);
3592                                 /* data matches, ignore it */
3593                                 if (!mc->mc_dbx->md_dcmp(data, &dkey))
3594                                         return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3595                                 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
3596                                 dkey.mv_data = dbuf;
3597                                 fp = (MDB_page *)pbuf;
3598                                 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
3599                                 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
3600                                 fp->mp_lower = PAGEHDRSZ;
3601                                 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
3602                                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3603                                         fp->mp_flags |= P_LEAF2;
3604                                         fp->mp_pad = data->mv_size;
3605                                 } else {
3606                                         fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
3607                                                 (dkey.mv_size & 1) + (data->mv_size & 1);
3608                                 }
3609                                 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3610                                 do_sub = 1;
3611                                 rdata = &xdata;
3612                                 xdata.mv_size = fp->mp_upper;
3613                                 xdata.mv_data = pbuf;
3614                                 flags |= F_DUPDATA;
3615                                 goto new_sub;
3616                         }
3617                         if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
3618                                 /* See if we need to convert from fake page to subDB */
3619                                 MDB_page *mp;
3620                                 unsigned int offset;
3621                                 unsigned int i;
3622
3623                                 fp = NODEDATA(leaf);
3624                                 if (flags == MDB_CURRENT) {
3625                                         fp->mp_flags |= P_DIRTY;
3626                                         fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
3627                                         mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
3628                                         flags |= F_DUPDATA;
3629                                         goto put_sub;
3630                                 }
3631                                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3632                                         offset = fp->mp_pad;
3633                                 } else {
3634                                         offset = NODESIZE + sizeof(indx_t) + data->mv_size;
3635                                 }
3636                                 offset += offset & 1;
3637                                 if (NODEDSZ(leaf) + offset >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
3638                                         /* yes, convert it */
3639                                         dummy.md_flags = 0;
3640                                         if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3641                                                 dummy.md_pad = fp->mp_pad;
3642                                                 dummy.md_flags = MDB_DUPFIXED;
3643                                                 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
3644                                                         dummy.md_flags |= MDB_INTEGERKEY;
3645                                         }
3646                                         dummy.md_depth = 1;
3647                                         dummy.md_branch_pages = 0;
3648                                         dummy.md_leaf_pages = 1;
3649                                         dummy.md_overflow_pages = 0;
3650                                         dummy.md_entries = NUMKEYS(fp);
3651                                         rdata = &xdata;
3652                                         xdata.mv_size = sizeof(MDB_db);
3653                                         xdata.mv_data = &dummy;
3654                                         mp = mdb_page_alloc(mc, 1);
3655                                         if (!mp)
3656                                                 return ENOMEM;
3657                                         offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
3658                                         flags |= F_DUPDATA|F_SUBDATA;
3659                                         dummy.md_root = mp->mp_pgno;
3660                                 } else {
3661                                         /* no, just grow it */
3662                                         rdata = &xdata;
3663                                         xdata.mv_size = NODEDSZ(leaf) + offset;
3664                                         xdata.mv_data = pbuf;
3665                                         mp = (MDB_page *)pbuf;
3666                                         mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
3667                                         flags |= F_DUPDATA;
3668                                 }
3669                                 mp->mp_flags = fp->mp_flags | P_DIRTY;
3670                                 mp->mp_pad   = fp->mp_pad;
3671                                 mp->mp_lower = fp->mp_lower;
3672                                 mp->mp_upper = fp->mp_upper + offset;
3673                                 if (IS_LEAF2(fp)) {
3674                                         memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
3675                                 } else {
3676                                         nsize = NODEDSZ(leaf) - fp->mp_upper;
3677                                         memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
3678                                         for (i=0; i<NUMKEYS(fp); i++)
3679                                                 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
3680                                 }
3681                                 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3682                                 do_sub = 1;
3683                                 goto new_sub;
3684                         }
3685                         /* data is on sub-DB, just store it */
3686                         flags |= F_DUPDATA|F_SUBDATA;
3687                         goto put_sub;
3688                 }
3689 current:
3690                 /* same size, just replace it */
3691                 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
3692                         NODEDSZ(leaf) == data->mv_size) {
3693                         memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3694                         goto done;
3695                 }
3696                 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3697         } else {
3698                 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
3699         }
3700
3701         rdata = data;
3702
3703 new_sub:
3704         nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
3705         if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
3706                 rc = mdb_page_split(mc, key, rdata, P_INVALID);
3707         } else {
3708                 /* There is room already in this leaf page. */
3709                 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, 0);
3710         }
3711
3712         if (rc != MDB_SUCCESS)
3713                 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
3714         else {
3715                 /* Remember if we just added a subdatabase */
3716                 if (flags & (F_SUBDATA|F_DUPDATA)) {
3717                         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3718                         leaf->mn_flags |= (flags & (F_SUBDATA|F_DUPDATA));
3719                 }
3720
3721                 /* Now store the actual data in the child DB. Note that we're
3722                  * storing the user data in the keys field, so there are strict
3723                  * size limits on dupdata. The actual data fields of the child
3724                  * DB are all zero size.
3725                  */
3726                 if (do_sub) {
3727                         MDB_db *db;
3728                         int xflags;
3729 put_sub:
3730                         xdata.mv_size = 0;
3731                         xdata.mv_data = "";
3732                         if (flags & MDB_CURRENT) {
3733                                 xflags = MDB_CURRENT;
3734                         } else {
3735                                 mdb_xcursor_init1(mc, leaf);
3736                                 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
3737                         }
3738                         /* converted, write the original data first */
3739                         if (dkey.mv_size) {
3740                                 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
3741                                 if (rc)
3742                                         return rc;
3743                         }
3744                         rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
3745                         if (flags & F_SUBDATA) {
3746                                 db = NODEDATA(leaf);
3747                                 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
3748                         }
3749                 }
3750                 /* sub-writes might have failed so check rc again.
3751                  * Don't increment count if we just replaced an existing item.
3752                  */
3753                 if (!rc && !(flags & MDB_CURRENT))
3754                         mc->mc_db->md_entries++;
3755         }
3756 done:
3757         return rc;
3758 }
3759
3760 int
3761 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
3762 {
3763         MDB_node        *leaf;
3764         int rc;
3765
3766         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3767                 return EACCES;
3768
3769         if (!mc->mc_flags & C_INITIALIZED)
3770                 return EINVAL;
3771
3772         rc = mdb_cursor_touch(mc);
3773         if (rc)
3774                 return rc;
3775
3776         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3777
3778         if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3779                 if (flags != MDB_NODUPDATA) {
3780                         if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
3781                                 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
3782                         }
3783                         rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
3784                         /* If sub-DB still has entries, we're done */
3785                         if (mc->mc_xcursor->mx_db.md_root != P_INVALID) {
3786                                 if (leaf->mn_flags & F_SUBDATA) {
3787                                         /* update subDB info */
3788                                         MDB_db *db = NODEDATA(leaf);
3789                                         memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
3790                                 } else {
3791                                         /* shrink fake page */
3792                                         mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3793                                 }
3794                                 mc->mc_db->md_entries--;
3795                                 return rc;
3796                         }
3797                         /* otherwise fall thru and delete the sub-DB */
3798                 }
3799
3800                 if (leaf->mn_flags & F_SUBDATA) {
3801                         /* add all the child DB's pages to the free list */
3802                         rc = mdb_page_search(&mc->mc_xcursor->mx_cursor, NULL, 0);
3803                         if (rc == MDB_SUCCESS) {
3804                                 MDB_node *ni;
3805                                 MDB_cursor *mx;
3806                                 unsigned int i;
3807
3808                                 mx = &mc->mc_xcursor->mx_cursor;
3809                                 mc->mc_db->md_entries -=
3810                                         mx->mc_db->md_entries;
3811
3812                                 mdb_cursor_pop(mx);
3813                                 while (mx->mc_snum > 0) {
3814                                         for (i=0; i<NUMKEYS(mx->mc_pg[mx->mc_top]); i++) {
3815                                                 pgno_t pg;
3816                                                 ni = NODEPTR(mx->mc_pg[mx->mc_top], i);
3817                                                 pg = NODEPGNO(ni);
3818                                                 /* free it */
3819                                                 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
3820                                         }
3821                                         if (!mx->mc_top)
3822                                                 break;
3823                                         rc = mdb_cursor_sibling(mx, 1);
3824                                         if (rc) {
3825                                                 /* no more siblings, go back to beginning
3826                                                  * of previous level. (stack was already popped
3827                                                  * by mdb_cursor_sibling)
3828                                                  */
3829                                                 for (i=1; i<mx->mc_top; i++) {
3830                                                         pgno_t pg;
3831                                                         ni = NODEPTR(mx->mc_pg[i-1],0);
3832                                                         pg = NODEPGNO(ni);
3833                                                         if ((rc = mdb_page_get(mc->mc_txn, pg, &mx->mc_pg[i])))
3834                                                                 break;
3835                                                 }
3836                                         }
3837                                 }
3838                                 /* free it */
3839                                 mdb_midl_append(mc->mc_txn->mt_free_pgs,
3840                                         mx->mc_db->md_root);
3841                         }
3842                 }
3843         }
3844
3845         return mdb_cursor_del0(mc, leaf);
3846 }
3847
3848 /** Allocate and initialize new pages for a database.
3849  * @param[in] mc a cursor on the database being added to.
3850  * @param[in] flags flags defining what type of page is being allocated.
3851  * @param[in] num the number of pages to allocate. This is usually 1,
3852  * unless allocating overflow pages for a large record.
3853  * @return Address of a page, or NULL on failure.
3854  */
3855 static MDB_page *
3856 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
3857 {
3858         MDB_page        *np;
3859
3860         if ((np = mdb_page_alloc(mc, num)) == NULL)
3861                 return NULL;
3862         DPRINTF("allocated new mpage %zu, page size %u",
3863             np->mp_pgno, mc->mc_txn->mt_env->me_psize);
3864         np->mp_flags = flags | P_DIRTY;
3865         np->mp_lower = PAGEHDRSZ;
3866         np->mp_upper = mc->mc_txn->mt_env->me_psize;
3867
3868         if (IS_BRANCH(np))
3869                 mc->mc_db->md_branch_pages++;
3870         else if (IS_LEAF(np))
3871                 mc->mc_db->md_leaf_pages++;
3872         else if (IS_OVERFLOW(np)) {
3873                 mc->mc_db->md_overflow_pages += num;
3874                 np->mp_pages = num;
3875         }
3876
3877         return np;
3878 }
3879
3880 /** Calculate the size of a leaf node.
3881  * The size depends on the environment's page size; if a data item
3882  * is too large it will be put onto an overflow page and the node
3883  * size will only include the key and not the data. Sizes are always
3884  * rounded up to an even number of bytes, to guarantee 2-byte alignment
3885  * of the #MDB_node headers.
3886  * @param[in] env The environment handle.
3887  * @param[in] key The key for the node.
3888  * @param[in] data The data for the node.
3889  * @return The number of bytes needed to store the node.
3890  */
3891 static size_t
3892 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
3893 {
3894         size_t           sz;
3895
3896         sz = LEAFSIZE(key, data);
3897         if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
3898                 /* put on overflow page */
3899                 sz -= data->mv_size - sizeof(pgno_t);
3900         }
3901         sz += sz & 1;
3902
3903         return sz + sizeof(indx_t);
3904 }
3905
3906 /** Calculate the size of a branch node.
3907  * The size should depend on the environment's page size but since
3908  * we currently don't support spilling large keys onto overflow
3909  * pages, it's simply the size of the #MDB_node header plus the
3910  * size of the key. Sizes are always rounded up to an even number
3911  * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
3912  * @param[in] env The environment handle.
3913  * @param[in] key The key for the node.
3914  * @return The number of bytes needed to store the node.
3915  */
3916 static size_t
3917 mdb_branch_size(MDB_env *env, MDB_val *key)
3918 {
3919         size_t           sz;
3920
3921         sz = INDXSIZE(key);
3922         if (sz >= env->me_psize / MDB_MINKEYS) {
3923                 /* put on overflow page */
3924                 /* not implemented */
3925                 /* sz -= key->size - sizeof(pgno_t); */
3926         }
3927
3928         return sz + sizeof(indx_t);
3929 }
3930
3931 /** Add a node to the page pointed to by the cursor.
3932  * @param[in] mc The cursor for this operation.
3933  * @param[in] indx The index on the page where the new node should be added.
3934  * @param[in] key The key for the new node.
3935  * @param[in] data The data for the new node, if any.
3936  * @param[in] pgno The page number, if adding a branch node.
3937  * @param[in] flags Flags for the node.
3938  * @return 0 on success, non-zero on failure. Possible errors are:
3939  * <ul>
3940  *      <li>ENOMEM - failed to allocate overflow pages for the node.
3941  *      <li>ENOSPC - there is insufficient room in the page. This error
3942  *      should never happen since all callers already calculate the
3943  *      page's free space before calling this function.
3944  * </ul>
3945  */
3946 static int
3947 mdb_node_add(MDB_cursor *mc, indx_t indx,
3948     MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
3949 {
3950         unsigned int     i;
3951         size_t           node_size = NODESIZE;
3952         indx_t           ofs;
3953         MDB_node        *node;
3954         MDB_page        *mp = mc->mc_pg[mc->mc_top];
3955         MDB_page        *ofp = NULL;            /* overflow page */
3956         DKBUF;
3957
3958         assert(mp->mp_upper >= mp->mp_lower);
3959
3960         DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
3961             IS_LEAF(mp) ? "leaf" : "branch",
3962                 IS_SUBP(mp) ? "sub-" : "",
3963             mp->mp_pgno, indx, data ? data->mv_size : 0,
3964                 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
3965
3966         if (IS_LEAF2(mp)) {
3967                 /* Move higher keys up one slot. */
3968                 int ksize = mc->mc_db->md_pad, dif;
3969                 char *ptr = LEAF2KEY(mp, indx, ksize);
3970                 dif = NUMKEYS(mp) - indx;
3971                 if (dif > 0)
3972                         memmove(ptr+ksize, ptr, dif*ksize);
3973                 /* insert new key */
3974                 memcpy(ptr, key->mv_data, ksize);
3975
3976                 /* Just using these for counting */
3977                 mp->mp_lower += sizeof(indx_t);
3978                 mp->mp_upper -= ksize - sizeof(indx_t);
3979                 return MDB_SUCCESS;
3980         }
3981
3982         if (key != NULL)
3983                 node_size += key->mv_size;
3984
3985         if (IS_LEAF(mp)) {
3986                 assert(data);
3987                 if (F_ISSET(flags, F_BIGDATA)) {
3988                         /* Data already on overflow page. */
3989                         node_size += sizeof(pgno_t);
3990                 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
3991                         int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
3992                         /* Put data on overflow page. */
3993                         DPRINTF("data size is %zu, put on overflow page",
3994                             data->mv_size);
3995                         node_size += sizeof(pgno_t);
3996                         if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
3997                                 return ENOMEM;
3998                         DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
3999                         flags |= F_BIGDATA;
4000                 } else {
4001                         node_size += data->mv_size;
4002                 }
4003         }
4004         node_size += node_size & 1;
4005
4006         if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4007                 DPRINTF("not enough room in page %zu, got %u ptrs",
4008                     mp->mp_pgno, NUMKEYS(mp));
4009                 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4010                     mp->mp_upper - mp->mp_lower);
4011                 DPRINTF("node size = %zu", node_size);
4012                 return ENOSPC;
4013         }
4014
4015         /* Move higher pointers up one slot. */
4016         for (i = NUMKEYS(mp); i > indx; i--)
4017                 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4018
4019         /* Adjust free space offsets. */
4020         ofs = mp->mp_upper - node_size;
4021         assert(ofs >= mp->mp_lower + sizeof(indx_t));
4022         mp->mp_ptrs[indx] = ofs;
4023         mp->mp_upper = ofs;
4024         mp->mp_lower += sizeof(indx_t);
4025
4026         /* Write the node data. */
4027         node = NODEPTR(mp, indx);
4028         node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4029         node->mn_flags = flags;
4030         if (IS_LEAF(mp))
4031                 SETDSZ(node,data->mv_size);
4032         else
4033                 SETPGNO(node,pgno);
4034
4035         if (key)
4036                 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4037
4038         if (IS_LEAF(mp)) {
4039                 assert(key);
4040                 if (ofp == NULL) {
4041                         if (F_ISSET(flags, F_BIGDATA))
4042                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
4043                                     sizeof(pgno_t));
4044                         else
4045                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
4046                                     data->mv_size);
4047                 } else {
4048                         memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4049                             sizeof(pgno_t));
4050                         memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4051                 }
4052         }
4053
4054         return MDB_SUCCESS;
4055 }
4056
4057 /** Delete the specified node from a page.
4058  * @param[in] mp The page to operate on.
4059  * @param[in] indx The index of the node to delete.
4060  * @param[in] ksize The size of a node. Only used if the page is
4061  * part of a #MDB_DUPFIXED database.
4062  */
4063 static void
4064 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4065 {
4066         unsigned int     sz;
4067         indx_t           i, j, numkeys, ptr;
4068         MDB_node        *node;
4069         char            *base;
4070
4071         DPRINTF("delete node %u on %s page %zu", indx,
4072             IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
4073         assert(indx < NUMKEYS(mp));
4074
4075         if (IS_LEAF2(mp)) {
4076                 int x = NUMKEYS(mp) - 1 - indx;
4077                 base = LEAF2KEY(mp, indx, ksize);
4078                 if (x)
4079                         memmove(base, base + ksize, x * ksize);
4080                 mp->mp_lower -= sizeof(indx_t);
4081                 mp->mp_upper += ksize - sizeof(indx_t);
4082                 return;
4083         }
4084
4085         node = NODEPTR(mp, indx);
4086         sz = NODESIZE + node->mn_ksize;
4087         if (IS_LEAF(mp)) {
4088                 if (F_ISSET(node->mn_flags, F_BIGDATA))
4089                         sz += sizeof(pgno_t);
4090                 else
4091                         sz += NODEDSZ(node);
4092         }
4093         sz += sz & 1;
4094
4095         ptr = mp->mp_ptrs[indx];
4096         numkeys = NUMKEYS(mp);
4097         for (i = j = 0; i < numkeys; i++) {
4098                 if (i != indx) {
4099                         mp->mp_ptrs[j] = mp->mp_ptrs[i];
4100                         if (mp->mp_ptrs[i] < ptr)
4101                                 mp->mp_ptrs[j] += sz;
4102                         j++;
4103                 }
4104         }
4105
4106         base = (char *)mp + mp->mp_upper;
4107         memmove(base + sz, base, ptr - mp->mp_upper);
4108
4109         mp->mp_lower -= sizeof(indx_t);
4110         mp->mp_upper += sz;
4111 }
4112
4113 /** Compact the main page after deleting a node on a subpage.
4114  * @param[in] mp The main page to operate on.
4115  * @param[in] indx The index of the subpage on the main page.
4116  */
4117 static void
4118 mdb_node_shrink(MDB_page *mp, indx_t indx)
4119 {
4120         MDB_node *node;
4121         MDB_page *sp, *xp;
4122         char *base;
4123         int osize, nsize;
4124         int delta;
4125         indx_t           i, numkeys, ptr;
4126
4127         node = NODEPTR(mp, indx);
4128         sp = (MDB_page *)NODEDATA(node);
4129         osize = NODEDSZ(node);
4130
4131         delta = sp->mp_upper - sp->mp_lower;
4132         SETDSZ(node, osize - delta);
4133         xp = (MDB_page *)((char *)sp + delta);
4134
4135         /* shift subpage upward */
4136         if (IS_LEAF2(sp)) {
4137                 nsize = NUMKEYS(sp) * sp->mp_pad;
4138                 memmove(METADATA(xp), METADATA(sp), nsize);
4139         } else {
4140                 int i;
4141                 nsize = osize - sp->mp_upper;
4142                 numkeys = NUMKEYS(sp);
4143                 for (i=numkeys-1; i>=0; i--)
4144                         xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4145         }
4146         xp->mp_upper = sp->mp_lower;
4147         xp->mp_lower = sp->mp_lower;
4148         xp->mp_flags = sp->mp_flags;
4149         xp->mp_pad = sp->mp_pad;
4150         xp->mp_pgno = mp->mp_pgno;
4151
4152         /* shift lower nodes upward */
4153         ptr = mp->mp_ptrs[indx];
4154         numkeys = NUMKEYS(mp);
4155         for (i = 0; i < numkeys; i++) {
4156                 if (mp->mp_ptrs[i] <= ptr)
4157                         mp->mp_ptrs[i] += delta;
4158         }
4159
4160         base = (char *)mp + mp->mp_upper;
4161         memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4162         mp->mp_upper += delta;
4163 }
4164
4165 /** Initial setup of a sorted-dups cursor.
4166  * Sorted duplicates are implemented as a sub-database for the given key.
4167  * The duplicate data items are actually keys of the sub-database.
4168  * Operations on the duplicate data items are performed using a sub-cursor
4169  * initialized when the sub-database is first accessed. This function does
4170  * the preliminary setup of the sub-cursor, filling in the fields that
4171  * depend only on the parent DB.
4172  * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4173  */
4174 static void
4175 mdb_xcursor_init0(MDB_cursor *mc)
4176 {
4177         MDB_xcursor *mx = mc->mc_xcursor;
4178
4179         mx->mx_cursor.mc_xcursor = NULL;
4180         mx->mx_cursor.mc_txn = mc->mc_txn;
4181         mx->mx_cursor.mc_db = &mx->mx_db;
4182         mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4183         mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4184         mx->mx_dbx.md_parent = mc->mc_dbi;
4185         mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4186         mx->mx_dbx.md_dcmp = NULL;
4187         mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4188         mx->mx_dbx.md_dirty = 0;
4189 }
4190
4191 /** Final setup of a sorted-dups cursor.
4192  *      Sets up the fields that depend on the data from the main cursor.
4193  * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4194  * @param[in] node The data containing the #MDB_db record for the
4195  * sorted-dup database.
4196  */
4197 static void
4198 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4199 {
4200         MDB_xcursor *mx = mc->mc_xcursor;
4201
4202         if (node->mn_flags & F_SUBDATA) {
4203                 MDB_db *db = NODEDATA(node);
4204                 mx->mx_db = *db;
4205                 mx->mx_cursor.mc_snum = 0;
4206                 mx->mx_cursor.mc_flags = 0;
4207         } else {
4208                 MDB_page *fp = NODEDATA(node);
4209                 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
4210                 mx->mx_db.md_flags = 0;
4211                 mx->mx_db.md_depth = 1;
4212                 mx->mx_db.md_branch_pages = 0;
4213                 mx->mx_db.md_leaf_pages = 1;
4214                 mx->mx_db.md_overflow_pages = 0;
4215                 mx->mx_db.md_entries = NUMKEYS(fp);
4216                 mx->mx_db.md_root = fp->mp_pgno;
4217                 mx->mx_cursor.mc_snum = 1;
4218                 mx->mx_cursor.mc_flags = C_INITIALIZED;
4219                 mx->mx_cursor.mc_top = 0;
4220                 mx->mx_cursor.mc_pg[0] = fp;
4221                 mx->mx_cursor.mc_ki[0] = 0;
4222                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4223                         mx->mx_db.md_flags = MDB_DUPFIXED;
4224                         mx->mx_db.md_pad = fp->mp_pad;
4225                         if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4226                                 mx->mx_db.md_flags |= MDB_INTEGERKEY;
4227                 }
4228         }
4229         DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
4230                 mx->mx_db.md_root);
4231         if (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY))
4232                 mx->mx_dbx.md_dirty = 1;
4233         mx->mx_dbx.md_name.mv_data = NODEKEY(node);
4234         mx->mx_dbx.md_name.mv_size = node->mn_ksize;
4235         if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
4236                 mx->mx_dbx.md_cmp = mdb_cmp_long;
4237 }
4238
4239 /** Initialize a cursor for a given transaction and database. */
4240 static void
4241 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
4242 {
4243         mc->mc_dbi = dbi;
4244         mc->mc_txn = txn;
4245         mc->mc_db = &txn->mt_dbs[dbi];
4246         mc->mc_dbx = &txn->mt_dbxs[dbi];
4247         mc->mc_snum = 0;
4248         mc->mc_flags = 0;
4249         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4250                 assert(mx != NULL);
4251                 mc->mc_xcursor = mx;
4252                 mdb_xcursor_init0(mc);
4253         } else {
4254                 mc->mc_xcursor = NULL;
4255         }
4256 }
4257
4258 int
4259 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
4260 {
4261         MDB_cursor      *mc;
4262         MDB_xcursor     *mx = NULL;
4263         size_t size = sizeof(MDB_cursor);
4264
4265         if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
4266                 return EINVAL;
4267
4268         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
4269                 size += sizeof(MDB_xcursor);
4270
4271         if ((mc = malloc(size)) != NULL) {
4272                 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4273                         mx = (MDB_xcursor *)(mc + 1);
4274                 }
4275                 mdb_cursor_init(mc, txn, dbi, mx);
4276         } else {
4277                 return ENOMEM;
4278         }
4279
4280         *ret = mc;
4281
4282         return MDB_SUCCESS;
4283 }
4284
4285 /* Return the count of duplicate data items for the current key */
4286 int
4287 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
4288 {
4289         MDB_node        *leaf;
4290
4291         if (mc == NULL || countp == NULL)
4292                 return EINVAL;
4293
4294         if (!(mc->mc_db->md_flags & MDB_DUPSORT))
4295                 return EINVAL;
4296
4297         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4298         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4299                 *countp = 1;
4300         } else {
4301                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
4302                         return EINVAL;
4303
4304                 *countp = mc->mc_xcursor->mx_db.md_entries;
4305         }
4306         return MDB_SUCCESS;
4307 }
4308
4309 void
4310 mdb_cursor_close(MDB_cursor *mc)
4311 {
4312         if (mc != NULL) {
4313                 free(mc);
4314         }
4315 }
4316
4317 /** Replace the key for a node with a new key.
4318  * @param[in] mp The page containing the node to operate on.
4319  * @param[in] indx The index of the node to operate on.
4320  * @param[in] key The new key to use.
4321  * @return 0 on success, non-zero on failure.
4322  */
4323 static int
4324 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
4325 {
4326         indx_t                   ptr, i, numkeys;
4327         int                      delta;
4328         size_t                   len;
4329         MDB_node                *node;
4330         char                    *base;
4331         DKBUF;
4332
4333         node = NODEPTR(mp, indx);
4334         ptr = mp->mp_ptrs[indx];
4335         DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %zu",
4336             indx, ptr,
4337             (int)node->mn_ksize, (char *)NODEKEY(node),
4338                 DKEY(key),
4339             mp->mp_pgno);
4340
4341         delta = key->mv_size - node->mn_ksize;
4342         if (delta) {
4343                 if (delta > 0 && SIZELEFT(mp) < delta) {
4344                         DPRINTF("OUCH! Not enough room, delta = %d", delta);
4345                         return ENOSPC;
4346                 }
4347
4348                 numkeys = NUMKEYS(mp);
4349                 for (i = 0; i < numkeys; i++) {
4350                         if (mp->mp_ptrs[i] <= ptr)
4351                                 mp->mp_ptrs[i] -= delta;
4352                 }
4353
4354                 base = (char *)mp + mp->mp_upper;
4355                 len = ptr - mp->mp_upper + NODESIZE;
4356                 memmove(base - delta, base, len);
4357                 mp->mp_upper -= delta;
4358
4359                 node = NODEPTR(mp, indx);
4360                 node->mn_ksize = key->mv_size;
4361         }
4362
4363         memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4364
4365         return MDB_SUCCESS;
4366 }
4367
4368 /** Move a node from csrc to cdst.
4369  */
4370 static int
4371 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
4372 {
4373         int                      rc;
4374         MDB_node                *srcnode;
4375         MDB_val          key, data;
4376         DKBUF;
4377
4378         /* Mark src and dst as dirty. */
4379         if ((rc = mdb_page_touch(csrc)) ||
4380             (rc = mdb_page_touch(cdst)))
4381                 return rc;
4382
4383         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4384                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);        /* fake */
4385                 key.mv_size = csrc->mc_db->md_pad;
4386                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4387                 data.mv_size = 0;
4388                 data.mv_data = NULL;
4389         } else {
4390                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
4391                 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4392                         unsigned int snum = csrc->mc_snum;
4393                         MDB_node *s2;
4394                         /* must find the lowest key below src */
4395                         mdb_page_search_root(csrc, NULL, 0);
4396                         s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4397                         key.mv_size = NODEKSZ(s2);
4398                         key.mv_data = NODEKEY(s2);
4399                         csrc->mc_snum = snum--;
4400                         csrc->mc_top = snum;
4401                 } else {
4402                         key.mv_size = NODEKSZ(srcnode);
4403                         key.mv_data = NODEKEY(srcnode);
4404                 }
4405                 data.mv_size = NODEDSZ(srcnode);
4406                 data.mv_data = NODEDATA(srcnode);
4407         }
4408         DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
4409             IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
4410             csrc->mc_ki[csrc->mc_top],
4411                 DKEY(&key),
4412             csrc->mc_pg[csrc->mc_top]->mp_pgno,
4413             cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
4414
4415         /* Add the node to the destination page.
4416          */
4417         rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
4418             srcnode->mn_flags);
4419         if (rc != MDB_SUCCESS)
4420                 return rc;
4421
4422         /* Delete the node from the source page.
4423          */
4424         mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4425
4426         /* Update the parent separators.
4427          */
4428         if (csrc->mc_ki[csrc->mc_top] == 0) {
4429                 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
4430                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4431                                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
4432                         } else {
4433                                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4434                                 key.mv_size = NODEKSZ(srcnode);
4435                                 key.mv_data = NODEKEY(srcnode);
4436                         }
4437                         DPRINTF("update separator for source page %zu to [%s]",
4438                                 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
4439                         if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
4440                                 &key)) != MDB_SUCCESS)
4441                                 return rc;
4442                 }
4443                 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4444                         MDB_val  nullkey;
4445                         nullkey.mv_size = 0;
4446                         assert(mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey) == MDB_SUCCESS);
4447                 }
4448         }
4449
4450         if (cdst->mc_ki[cdst->mc_top] == 0) {
4451                 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
4452                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4453                                 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
4454                         } else {
4455                                 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
4456                                 key.mv_size = NODEKSZ(srcnode);
4457                                 key.mv_data = NODEKEY(srcnode);
4458                         }
4459                         DPRINTF("update separator for destination page %zu to [%s]",
4460                                 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
4461                         if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
4462                                 &key)) != MDB_SUCCESS)
4463                                 return rc;
4464                 }
4465                 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
4466                         MDB_val  nullkey;
4467                         nullkey.mv_size = 0;
4468                         assert(mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey) == MDB_SUCCESS);
4469                 }
4470         }
4471
4472         return MDB_SUCCESS;
4473 }
4474
4475 /** Merge one page into another.
4476  *  The nodes from the page pointed to by \b csrc will
4477  *      be copied to the page pointed to by \b cdst and then
4478  *      the \b csrc page will be freed.
4479  * @param[in] csrc Cursor pointing to the source page.
4480  * @param[in] cdst Cursor pointing to the destination page.
4481  */
4482 static int
4483 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
4484 {
4485         int                      rc;
4486         indx_t                   i, j;
4487         MDB_node                *srcnode;
4488         MDB_val          key, data;
4489
4490         DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
4491                 cdst->mc_pg[cdst->mc_top]->mp_pgno);
4492
4493         assert(csrc->mc_snum > 1);      /* can't merge root page */
4494         assert(cdst->mc_snum > 1);
4495
4496         /* Mark dst as dirty. */
4497         if ((rc = mdb_page_touch(cdst)))
4498                 return rc;
4499
4500         /* Move all nodes from src to dst.
4501          */
4502         j = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
4503         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4504                 key.mv_size = csrc->mc_db->md_pad;
4505                 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
4506                 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4507                         rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
4508                         if (rc != MDB_SUCCESS)
4509                                 return rc;
4510                         key.mv_data = (char *)key.mv_data + key.mv_size;
4511                 }
4512         } else {
4513                 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4514                         srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
4515
4516                         key.mv_size = srcnode->mn_ksize;
4517                         key.mv_data = NODEKEY(srcnode);
4518                         data.mv_size = NODEDSZ(srcnode);
4519                         data.mv_data = NODEDATA(srcnode);
4520                         rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
4521                         if (rc != MDB_SUCCESS)
4522                                 return rc;
4523                 }
4524         }
4525
4526         DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
4527             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);
4528
4529         /* Unlink the src page from parent and add to free list.
4530          */
4531         mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
4532         if (csrc->mc_ki[csrc->mc_top-1] == 0) {
4533                 key.mv_size = 0;
4534                 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
4535                         return rc;
4536         }
4537
4538         mdb_midl_append(csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
4539         if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
4540                 csrc->mc_db->md_leaf_pages--;
4541         else
4542                 csrc->mc_db->md_branch_pages--;
4543         mdb_cursor_pop(csrc);
4544
4545         return mdb_rebalance(csrc);
4546 }
4547
4548 /** Copy the contents of a cursor.
4549  * @param[in] csrc The cursor to copy from.
4550  * @param[out] cdst The cursor to copy to.
4551  */
4552 static void
4553 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
4554 {
4555         unsigned int i;
4556
4557         cdst->mc_txn = csrc->mc_txn;
4558         cdst->mc_dbi = csrc->mc_dbi;
4559         cdst->mc_db  = csrc->mc_db;
4560         cdst->mc_dbx = csrc->mc_dbx;
4561         cdst->mc_snum = csrc->mc_snum;
4562         cdst->mc_top = csrc->mc_top;
4563         cdst->mc_flags = csrc->mc_flags;
4564
4565         for (i=0; i<csrc->mc_snum; i++) {
4566                 cdst->mc_pg[i] = csrc->mc_pg[i];
4567                 cdst->mc_ki[i] = csrc->mc_ki[i];
4568         }
4569 }
4570
4571 /** Rebalance the tree after a delete operation.
4572  * @param[in] mc Cursor pointing to the page where rebalancing
4573  * should begin.
4574  * @return 0 on success, non-zero on failure.
4575  */
4576 static int
4577 mdb_rebalance(MDB_cursor *mc)
4578 {
4579         MDB_node        *node;
4580         int rc;
4581         unsigned int ptop;
4582         MDB_cursor      mn;
4583
4584         DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
4585             IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
4586             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);
4587
4588         if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
4589                 DPRINTF("no need to rebalance page %zu, above fill threshold",
4590                     mc->mc_pg[mc->mc_top]->mp_pgno);
4591                 return MDB_SUCCESS;
4592         }
4593
4594         if (mc->mc_snum < 2) {
4595                 if (NUMKEYS(mc->mc_pg[mc->mc_top]) == 0) {
4596                         DPUTS("tree is completely empty");
4597                         mc->mc_db->md_root = P_INVALID;
4598                         mc->mc_db->md_depth = 0;
4599                         mc->mc_db->md_leaf_pages = 0;
4600                         mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4601                         mc->mc_snum = 0;
4602                 } else if (IS_BRANCH(mc->mc_pg[mc->mc_top]) && NUMKEYS(mc->mc_pg[mc->mc_top]) == 1) {
4603                         DPUTS("collapsing root page!");
4604                         mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4605                         mc->mc_db->md_root = NODEPGNO(NODEPTR(mc->mc_pg[mc->mc_top], 0));
4606                         if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
4607                                 &mc->mc_pg[mc->mc_top])))
4608                                 return rc;
4609                         mc->mc_db->md_depth--;
4610                         mc->mc_db->md_branch_pages--;
4611                 } else
4612                         DPUTS("root page doesn't need rebalancing");
4613                 return MDB_SUCCESS;
4614         }
4615
4616         /* The parent (branch page) must have at least 2 pointers,
4617          * otherwise the tree is invalid.
4618          */
4619         ptop = mc->mc_top-1;
4620         assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
4621
4622         /* Leaf page fill factor is below the threshold.
4623          * Try to move keys from left or right neighbor, or
4624          * merge with a neighbor page.
4625          */
4626
4627         /* Find neighbors.
4628          */
4629         mdb_cursor_copy(mc, &mn);
4630         mn.mc_xcursor = NULL;
4631
4632         if (mc->mc_ki[ptop] == 0) {
4633                 /* We're the leftmost leaf in our parent.
4634                  */
4635                 DPUTS("reading right neighbor");
4636                 mn.mc_ki[ptop]++;
4637                 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4638                 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4639                         return rc;
4640                 mn.mc_ki[mn.mc_top] = 0;
4641                 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
4642         } else {
4643                 /* There is at least one neighbor to the left.
4644                  */
4645                 DPUTS("reading left neighbor");
4646                 mn.mc_ki[ptop]--;
4647                 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4648                 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4649                         return rc;
4650                 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
4651                 mc->mc_ki[mc->mc_top] = 0;
4652         }
4653
4654         DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
4655             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);
4656
4657         /* If the neighbor page is above threshold and has at least two
4658          * keys, move one key from it.
4659          *
4660          * Otherwise we should try to merge them.
4661          */
4662         if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
4663                 return mdb_node_move(&mn, mc);
4664         else { /* FIXME: if (has_enough_room()) */
4665                 mc->mc_flags &= ~C_INITIALIZED;
4666                 if (mc->mc_ki[ptop] == 0)
4667                         return mdb_page_merge(&mn, mc);
4668                 else
4669                         return mdb_page_merge(mc, &mn);
4670         }
4671 }
4672
4673 /** Complete a delete operation started by #mdb_cursor_del(). */
4674 static int
4675 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
4676 {
4677         int rc;
4678
4679         /* add overflow pages to free list */
4680         if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4681                 int i, ovpages;
4682                 pgno_t pg;
4683
4684                 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
4685                 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
4686                 for (i=0; i<ovpages; i++) {
4687                         DPRINTF("freed ov page %zu", pg);
4688                         mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
4689                         pg++;
4690                 }
4691         }
4692         mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
4693         mc->mc_db->md_entries--;
4694         rc = mdb_rebalance(mc);
4695         if (rc != MDB_SUCCESS)
4696                 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4697
4698         return rc;
4699 }
4700
4701 int
4702 mdb_del(MDB_txn *txn, MDB_dbi dbi,
4703     MDB_val *key, MDB_val *data)
4704 {
4705         MDB_cursor mc;
4706         MDB_xcursor mx;
4707         MDB_cursor_op op;
4708         MDB_val rdata, *xdata;
4709         int              rc, exact;
4710         DKBUF;
4711
4712         assert(key != NULL);
4713
4714         DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
4715
4716         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4717                 return EINVAL;
4718
4719         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4720                 return EACCES;
4721         }
4722
4723         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4724                 return EINVAL;
4725         }
4726
4727         mdb_cursor_init(&mc, txn, dbi, &mx);
4728
4729         exact = 0;
4730         if (data) {
4731                 op = MDB_GET_BOTH;
4732                 rdata = *data;
4733                 xdata = &rdata;
4734         } else {
4735                 op = MDB_SET;
4736                 xdata = NULL;
4737         }
4738         rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
4739         if (rc == 0)
4740                 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
4741         return rc;
4742 }
4743
4744 /** Split a page and insert a new node.
4745  * @param[in,out] mc Cursor pointing to the page and desired insertion index.
4746  * The cursor will be updated to point to the actual page and index where
4747  * the node got inserted after the split.
4748  * @param[in] newkey The key for the newly inserted node.
4749  * @param[in] newdata The data for the newly inserted node.
4750  * @param[in] newpgno The page number, if the new node is a branch node.
4751  * @return 0 on success, non-zero on failure.
4752  */
4753 static int
4754 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
4755 {
4756         uint8_t          flags;
4757         int              rc = MDB_SUCCESS, ins_new = 0;
4758         indx_t           newindx;
4759         pgno_t           pgno = 0;
4760         unsigned int     i, j, split_indx, nkeys, pmax;
4761         MDB_node        *node;
4762         MDB_val  sepkey, rkey, rdata;
4763         MDB_page        *copy;
4764         MDB_page        *mp, *rp, *pp;
4765         unsigned int ptop;
4766         MDB_cursor      mn;
4767         DKBUF;
4768
4769         mp = mc->mc_pg[mc->mc_top];
4770         newindx = mc->mc_ki[mc->mc_top];
4771
4772         DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
4773             IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
4774             DKEY(newkey), mc->mc_ki[mc->mc_top]);
4775
4776         if (mc->mc_snum < 2) {
4777                 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
4778                         return ENOMEM;
4779                 /* shift current top to make room for new parent */
4780                 mc->mc_pg[1] = mc->mc_pg[0];
4781                 mc->mc_ki[1] = mc->mc_ki[0];
4782                 mc->mc_pg[0] = pp;
4783                 mc->mc_ki[0] = 0;
4784                 mc->mc_db->md_root = pp->mp_pgno;
4785                 DPRINTF("root split! new root = %zu", pp->mp_pgno);
4786                 mc->mc_db->md_depth++;
4787
4788                 /* Add left (implicit) pointer. */
4789                 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
4790                         /* undo the pre-push */
4791                         mc->mc_pg[0] = mc->mc_pg[1];
4792                         mc->mc_ki[0] = mc->mc_ki[1];
4793                         mc->mc_db->md_root = mp->mp_pgno;
4794                         mc->mc_db->md_depth--;
4795                         return rc;
4796                 }
4797                 mc->mc_snum = 2;
4798                 mc->mc_top = 1;
4799                 ptop = 0;
4800         } else {
4801                 ptop = mc->mc_top-1;
4802                 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
4803         }
4804
4805         /* Create a right sibling. */
4806         if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
4807                 return ENOMEM;
4808         mdb_cursor_copy(mc, &mn);
4809         mn.mc_pg[mn.mc_top] = rp;
4810         mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
4811         DPRINTF("new right sibling: page %zu", rp->mp_pgno);
4812
4813         nkeys = NUMKEYS(mp);
4814         split_indx = nkeys / 2 + 1;
4815
4816         if (IS_LEAF2(rp)) {
4817                 char *split, *ins;
4818                 int x;
4819                 unsigned int lsize, rsize, ksize;
4820                 /* Move half of the keys to the right sibling */
4821                 copy = NULL;
4822                 x = mc->mc_ki[mc->mc_top] - split_indx;
4823                 ksize = mc->mc_db->md_pad;
4824                 split = LEAF2KEY(mp, split_indx, ksize);
4825                 rsize = (nkeys - split_indx) * ksize;
4826                 lsize = (nkeys - split_indx) * sizeof(indx_t);
4827                 mp->mp_lower -= lsize;
4828                 rp->mp_lower += lsize;
4829                 mp->mp_upper += rsize - lsize;
4830                 rp->mp_upper -= rsize - lsize;
4831                 sepkey.mv_size = ksize;
4832                 if (newindx == split_indx) {
4833                         sepkey.mv_data = newkey->mv_data;
4834                 } else {
4835                         sepkey.mv_data = split;
4836                 }
4837                 if (x<0) {
4838                         ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
4839                         memcpy(rp->mp_ptrs, split, rsize);
4840                         sepkey.mv_data = rp->mp_ptrs;
4841                         memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
4842                         memcpy(ins, newkey->mv_data, ksize);
4843                         mp->mp_lower += sizeof(indx_t);
4844                         mp->mp_upper -= ksize - sizeof(indx_t);
4845                 } else {
4846                         if (x)
4847                                 memcpy(rp->mp_ptrs, split, x * ksize);
4848                         ins = LEAF2KEY(rp, x, ksize);
4849                         memcpy(ins, newkey->mv_data, ksize);
4850                         memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
4851                         rp->mp_lower += sizeof(indx_t);
4852                         rp->mp_upper -= ksize - sizeof(indx_t);
4853                         mc->mc_ki[mc->mc_top] = x;
4854                         mc->mc_pg[mc->mc_top] = rp;
4855                 }
4856                 goto newsep;
4857         }
4858
4859         /* For leaf pages, check the split point based on what
4860          * fits where, since otherwise add_node can fail.
4861          */
4862         if (IS_LEAF(mp)) {
4863                 unsigned int psize, nsize;
4864                 /* Maximum free space in an empty page */
4865                 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
4866                 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
4867                 if (newindx < split_indx) {
4868                         psize = nsize;
4869                         for (i=0; i<split_indx; i++) {
4870                                 node = NODEPTR(mp, i);
4871                                 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4872                                 if (F_ISSET(node->mn_flags, F_BIGDATA))
4873                                         psize += sizeof(pgno_t);
4874                                 else
4875                                         psize += NODEDSZ(node);
4876                                 psize += psize & 1;
4877                                 if (psize > pmax) {
4878                                         split_indx = i;
4879                                         break;
4880                                 }
4881                         }
4882                 } else {
4883                         psize = nsize;
4884                         for (i=nkeys-1; i>=split_indx; i--) {
4885                                 node = NODEPTR(mp, i);
4886                                 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4887                                 if (F_ISSET(node->mn_flags, F_BIGDATA))
4888                                         psize += sizeof(pgno_t);
4889                                 else
4890                                         psize += NODEDSZ(node);
4891                                 psize += psize & 1;
4892                                 if (psize > pmax) {
4893                                         split_indx = i+1;
4894                                         break;
4895                                 }
4896                         }
4897                 }
4898         }
4899
4900         /* First find the separating key between the split pages.
4901          */
4902         if (newindx == split_indx) {
4903                 sepkey.mv_size = newkey->mv_size;
4904                 sepkey.mv_data = newkey->mv_data;
4905         } else {
4906                 node = NODEPTR(mp, split_indx);
4907                 sepkey.mv_size = node->mn_ksize;
4908                 sepkey.mv_data = NODEKEY(node);
4909         }
4910
4911 newsep:
4912         DPRINTF("separator is [%s]", DKEY(&sepkey));
4913
4914         /* Copy separator key to the parent.
4915          */
4916         if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
4917                 mn.mc_snum--;
4918                 mn.mc_top--;
4919                 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno);
4920
4921                 /* Right page might now have changed parent.
4922                  * Check if left page also changed parent.
4923                  */
4924                 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
4925                     mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
4926                         mc->mc_pg[ptop] = mn.mc_pg[ptop];
4927                         mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
4928                 }
4929         } else {
4930                 mn.mc_top--;
4931                 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
4932                 mn.mc_top++;
4933         }
4934         if (IS_LEAF2(rp)) {
4935                 return rc;
4936         }
4937         if (rc != MDB_SUCCESS) {
4938                 return rc;
4939         }
4940
4941         /* Move half of the keys to the right sibling. */
4942
4943         /* grab a page to hold a temporary copy */
4944         if (mc->mc_txn->mt_env->me_dpages) {
4945                 copy = mc->mc_txn->mt_env->me_dpages;
4946                 mc->mc_txn->mt_env->me_dpages = copy->mp_next;
4947         } else {
4948                 if ((copy = malloc(mc->mc_txn->mt_env->me_psize)) == NULL)
4949                         return ENOMEM;
4950         }
4951
4952         copy->mp_pgno  = mp->mp_pgno;
4953         copy->mp_flags = mp->mp_flags;
4954         copy->mp_lower = PAGEHDRSZ;
4955         copy->mp_upper = mc->mc_txn->mt_env->me_psize;
4956         mc->mc_pg[mc->mc_top] = copy;
4957         for (i = j = 0; i <= nkeys; j++) {
4958                 if (i == split_indx) {
4959                 /* Insert in right sibling. */
4960                 /* Reset insert index for right sibling. */
4961                         j = (i == newindx && ins_new);
4962                         mc->mc_pg[mc->mc_top] = rp;
4963                 }
4964
4965                 if (i == newindx && !ins_new) {
4966                         /* Insert the original entry that caused the split. */
4967                         rkey.mv_data = newkey->mv_data;
4968                         rkey.mv_size = newkey->mv_size;
4969                         if (IS_LEAF(mp)) {
4970                                 rdata.mv_data = newdata->mv_data;
4971                                 rdata.mv_size = newdata->mv_size;
4972                         } else
4973                                 pgno = newpgno;
4974                         flags = 0;
4975
4976                         ins_new = 1;
4977
4978                         /* Update page and index for the new key. */
4979                         mc->mc_ki[mc->mc_top] = j;
4980                 } else if (i == nkeys) {
4981                         break;
4982                 } else {
4983                         node = NODEPTR(mp, i);
4984                         rkey.mv_data = NODEKEY(node);
4985                         rkey.mv_size = node->mn_ksize;
4986                         if (IS_LEAF(mp)) {
4987                                 rdata.mv_data = NODEDATA(node);
4988                                 rdata.mv_size = NODEDSZ(node);
4989                         } else
4990                                 pgno = NODEPGNO(node);
4991                         flags = node->mn_flags;
4992
4993                         i++;
4994                 }
4995
4996                 if (!IS_LEAF(mp) && j == 0) {
4997                         /* First branch index doesn't need key data. */
4998                         rkey.mv_size = 0;
4999                 }
5000
5001                 rc = mdb_node_add(mc, j, &rkey, &rdata, pgno, flags);
5002         }
5003
5004         /* reset back to original page */
5005         if (newindx < split_indx)
5006                 mc->mc_pg[mc->mc_top] = mp;
5007
5008         nkeys = NUMKEYS(copy);
5009         for (i=0; i<nkeys; i++)
5010                 mp->mp_ptrs[i] = copy->mp_ptrs[i];
5011         mp->mp_lower = copy->mp_lower;
5012         mp->mp_upper = copy->mp_upper;
5013         memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
5014                 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
5015
5016         /* return tmp page to freelist */
5017         copy->mp_next = mc->mc_txn->mt_env->me_dpages;
5018         mc->mc_txn->mt_env->me_dpages = copy;
5019         return rc;
5020 }
5021
5022 int
5023 mdb_put(MDB_txn *txn, MDB_dbi dbi,
5024     MDB_val *key, MDB_val *data, unsigned int flags)
5025 {
5026         MDB_cursor mc;
5027         MDB_xcursor mx;
5028
5029         assert(key != NULL);
5030         assert(data != NULL);
5031
5032         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5033                 return EINVAL;
5034
5035         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5036                 return EACCES;
5037         }
5038
5039         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5040                 return EINVAL;
5041         }
5042
5043         if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
5044                 return EINVAL;
5045
5046         mdb_cursor_init(&mc, txn, dbi, &mx);
5047         return mdb_cursor_put(&mc, key, data, flags);
5048 }
5049
5050 int
5051 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
5052 {
5053         /** Only a subset of the @ref mdb_env flags can be changed
5054          *      at runtime. Changing other flags requires closing the environment
5055          *      and re-opening it with the new flags.
5056          */
5057 #define CHANGEABLE      (MDB_NOSYNC)
5058         if ((flag & CHANGEABLE) != flag)
5059                 return EINVAL;
5060         if (onoff)
5061                 env->me_flags |= flag;
5062         else
5063                 env->me_flags &= ~flag;
5064         return MDB_SUCCESS;
5065 }
5066
5067 int
5068 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
5069 {
5070         if (!env || !arg)
5071                 return EINVAL;
5072
5073         *arg = env->me_flags;
5074         return MDB_SUCCESS;
5075 }
5076
5077 int
5078 mdb_env_get_path(MDB_env *env, const char **arg)
5079 {
5080         if (!env || !arg)
5081                 return EINVAL;
5082
5083         *arg = env->me_path;
5084         return MDB_SUCCESS;
5085 }
5086
5087 /** Common code for #mdb_stat() and #mdb_env_stat().
5088  * @param[in] env the environment to operate in.
5089  * @param[in] db the #MDB_db record containing the stats to return.
5090  * @param[out] arg the address of an #MDB_stat structure to receive the stats.
5091  * @return 0, this function always succeeds.
5092  */
5093 static int
5094 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
5095 {
5096         arg->ms_psize = env->me_psize;
5097         arg->ms_depth = db->md_depth;
5098         arg->ms_branch_pages = db->md_branch_pages;
5099         arg->ms_leaf_pages = db->md_leaf_pages;
5100         arg->ms_overflow_pages = db->md_overflow_pages;
5101         arg->ms_entries = db->md_entries;
5102
5103         return MDB_SUCCESS;
5104 }
5105 int
5106 mdb_env_stat(MDB_env *env, MDB_stat *arg)
5107 {
5108         int toggle;
5109
5110         if (env == NULL || arg == NULL)
5111                 return EINVAL;
5112
5113         mdb_env_read_meta(env, &toggle);
5114
5115         return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
5116 }
5117
5118 /** Set the default comparison functions for a database.
5119  * Called immediately after a database is opened to set the defaults.
5120  * The user can then override them with #mdb_set_compare() or
5121  * #mdb_set_dupsort().
5122  * @param[in] txn A transaction handle returned by #mdb_txn_begin()
5123  * @param[in] dbi A database handle returned by #mdb_open()
5124  */
5125 static void
5126 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
5127 {
5128         if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
5129                 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memnr;
5130         else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
5131                 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_cint;
5132         else
5133                 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memn;
5134
5135         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5136                 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
5137                         if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
5138                                 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_int;
5139                         else
5140                                 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_cint;
5141                 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
5142                         txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memnr;
5143                 } else {
5144                         txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memn;
5145                 }
5146         } else {
5147                 txn->mt_dbxs[dbi].md_dcmp = NULL;
5148         }
5149 }
5150
5151 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
5152 {
5153         MDB_val key, data;
5154         MDB_dbi i;
5155         int rc, dirty = 0;
5156         size_t len;
5157
5158         if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
5159                 mdb_default_cmp(txn, FREE_DBI);
5160         }
5161
5162         /* main DB? */
5163         if (!name) {
5164                 *dbi = MAIN_DBI;
5165                 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
5166                         txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
5167                 mdb_default_cmp(txn, MAIN_DBI);
5168                 return MDB_SUCCESS;
5169         }
5170
5171         if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
5172                 mdb_default_cmp(txn, MAIN_DBI);
5173         }
5174
5175         /* Is the DB already open? */
5176         len = strlen(name);
5177         for (i=2; i<txn->mt_numdbs; i++) {
5178                 if (len == txn->mt_dbxs[i].md_name.mv_size &&
5179                         !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
5180                         *dbi = i;
5181                         return MDB_SUCCESS;
5182                 }
5183         }
5184
5185         if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
5186                 return ENFILE;
5187
5188         /* Find the DB info */
5189         key.mv_size = len;
5190         key.mv_data = (void *)name;
5191         rc = mdb_get(txn, MAIN_DBI, &key, &data);
5192
5193         /* Create if requested */
5194         if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
5195                 MDB_cursor mc;
5196                 MDB_db dummy;
5197                 data.mv_size = sizeof(MDB_db);
5198                 data.mv_data = &dummy;
5199                 memset(&dummy, 0, sizeof(dummy));
5200                 dummy.md_root = P_INVALID;
5201                 dummy.md_flags = flags & 0xffff;
5202                 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
5203                 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
5204                 dirty = 1;
5205         }
5206
5207         /* OK, got info, add to table */
5208         if (rc == MDB_SUCCESS) {
5209                 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
5210                 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
5211                 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
5212                 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
5213                 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
5214                 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
5215                 *dbi = txn->mt_numdbs;
5216                 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5217                 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5218                 mdb_default_cmp(txn, txn->mt_numdbs);
5219                 txn->mt_numdbs++;
5220         }
5221
5222         return rc;
5223 }
5224
5225 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
5226 {
5227         if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
5228                 return EINVAL;
5229
5230         return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
5231 }
5232
5233 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
5234 {
5235         char *ptr;
5236         if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
5237                 return;
5238         ptr = txn->mt_dbxs[dbi].md_name.mv_data;
5239         txn->mt_dbxs[dbi].md_name.mv_data = NULL;
5240         txn->mt_dbxs[dbi].md_name.mv_size = 0;
5241         free(ptr);
5242 }
5243
5244 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5245 {
5246         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5247                 return EINVAL;
5248
5249         txn->mt_dbxs[dbi].md_cmp = cmp;
5250         return MDB_SUCCESS;
5251 }
5252
5253 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5254 {
5255         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5256                 return EINVAL;
5257
5258         txn->mt_dbxs[dbi].md_dcmp = cmp;
5259         return MDB_SUCCESS;
5260 }
5261
5262 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
5263 {
5264         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5265                 return EINVAL;
5266
5267         txn->mt_dbxs[dbi].md_rel = rel;
5268         return MDB_SUCCESS;
5269 }
5270
5271 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
5272 {
5273         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5274                 return EINVAL;
5275
5276         txn->mt_dbxs[dbi].md_relctx = ctx;
5277         return MDB_SUCCESS;
5278 }
5279
5280 /** @} */