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