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