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