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