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