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