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