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