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