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