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