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