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