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