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