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