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