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