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