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