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