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