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