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