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