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