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