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