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