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