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