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