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