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