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