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