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