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