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