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