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