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