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