]> git.sur5r.net Git - openldap/blob - libraries/liblmdb/mdb.c
ITS#8557 fix mdb_cursor_last
[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) || defined(__FreeBSD_kernel__)
153 # if !(defined(MDB_USE_POSIX_MUTEX) || defined(MDB_USE_POSIX_SEM))
154 # define MDB_USE_SYSV_SEM       1
155 # endif
156 # define MDB_FDATASYNC          fsync
157 #elif defined(ANDROID)
158 # define MDB_FDATASYNC          fsync
159 #endif
160
161 #ifndef _WIN32
162 #include <pthread.h>
163 #include <signal.h>
164 #ifdef MDB_USE_POSIX_SEM
165 # define MDB_USE_HASH           1
166 #include <semaphore.h>
167 #elif defined(MDB_USE_SYSV_SEM)
168 #include <sys/ipc.h>
169 #include <sys/sem.h>
170 #ifdef _SEM_SEMUN_UNDEFINED
171 union semun {
172         int val;
173         struct semid_ds *buf;
174         unsigned short *array;
175 };
176 #endif /* _SEM_SEMUN_UNDEFINED */
177 #else
178 #define MDB_USE_POSIX_MUTEX     1
179 #endif /* MDB_USE_POSIX_SEM */
180 #endif /* !_WIN32 */
181
182 #if defined(_WIN32) + defined(MDB_USE_POSIX_SEM) + defined(MDB_USE_SYSV_SEM) \
183         + defined(MDB_USE_POSIX_MUTEX) != 1
184 # error "Ambiguous shared-lock implementation"
185 #endif
186
187 #ifdef USE_VALGRIND
188 #include <valgrind/memcheck.h>
189 #define VGMEMP_CREATE(h,r,z)    VALGRIND_CREATE_MEMPOOL(h,r,z)
190 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
191 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
192 #define VGMEMP_DESTROY(h)       VALGRIND_DESTROY_MEMPOOL(h)
193 #define VGMEMP_DEFINED(a,s)     VALGRIND_MAKE_MEM_DEFINED(a,s)
194 #else
195 #define VGMEMP_CREATE(h,r,z)
196 #define VGMEMP_ALLOC(h,a,s)
197 #define VGMEMP_FREE(h,a)
198 #define VGMEMP_DESTROY(h)
199 #define VGMEMP_DEFINED(a,s)
200 #endif
201
202 #ifndef BYTE_ORDER
203 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
204 /* Solaris just defines one or the other */
205 #  define LITTLE_ENDIAN 1234
206 #  define BIG_ENDIAN    4321
207 #  ifdef _LITTLE_ENDIAN
208 #   define BYTE_ORDER  LITTLE_ENDIAN
209 #  else
210 #   define BYTE_ORDER  BIG_ENDIAN
211 #  endif
212 # else
213 #  define BYTE_ORDER   __BYTE_ORDER
214 # endif
215 #endif
216
217 #ifndef LITTLE_ENDIAN
218 #define LITTLE_ENDIAN   __LITTLE_ENDIAN
219 #endif
220 #ifndef BIG_ENDIAN
221 #define BIG_ENDIAN      __BIG_ENDIAN
222 #endif
223
224 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
225 #define MISALIGNED_OK   1
226 #endif
227
228 #include "lmdb.h"
229 #include "midl.h"
230
231 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
232 # error "Unknown or unsupported endianness (BYTE_ORDER)"
233 #elif (-6 & 5) || CHAR_BIT!=8 || UINT_MAX!=0xffffffff || MDB_SIZE_MAX%UINT_MAX
234 # error "Two's complement, reasonably sized integer types, please"
235 #endif
236
237 #ifdef __GNUC__
238 /** Put infrequently used env functions in separate section */
239 # ifdef __APPLE__
240 #  define       ESECT   __attribute__ ((section("__TEXT,text_env")))
241 # else
242 #  define       ESECT   __attribute__ ((section("text_env")))
243 # endif
244 #else
245 #define ESECT
246 #endif
247
248 #ifdef _WIN32
249 #define CALL_CONV WINAPI
250 #else
251 #define CALL_CONV
252 #endif
253
254 /** @defgroup internal  LMDB Internals
255  *      @{
256  */
257 /** @defgroup compat    Compatibility Macros
258  *      A bunch of macros to minimize the amount of platform-specific ifdefs
259  *      needed throughout the rest of the code. When the features this library
260  *      needs are similar enough to POSIX to be hidden in a one-or-two line
261  *      replacement, this macro approach is used.
262  *      @{
263  */
264
265         /** Features under development */
266 #ifndef MDB_DEVEL
267 #define MDB_DEVEL 0
268 #endif
269
270         /** Wrapper around __func__, which is a C99 feature */
271 #if __STDC_VERSION__ >= 199901L
272 # define mdb_func_      __func__
273 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
274 # define mdb_func_      __FUNCTION__
275 #else
276 /* If a debug message says <mdb_unknown>(), update the #if statements above */
277 # define mdb_func_      "<mdb_unknown>"
278 #endif
279
280 /* Internal error codes, not exposed outside liblmdb */
281 #define MDB_NO_ROOT             (MDB_LAST_ERRCODE + 10)
282 #ifdef _WIN32
283 #define MDB_OWNERDEAD   ((int) WAIT_ABANDONED)
284 #elif defined MDB_USE_SYSV_SEM
285 #define MDB_OWNERDEAD   (MDB_LAST_ERRCODE + 11)
286 #elif defined(MDB_USE_POSIX_MUTEX) && defined(EOWNERDEAD)
287 #define MDB_OWNERDEAD   EOWNERDEAD      /**< #LOCK_MUTEX0() result if dead owner */
288 #endif
289
290 #ifdef __GLIBC__
291 #define GLIBC_VER       ((__GLIBC__ << 16 )| __GLIBC_MINOR__)
292 #endif
293 /** Some platforms define the EOWNERDEAD error code
294  * even though they don't support Robust Mutexes.
295  * Compile with -DMDB_USE_ROBUST=0, or use some other
296  * mechanism like -DMDB_USE_SYSV_SEM instead of
297  * -DMDB_USE_POSIX_MUTEX. (SysV semaphores are
298  * also Robust, but some systems don't support them
299  * either.)
300  */
301 #ifndef MDB_USE_ROBUST
302 /* Android currently lacks Robust Mutex support. So does glibc < 2.4. */
303 # if defined(MDB_USE_POSIX_MUTEX) && (defined(ANDROID) || \
304         (defined(__GLIBC__) && GLIBC_VER < 0x020004))
305 #  define MDB_USE_ROBUST        0
306 # else
307 #  define MDB_USE_ROBUST        1
308 # endif
309 #endif /* !MDB_USE_ROBUST */
310
311 #if defined(MDB_USE_POSIX_MUTEX) && (MDB_USE_ROBUST)
312 /* glibc < 2.12 only provided _np API */
313 #  if (defined(__GLIBC__) && GLIBC_VER < 0x02000c) || \
314         (defined(PTHREAD_MUTEX_ROBUST_NP) && !defined(PTHREAD_MUTEX_ROBUST))
315 #   define PTHREAD_MUTEX_ROBUST PTHREAD_MUTEX_ROBUST_NP
316 #   define pthread_mutexattr_setrobust(attr, flag)      pthread_mutexattr_setrobust_np(attr, flag)
317 #   define pthread_mutex_consistent(mutex)      pthread_mutex_consistent_np(mutex)
318 #  endif
319 #endif /* MDB_USE_POSIX_MUTEX && MDB_USE_ROBUST */
320
321 #if defined(MDB_OWNERDEAD) && (MDB_USE_ROBUST)
322 #define MDB_ROBUST_SUPPORTED    1
323 #endif
324
325 #ifdef _WIN32
326 #define MDB_USE_HASH    1
327 #define MDB_PIDLOCK     0
328 #define THREAD_RET      DWORD
329 #define pthread_t       HANDLE
330 #define pthread_mutex_t HANDLE
331 #define pthread_cond_t  HANDLE
332 typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
333 #define pthread_key_t   DWORD
334 #define pthread_self()  GetCurrentThreadId()
335 #define pthread_key_create(x,y) \
336         ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
337 #define pthread_key_delete(x)   TlsFree(x)
338 #define pthread_getspecific(x)  TlsGetValue(x)
339 #define pthread_setspecific(x,y)        (TlsSetValue(x,y) ? 0 : ErrCode())
340 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
341 #define pthread_mutex_lock(x)   WaitForSingleObject(*x, INFINITE)
342 #define pthread_cond_signal(x)  SetEvent(*x)
343 #define pthread_cond_wait(cond,mutex)   do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
344 #define THREAD_CREATE(thr,start,arg) \
345         (((thr) = CreateThread(NULL, 0, start, arg, 0, NULL)) ? 0 : ErrCode())
346 #define THREAD_FINISH(thr) \
347         (WaitForSingleObject(thr, INFINITE) ? ErrCode() : 0)
348 #define LOCK_MUTEX0(mutex)              WaitForSingleObject(mutex, INFINITE)
349 #define UNLOCK_MUTEX(mutex)             ReleaseMutex(mutex)
350 #define mdb_mutex_consistent(mutex)     0
351 #define getpid()        GetCurrentProcessId()
352 #define MDB_FDATASYNC(fd)       (!FlushFileBuffers(fd))
353 #define MDB_MSYNC(addr,len,flags)       (!FlushViewOfFile(addr,len))
354 #define ErrCode()       GetLastError()
355 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
356 #define close(fd)       (CloseHandle(fd) ? 0 : -1)
357 #define munmap(ptr,len) UnmapViewOfFile(ptr)
358 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
359 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
360 #else
361 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
362 #endif
363 #else
364 #define THREAD_RET      void *
365 #define THREAD_CREATE(thr,start,arg)    pthread_create(&thr,NULL,start,arg)
366 #define THREAD_FINISH(thr)      pthread_join(thr,NULL)
367
368         /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
369 #define MDB_PIDLOCK                     1
370
371 #ifdef MDB_USE_POSIX_SEM
372
373 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
374 #define LOCK_MUTEX0(mutex)              mdb_sem_wait(mutex)
375 #define UNLOCK_MUTEX(mutex)             sem_post(mutex)
376
377 static int
378 mdb_sem_wait(sem_t *sem)
379 {
380    int rc;
381    while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
382    return rc;
383 }
384
385 #elif defined MDB_USE_SYSV_SEM
386
387 typedef struct mdb_mutex {
388         int semid;
389         int semnum;
390         int *locked;
391 } mdb_mutex_t[1], *mdb_mutexref_t;
392
393 #define LOCK_MUTEX0(mutex)              mdb_sem_wait(mutex)
394 #define UNLOCK_MUTEX(mutex)             do { \
395         struct sembuf sb = { 0, 1, SEM_UNDO }; \
396         sb.sem_num = (mutex)->semnum; \
397         *(mutex)->locked = 0; \
398         semop((mutex)->semid, &sb, 1); \
399 } while(0)
400
401 static int
402 mdb_sem_wait(mdb_mutexref_t sem)
403 {
404         int rc, *locked = sem->locked;
405         struct sembuf sb = { 0, -1, SEM_UNDO };
406         sb.sem_num = sem->semnum;
407         do {
408                 if (!semop(sem->semid, &sb, 1)) {
409                         rc = *locked ? MDB_OWNERDEAD : MDB_SUCCESS;
410                         *locked = 1;
411                         break;
412                 }
413         } while ((rc = errno) == EINTR);
414         return rc;
415 }
416
417 #define mdb_mutex_consistent(mutex)     0
418
419 #else   /* MDB_USE_POSIX_MUTEX: */
420         /** Shared mutex/semaphore as the original is stored.
421          *
422          *      Not for copies.  Instead it can be assigned to an #mdb_mutexref_t.
423          *      When mdb_mutexref_t is a pointer and mdb_mutex_t is not, then it
424          *      is array[size 1] so it can be assigned to the pointer.
425          */
426 typedef pthread_mutex_t mdb_mutex_t[1];
427         /** Reference to an #mdb_mutex_t */
428 typedef pthread_mutex_t *mdb_mutexref_t;
429         /** Lock the reader or writer mutex.
430          *      Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
431          */
432 #define LOCK_MUTEX0(mutex)      pthread_mutex_lock(mutex)
433         /** Unlock the reader or writer mutex.
434          */
435 #define UNLOCK_MUTEX(mutex)     pthread_mutex_unlock(mutex)
436         /** Mark mutex-protected data as repaired, after death of previous owner.
437          */
438 #define mdb_mutex_consistent(mutex)     pthread_mutex_consistent(mutex)
439 #endif  /* MDB_USE_POSIX_SEM || MDB_USE_SYSV_SEM */
440
441         /** Get the error code for the last failed system function.
442          */
443 #define ErrCode()       errno
444
445         /** An abstraction for a file handle.
446          *      On POSIX systems file handles are small integers. On Windows
447          *      they're opaque pointers.
448          */
449 #define HANDLE  int
450
451         /**     A value for an invalid file handle.
452          *      Mainly used to initialize file variables and signify that they are
453          *      unused.
454          */
455 #define INVALID_HANDLE_VALUE    (-1)
456
457         /** Get the size of a memory page for the system.
458          *      This is the basic size that the platform's memory manager uses, and is
459          *      fundamental to the use of memory-mapped files.
460          */
461 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
462 #endif
463
464 #define Z       MDB_FMT_Z       /**< printf/scanf format modifier for size_t */
465 #define Yu      MDB_PRIy(u)     /**< printf format for #mdb_size_t */
466 #define Yd      MDB_PRIy(d)     /**< printf format for 'signed #mdb_size_t' */
467
468 #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                                 /* if already init'd, see if we're already in right place */
6210                                 if (mc->mc_flags & C_INITIALIZED) {
6211                                         if (mc->mc_ki[mc->mc_top] == i) {
6212                                                 mp = mc->mc_pg[mc->mc_top];
6213                                                 mc->mc_top = mc->mc_snum++;
6214                                                 goto ready;
6215                                         }
6216                                 }
6217                         }
6218                 } else {
6219                         int      exact;
6220                         node = mdb_node_search(mc, key, &exact);
6221                         if (node == NULL)
6222                                 i = NUMKEYS(mp) - 1;
6223                         else {
6224                                 i = mc->mc_ki[mc->mc_top];
6225                                 if (!exact) {
6226                                         mdb_cassert(mc, i > 0);
6227                                         i--;
6228                                 }
6229                         }
6230                         DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
6231                 }
6232
6233                 mdb_cassert(mc, i < NUMKEYS(mp));
6234                 node = NODEPTR(mp, i);
6235
6236                 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6237                         return rc;
6238
6239                 mc->mc_ki[mc->mc_top] = i;
6240                 if ((rc = mdb_cursor_push(mc, mp)))
6241                         return rc;
6242
6243 ready:
6244                 if (flags & MDB_PS_MODIFY) {
6245                         if ((rc = mdb_page_touch(mc)) != 0)
6246                                 return rc;
6247                         mp = mc->mc_pg[mc->mc_top];
6248                 }
6249         }
6250
6251         if (!IS_LEAF(mp)) {
6252                 DPRINTF(("internal error, index points to a %02X page!?",
6253                     mp->mp_flags));
6254                 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6255                 return MDB_CORRUPTED;
6256         }
6257
6258         DPRINTF(("found leaf page %"Yu" for key [%s]", mp->mp_pgno,
6259             key ? DKEY(key) : "null"));
6260         mc->mc_flags |= C_INITIALIZED;
6261         mc->mc_flags &= ~C_EOF;
6262
6263         return MDB_SUCCESS;
6264 }
6265
6266 /** Search for the lowest key under the current branch page.
6267  * This just bypasses a NUMKEYS check in the current page
6268  * before calling mdb_page_search_root(), because the callers
6269  * are all in situations where the current page is known to
6270  * be underfilled.
6271  */
6272 static int
6273 mdb_page_search_lowest(MDB_cursor *mc)
6274 {
6275         MDB_page        *mp = mc->mc_pg[mc->mc_top];
6276         MDB_node        *node = NODEPTR(mp, 0);
6277         int rc;
6278
6279         if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6280                 return rc;
6281
6282         mc->mc_ki[mc->mc_top] = 0;
6283         if ((rc = mdb_cursor_push(mc, mp)))
6284                 return rc;
6285         return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
6286 }
6287
6288 /** Search for the page a given key should be in.
6289  * Push it and its parent pages on the cursor stack.
6290  * @param[in,out] mc the cursor for this operation.
6291  * @param[in] key the key to search for, or NULL for first/last page.
6292  * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
6293  *   are touched (updated with new page numbers).
6294  *   If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
6295  *   This is used by #mdb_cursor_first() and #mdb_cursor_last().
6296  *   If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
6297  * @return 0 on success, non-zero on failure.
6298  */
6299 static int
6300 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
6301 {
6302         int              rc;
6303         pgno_t           root;
6304
6305         /* Make sure the txn is still viable, then find the root from
6306          * the txn's db table and set it as the root of the cursor's stack.
6307          */
6308         if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
6309                 DPUTS("transaction may not be used now");
6310                 return MDB_BAD_TXN;
6311         } else {
6312                 /* Make sure we're using an up-to-date root */
6313                 if (*mc->mc_dbflag & DB_STALE) {
6314                                 MDB_cursor mc2;
6315                                 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6316                                         return MDB_BAD_DBI;
6317                                 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
6318                                 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
6319                                 if (rc)
6320                                         return rc;
6321                                 {
6322                                         MDB_val data;
6323                                         int exact = 0;
6324                                         uint16_t flags;
6325                                         MDB_node *leaf = mdb_node_search(&mc2,
6326                                                 &mc->mc_dbx->md_name, &exact);
6327                                         if (!exact)
6328                                                 return MDB_NOTFOUND;
6329                                         if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
6330                                                 return MDB_INCOMPATIBLE; /* not a named DB */
6331                                         rc = mdb_node_read(&mc2, leaf, &data);
6332                                         if (rc)
6333                                                 return rc;
6334                                         memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
6335                                                 sizeof(uint16_t));
6336                                         /* The txn may not know this DBI, or another process may
6337                                          * have dropped and recreated the DB with other flags.
6338                                          */
6339                                         if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
6340                                                 return MDB_INCOMPATIBLE;
6341                                         memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
6342                                 }
6343                                 *mc->mc_dbflag &= ~DB_STALE;
6344                 }
6345                 root = mc->mc_db->md_root;
6346
6347                 if (root == P_INVALID) {                /* Tree is empty. */
6348                         DPUTS("tree is empty");
6349                         return MDB_NOTFOUND;
6350                 }
6351         }
6352
6353         mdb_cassert(mc, root > 1);
6354         if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root) {
6355 #ifdef MDB_VL32
6356                 if (mc->mc_pg[0])
6357                         MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[0]);
6358 #endif
6359                 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
6360                         return rc;
6361         }
6362
6363 #ifdef MDB_VL32
6364         {
6365                 int i;
6366                 for (i=1; i<mc->mc_snum; i++)
6367                         MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[i]);
6368         }
6369 #endif
6370         mc->mc_snum = 1;
6371         mc->mc_top = 0;
6372
6373         DPRINTF(("db %d root page %"Yu" has flags 0x%X",
6374                 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
6375
6376         if (flags & MDB_PS_MODIFY) {
6377                 if ((rc = mdb_page_touch(mc)))
6378                         return rc;
6379         }
6380
6381         if (flags & MDB_PS_ROOTONLY)
6382                 return MDB_SUCCESS;
6383
6384         return mdb_page_search_root(mc, key, flags);
6385 }
6386
6387 static int
6388 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
6389 {
6390         MDB_txn *txn = mc->mc_txn;
6391         pgno_t pg = mp->mp_pgno;
6392         unsigned x = 0, ovpages = mp->mp_pages;
6393         MDB_env *env = txn->mt_env;
6394         MDB_IDL sl = txn->mt_spill_pgs;
6395         MDB_ID pn = pg << 1;
6396         int rc;
6397
6398         DPRINTF(("free ov page %"Yu" (%d)", pg, ovpages));
6399         /* If the page is dirty or on the spill list we just acquired it,
6400          * so we should give it back to our current free list, if any.
6401          * Otherwise put it onto the list of pages we freed in this txn.
6402          *
6403          * Won't create me_pghead: me_pglast must be inited along with it.
6404          * Unsupported in nested txns: They would need to hide the page
6405          * range in ancestor txns' dirty and spilled lists.
6406          */
6407         if (env->me_pghead &&
6408                 !txn->mt_parent &&
6409                 ((mp->mp_flags & P_DIRTY) ||
6410                  (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
6411         {
6412                 unsigned i, j;
6413                 pgno_t *mop;
6414                 MDB_ID2 *dl, ix, iy;
6415                 rc = mdb_midl_need(&env->me_pghead, ovpages);
6416                 if (rc)
6417                         return rc;
6418                 if (!(mp->mp_flags & P_DIRTY)) {
6419                         /* This page is no longer spilled */
6420                         if (x == sl[0])
6421                                 sl[0]--;
6422                         else
6423                                 sl[x] |= 1;
6424                         goto release;
6425                 }
6426                 /* Remove from dirty list */
6427                 dl = txn->mt_u.dirty_list;
6428                 x = dl[0].mid--;
6429                 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
6430                         if (x > 1) {
6431                                 x--;
6432                                 iy = dl[x];
6433                                 dl[x] = ix;
6434                         } else {
6435                                 mdb_cassert(mc, x > 1);
6436                                 j = ++(dl[0].mid);
6437                                 dl[j] = ix;             /* Unsorted. OK when MDB_TXN_ERROR. */
6438                                 txn->mt_flags |= MDB_TXN_ERROR;
6439                                 return MDB_PROBLEM;
6440                         }
6441                 }
6442                 txn->mt_dirty_room++;
6443                 if (!(env->me_flags & MDB_WRITEMAP))
6444                         mdb_dpage_free(env, mp);
6445 release:
6446                 /* Insert in me_pghead */
6447                 mop = env->me_pghead;
6448                 j = mop[0] + ovpages;
6449                 for (i = mop[0]; i && mop[i] < pg; i--)
6450                         mop[j--] = mop[i];
6451                 while (j>i)
6452                         mop[j--] = pg++;
6453                 mop[0] += ovpages;
6454         } else {
6455                 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
6456                 if (rc)
6457                         return rc;
6458         }
6459         mc->mc_db->md_overflow_pages -= ovpages;
6460         return 0;
6461 }
6462
6463 /** Return the data associated with a given node.
6464  * @param[in] mc The cursor for this operation.
6465  * @param[in] leaf The node being read.
6466  * @param[out] data Updated to point to the node's data.
6467  * @return 0 on success, non-zero on failure.
6468  */
6469 static int
6470 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
6471 {
6472         MDB_page        *omp;           /* overflow page */
6473         pgno_t           pgno;
6474         int rc;
6475
6476         if (MC_OVPG(mc)) {
6477                 MDB_PAGE_UNREF(mc->mc_txn, MC_OVPG(mc));
6478                 MC_SET_OVPG(mc, NULL);
6479         }
6480         if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6481                 data->mv_size = NODEDSZ(leaf);
6482                 data->mv_data = NODEDATA(leaf);
6483                 return MDB_SUCCESS;
6484         }
6485
6486         /* Read overflow data.
6487          */
6488         data->mv_size = NODEDSZ(leaf);
6489         memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
6490         if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
6491                 DPRINTF(("read overflow page %"Yu" failed", pgno));
6492                 return rc;
6493         }
6494         data->mv_data = METADATA(omp);
6495         MC_SET_OVPG(mc, omp);
6496
6497         return MDB_SUCCESS;
6498 }
6499
6500 int
6501 mdb_get(MDB_txn *txn, MDB_dbi dbi,
6502     MDB_val *key, MDB_val *data)
6503 {
6504         MDB_cursor      mc;
6505         MDB_xcursor     mx;
6506         int exact = 0, rc;
6507         DKBUF;
6508
6509         DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
6510
6511         if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
6512                 return EINVAL;
6513
6514         if (txn->mt_flags & MDB_TXN_BLOCKED)
6515                 return MDB_BAD_TXN;
6516
6517         mdb_cursor_init(&mc, txn, dbi, &mx);
6518         rc = mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
6519         /* unref all the pages when MDB_VL32 - caller must copy the data
6520          * before doing anything else
6521          */
6522         MDB_CURSOR_UNREF(&mc, 1);
6523         return rc;
6524 }
6525
6526 /** Find a sibling for a page.
6527  * Replaces the page at the top of the cursor's stack with the
6528  * specified sibling, if one exists.
6529  * @param[in] mc The cursor for this operation.
6530  * @param[in] move_right Non-zero if the right sibling is requested,
6531  * otherwise the left sibling.
6532  * @return 0 on success, non-zero on failure.
6533  */
6534 static int
6535 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
6536 {
6537         int              rc;
6538         MDB_node        *indx;
6539         MDB_page        *mp;
6540 #ifdef MDB_VL32
6541         MDB_page        *op;
6542 #endif
6543
6544         if (mc->mc_snum < 2) {
6545                 return MDB_NOTFOUND;            /* root has no siblings */
6546         }
6547
6548 #ifdef MDB_VL32
6549         op = mc->mc_pg[mc->mc_top];
6550 #endif
6551         mdb_cursor_pop(mc);
6552         DPRINTF(("parent page is page %"Yu", index %u",
6553                 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
6554
6555         if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6556                        : (mc->mc_ki[mc->mc_top] == 0)) {
6557                 DPRINTF(("no more keys left, moving to %s sibling",
6558                     move_right ? "right" : "left"));
6559                 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
6560                         /* undo cursor_pop before returning */
6561                         mc->mc_top++;
6562                         mc->mc_snum++;
6563                         return rc;
6564                 }
6565         } else {
6566                 if (move_right)
6567                         mc->mc_ki[mc->mc_top]++;
6568                 else
6569                         mc->mc_ki[mc->mc_top]--;
6570                 DPRINTF(("just moving to %s index key %u",
6571                     move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
6572         }
6573         mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
6574
6575         MDB_PAGE_UNREF(mc->mc_txn, op);
6576
6577         indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6578         if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
6579                 /* mc will be inconsistent if caller does mc_snum++ as above */
6580                 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6581                 return rc;
6582         }
6583
6584         mdb_cursor_push(mc, mp);
6585         if (!move_right)
6586                 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
6587
6588         return MDB_SUCCESS;
6589 }
6590
6591 /** Move the cursor to the next data item. */
6592 static int
6593 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6594 {
6595         MDB_page        *mp;
6596         MDB_node        *leaf;
6597         int rc;
6598
6599         if ((mc->mc_flags & C_EOF) ||
6600                 ((mc->mc_flags & C_DEL) && op == MDB_NEXT_DUP)) {
6601                 return MDB_NOTFOUND;
6602         }
6603         if (!(mc->mc_flags & C_INITIALIZED))
6604                 return mdb_cursor_first(mc, key, data);
6605
6606         mp = mc->mc_pg[mc->mc_top];
6607
6608         if (mc->mc_db->md_flags & MDB_DUPSORT) {
6609                 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6610                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6611                         if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
6612                                 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
6613                                 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
6614                                         if (rc == MDB_SUCCESS)
6615                                                 MDB_GET_KEY(leaf, key);
6616                                         return rc;
6617                                 }
6618                         }
6619                         else {
6620                                 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6621                         }
6622                 } else {
6623                         mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6624                         if (op == MDB_NEXT_DUP)
6625                                 return MDB_NOTFOUND;
6626                 }
6627         }
6628
6629         DPRINTF(("cursor_next: top page is %"Yu" in cursor %p",
6630                 mdb_dbg_pgno(mp), (void *) mc));
6631         if (mc->mc_flags & C_DEL) {
6632                 mc->mc_flags ^= C_DEL;
6633                 goto skip;
6634         }
6635
6636         if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
6637                 DPUTS("=====> move to next sibling page");
6638                 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6639                         mc->mc_flags |= C_EOF;
6640                         return rc;
6641                 }
6642                 mp = mc->mc_pg[mc->mc_top];
6643                 DPRINTF(("next page is %"Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6644         } else
6645                 mc->mc_ki[mc->mc_top]++;
6646
6647 skip:
6648         DPRINTF(("==> cursor points to page %"Yu" with %u keys, key index %u",
6649             mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6650
6651         if (IS_LEAF2(mp)) {
6652                 key->mv_size = mc->mc_db->md_pad;
6653                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6654                 return MDB_SUCCESS;
6655         }
6656
6657         mdb_cassert(mc, IS_LEAF(mp));
6658         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6659
6660         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6661                 mdb_xcursor_init1(mc, leaf);
6662         }
6663         if (data) {
6664                 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6665                         return rc;
6666
6667                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6668                         rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6669                         if (rc != MDB_SUCCESS)
6670                                 return rc;
6671                 }
6672         }
6673
6674         MDB_GET_KEY(leaf, key);
6675         return MDB_SUCCESS;
6676 }
6677
6678 /** Move the cursor to the previous data item. */
6679 static int
6680 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6681 {
6682         MDB_page        *mp;
6683         MDB_node        *leaf;
6684         int rc;
6685
6686         if (!(mc->mc_flags & C_INITIALIZED)) {
6687                 rc = mdb_cursor_last(mc, key, data);
6688                 if (rc)
6689                         return rc;
6690                 mc->mc_ki[mc->mc_top]++;
6691         }
6692
6693         mp = mc->mc_pg[mc->mc_top];
6694
6695         if (mc->mc_db->md_flags & MDB_DUPSORT) {
6696                 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6697                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6698                         if (op == MDB_PREV || op == MDB_PREV_DUP) {
6699                                 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
6700                                 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
6701                                         if (rc == MDB_SUCCESS) {
6702                                                 MDB_GET_KEY(leaf, key);
6703                                                 mc->mc_flags &= ~C_EOF;
6704                                         }
6705                                         return rc;
6706                                 }
6707                         }
6708                         else {
6709                                 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6710                         }
6711                 } else {
6712                         mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6713                         if (op == MDB_PREV_DUP)
6714                                 return MDB_NOTFOUND;
6715                 }
6716         }
6717
6718         DPRINTF(("cursor_prev: top page is %"Yu" in cursor %p",
6719                 mdb_dbg_pgno(mp), (void *) mc));
6720
6721         mc->mc_flags &= ~(C_EOF|C_DEL);
6722
6723         if (mc->mc_ki[mc->mc_top] == 0)  {
6724                 DPUTS("=====> move to prev sibling page");
6725                 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
6726                         return rc;
6727                 }
6728                 mp = mc->mc_pg[mc->mc_top];
6729                 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
6730                 DPRINTF(("prev page is %"Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6731         } else
6732                 mc->mc_ki[mc->mc_top]--;
6733
6734         DPRINTF(("==> cursor points to page %"Yu" with %u keys, key index %u",
6735             mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6736
6737         if (IS_LEAF2(mp)) {
6738                 key->mv_size = mc->mc_db->md_pad;
6739                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6740                 return MDB_SUCCESS;
6741         }
6742
6743         mdb_cassert(mc, IS_LEAF(mp));
6744         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6745
6746         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6747                 mdb_xcursor_init1(mc, leaf);
6748         }
6749         if (data) {
6750                 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6751                         return rc;
6752
6753                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6754                         rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6755                         if (rc != MDB_SUCCESS)
6756                                 return rc;
6757                 }
6758         }
6759
6760         MDB_GET_KEY(leaf, key);
6761         return MDB_SUCCESS;
6762 }
6763
6764 /** Set the cursor on a specific data item. */
6765 static int
6766 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6767     MDB_cursor_op op, int *exactp)
6768 {
6769         int              rc;
6770         MDB_page        *mp;
6771         MDB_node        *leaf = NULL;
6772         DKBUF;
6773
6774         if (key->mv_size == 0)
6775                 return MDB_BAD_VALSIZE;
6776
6777         if (mc->mc_xcursor) {
6778                 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6779                 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6780         }
6781
6782         /* See if we're already on the right page */
6783         if (mc->mc_flags & C_INITIALIZED) {
6784                 MDB_val nodekey;
6785
6786                 mp = mc->mc_pg[mc->mc_top];
6787                 if (!NUMKEYS(mp)) {
6788                         mc->mc_ki[mc->mc_top] = 0;
6789                         return MDB_NOTFOUND;
6790                 }
6791                 if (mp->mp_flags & P_LEAF2) {
6792                         nodekey.mv_size = mc->mc_db->md_pad;
6793                         nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
6794                 } else {
6795                         leaf = NODEPTR(mp, 0);
6796                         MDB_GET_KEY2(leaf, nodekey);
6797                 }
6798                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6799                 if (rc == 0) {
6800                         /* Probably happens rarely, but first node on the page
6801                          * was the one we wanted.
6802                          */
6803                         mc->mc_ki[mc->mc_top] = 0;
6804                         if (exactp)
6805                                 *exactp = 1;
6806                         goto set1;
6807                 }
6808                 if (rc > 0) {
6809                         unsigned int i;
6810                         unsigned int nkeys = NUMKEYS(mp);
6811                         if (nkeys > 1) {
6812                                 if (mp->mp_flags & P_LEAF2) {
6813                                         nodekey.mv_data = LEAF2KEY(mp,
6814                                                  nkeys-1, nodekey.mv_size);
6815                                 } else {
6816                                         leaf = NODEPTR(mp, nkeys-1);
6817                                         MDB_GET_KEY2(leaf, nodekey);
6818                                 }
6819                                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6820                                 if (rc == 0) {
6821                                         /* last node was the one we wanted */
6822                                         mc->mc_ki[mc->mc_top] = nkeys-1;
6823                                         if (exactp)
6824                                                 *exactp = 1;
6825                                         goto set1;
6826                                 }
6827                                 if (rc < 0) {
6828                                         if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
6829                                                 /* This is definitely the right page, skip search_page */
6830                                                 if (mp->mp_flags & P_LEAF2) {
6831                                                         nodekey.mv_data = LEAF2KEY(mp,
6832                                                                  mc->mc_ki[mc->mc_top], nodekey.mv_size);
6833                                                 } else {
6834                                                         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6835                                                         MDB_GET_KEY2(leaf, nodekey);
6836                                                 }
6837                                                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6838                                                 if (rc == 0) {
6839                                                         /* current node was the one we wanted */
6840                                                         if (exactp)
6841                                                                 *exactp = 1;
6842                                                         goto set1;
6843                                                 }
6844                                         }
6845                                         rc = 0;
6846                                         mc->mc_flags &= ~C_EOF;
6847                                         goto set2;
6848                                 }
6849                         }
6850                         /* If any parents have right-sibs, search.
6851                          * Otherwise, there's nothing further.
6852                          */
6853                         for (i=0; i<mc->mc_top; i++)
6854                                 if (mc->mc_ki[i] <
6855                                         NUMKEYS(mc->mc_pg[i])-1)
6856                                         break;
6857                         if (i == mc->mc_top) {
6858                                 /* There are no other pages */
6859                                 mc->mc_ki[mc->mc_top] = nkeys;
6860                                 return MDB_NOTFOUND;
6861                         }
6862                 }
6863                 if (!mc->mc_top) {
6864                         /* There are no other pages */
6865                         mc->mc_ki[mc->mc_top] = 0;
6866                         if (op == MDB_SET_RANGE && !exactp) {
6867                                 rc = 0;
6868                                 goto set1;
6869                         } else
6870                                 return MDB_NOTFOUND;
6871                 }
6872         } else {
6873                 mc->mc_pg[0] = 0;
6874         }
6875
6876         rc = mdb_page_search(mc, key, 0);
6877         if (rc != MDB_SUCCESS)
6878                 return rc;
6879
6880         mp = mc->mc_pg[mc->mc_top];
6881         mdb_cassert(mc, IS_LEAF(mp));
6882
6883 set2:
6884         leaf = mdb_node_search(mc, key, exactp);
6885         if (exactp != NULL && !*exactp) {
6886                 /* MDB_SET specified and not an exact match. */
6887                 return MDB_NOTFOUND;
6888         }
6889
6890         if (leaf == NULL) {
6891                 DPUTS("===> inexact leaf not found, goto sibling");
6892                 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6893                         mc->mc_flags |= C_EOF;
6894                         return rc;              /* no entries matched */
6895                 }
6896                 mp = mc->mc_pg[mc->mc_top];
6897                 mdb_cassert(mc, IS_LEAF(mp));
6898                 leaf = NODEPTR(mp, 0);
6899         }
6900
6901 set1:
6902         mc->mc_flags |= C_INITIALIZED;
6903         mc->mc_flags &= ~C_EOF;
6904
6905         if (IS_LEAF2(mp)) {
6906                 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
6907                         key->mv_size = mc->mc_db->md_pad;
6908                         key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6909                 }
6910                 return MDB_SUCCESS;
6911         }
6912
6913         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6914                 mdb_xcursor_init1(mc, leaf);
6915         }
6916         if (data) {
6917                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6918                         if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
6919                                 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6920                         } else {
6921                                 int ex2, *ex2p;
6922                                 if (op == MDB_GET_BOTH) {
6923                                         ex2p = &ex2;
6924                                         ex2 = 0;
6925                                 } else {
6926                                         ex2p = NULL;
6927                                 }
6928                                 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
6929                                 if (rc != MDB_SUCCESS)
6930                                         return rc;
6931                         }
6932                 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
6933                         MDB_val olddata;
6934                         MDB_cmp_func *dcmp;
6935                         if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
6936                                 return rc;
6937                         dcmp = mc->mc_dbx->md_dcmp;
6938                         if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
6939                                 dcmp = mdb_cmp_clong;
6940                         rc = dcmp(data, &olddata);
6941                         if (rc) {
6942                                 if (op == MDB_GET_BOTH || rc > 0)
6943                                         return MDB_NOTFOUND;
6944                                 rc = 0;
6945                         }
6946                         *data = olddata;
6947
6948                 } else {
6949                         if (mc->mc_xcursor)
6950                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6951                         if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6952                                 return rc;
6953                 }
6954         }
6955
6956         /* The key already matches in all other cases */
6957         if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6958                 MDB_GET_KEY(leaf, key);
6959         DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6960
6961         return rc;
6962 }
6963
6964 /** Move the cursor to the first item in the database. */
6965 static int
6966 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6967 {
6968         int              rc;
6969         MDB_node        *leaf;
6970
6971         if (mc->mc_xcursor) {
6972                 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6973                 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6974         }
6975
6976         if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6977                 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6978                 if (rc != MDB_SUCCESS)
6979                         return rc;
6980         }
6981         mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6982
6983         leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6984         mc->mc_flags |= C_INITIALIZED;
6985         mc->mc_flags &= ~C_EOF;
6986
6987         mc->mc_ki[mc->mc_top] = 0;
6988
6989         if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6990                 key->mv_size = mc->mc_db->md_pad;
6991                 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
6992                 return MDB_SUCCESS;
6993         }
6994
6995         if (data) {
6996                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6997                         mdb_xcursor_init1(mc, leaf);
6998                         rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6999                         if (rc)
7000                                 return rc;
7001                 } else {
7002                         if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
7003                                 return rc;
7004                 }
7005         }
7006         MDB_GET_KEY(leaf, key);
7007         return MDB_SUCCESS;
7008 }
7009
7010 /** Move the cursor to the last item in the database. */
7011 static int
7012 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
7013 {
7014         int              rc;
7015         MDB_node        *leaf;
7016
7017         if (mc->mc_xcursor) {
7018                 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
7019                 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
7020         }
7021
7022         if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
7023                 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
7024                 if (rc != MDB_SUCCESS)
7025                         return rc;
7026         }
7027         mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
7028
7029         mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
7030         mc->mc_flags |= C_INITIALIZED|C_EOF;
7031         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7032
7033         if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7034                 key->mv_size = mc->mc_db->md_pad;
7035                 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
7036                 return MDB_SUCCESS;
7037         }
7038
7039         if (data) {
7040                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7041                         mdb_xcursor_init1(mc, leaf);
7042                         rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
7043                         if (rc)
7044                                 return rc;
7045                 } else {
7046                         if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
7047                                 return rc;
7048                 }
7049         }
7050
7051         MDB_GET_KEY(leaf, key);
7052         return MDB_SUCCESS;
7053 }
7054
7055 int
7056 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7057     MDB_cursor_op op)
7058 {
7059         int              rc;
7060         int              exact = 0;
7061         int              (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
7062
7063         if (mc == NULL)
7064                 return EINVAL;
7065
7066         if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
7067                 return MDB_BAD_TXN;
7068
7069         switch (op) {
7070         case MDB_GET_CURRENT:
7071                 if (!(mc->mc_flags & C_INITIALIZED)) {
7072                         rc = EINVAL;
7073                 } else {
7074                         MDB_page *mp = mc->mc_pg[mc->mc_top];
7075                         int nkeys = NUMKEYS(mp);
7076                         if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
7077                                 mc->mc_ki[mc->mc_top] = nkeys;
7078                                 rc = MDB_NOTFOUND;
7079                                 break;
7080                         }
7081                         rc = MDB_SUCCESS;
7082                         if (IS_LEAF2(mp)) {
7083                                 key->mv_size = mc->mc_db->md_pad;
7084                                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
7085                         } else {
7086                                 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7087                                 MDB_GET_KEY(leaf, key);
7088                                 if (data) {
7089                                         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7090                                                 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
7091                                         } else {
7092                                                 rc = mdb_node_read(mc, leaf, data);
7093                                         }
7094                                 }
7095                         }
7096                 }
7097                 break;
7098         case MDB_GET_BOTH:
7099         case MDB_GET_BOTH_RANGE:
7100                 if (data == NULL) {
7101                         rc = EINVAL;
7102                         break;
7103                 }
7104                 if (mc->mc_xcursor == NULL) {
7105                         rc = MDB_INCOMPATIBLE;
7106                         break;
7107                 }
7108                 /* FALLTHRU */
7109         case MDB_SET:
7110         case MDB_SET_KEY:
7111         case MDB_SET_RANGE:
7112                 if (key == NULL) {
7113                         rc = EINVAL;
7114                 } else {
7115                         rc = mdb_cursor_set(mc, key, data, op,
7116                                 op == MDB_SET_RANGE ? NULL : &exact);
7117                 }
7118                 break;
7119         case MDB_GET_MULTIPLE:
7120                 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7121                         rc = EINVAL;
7122                         break;
7123                 }
7124                 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7125                         rc = MDB_INCOMPATIBLE;
7126                         break;
7127                 }
7128                 rc = MDB_SUCCESS;
7129                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
7130                         (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
7131                         break;
7132                 goto fetchm;
7133         case MDB_NEXT_MULTIPLE:
7134                 if (data == NULL) {
7135                         rc = EINVAL;
7136                         break;
7137                 }
7138                 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7139                         rc = MDB_INCOMPATIBLE;
7140                         break;
7141                 }
7142                 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
7143                 if (rc == MDB_SUCCESS) {
7144                         if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
7145                                 MDB_cursor *mx;
7146 fetchm:
7147                                 mx = &mc->mc_xcursor->mx_cursor;
7148                                 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
7149                                         mx->mc_db->md_pad;
7150                                 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
7151                                 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
7152                         } else {
7153                                 rc = MDB_NOTFOUND;
7154                         }
7155                 }
7156                 break;
7157         case MDB_PREV_MULTIPLE:
7158                 if (data == NULL) {
7159                         rc = EINVAL;
7160                         break;
7161                 }
7162                 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7163                         rc = MDB_INCOMPATIBLE;
7164                         break;
7165                 }
7166                 if (!(mc->mc_flags & C_INITIALIZED))
7167                         rc = mdb_cursor_last(mc, key, data);
7168                 else
7169                         rc = MDB_SUCCESS;
7170                 if (rc == MDB_SUCCESS) {
7171                         MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
7172                         if (mx->mc_flags & C_INITIALIZED) {
7173                                 rc = mdb_cursor_sibling(mx, 0);
7174                                 if (rc == MDB_SUCCESS)
7175                                         goto fetchm;
7176                         } else {
7177                                 rc = MDB_NOTFOUND;
7178                         }
7179                 }
7180                 break;
7181         case MDB_NEXT:
7182         case MDB_NEXT_DUP:
7183         case MDB_NEXT_NODUP:
7184                 rc = mdb_cursor_next(mc, key, data, op);
7185                 break;
7186         case MDB_PREV:
7187         case MDB_PREV_DUP:
7188         case MDB_PREV_NODUP:
7189                 rc = mdb_cursor_prev(mc, key, data, op);
7190                 break;
7191         case MDB_FIRST:
7192                 rc = mdb_cursor_first(mc, key, data);
7193                 break;
7194         case MDB_FIRST_DUP:
7195                 mfunc = mdb_cursor_first;
7196         mmove:
7197                 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7198                         rc = EINVAL;
7199                         break;
7200                 }
7201                 if (mc->mc_xcursor == NULL) {
7202                         rc = MDB_INCOMPATIBLE;
7203                         break;
7204                 }
7205                 {
7206                         MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7207                         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7208                                 MDB_GET_KEY(leaf, key);
7209                                 rc = mdb_node_read(mc, leaf, data);
7210                                 break;
7211                         }
7212                 }
7213                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
7214                         rc = EINVAL;
7215                         break;
7216                 }
7217                 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
7218                 break;
7219         case MDB_LAST:
7220                 rc = mdb_cursor_last(mc, key, data);
7221                 break;
7222         case MDB_LAST_DUP:
7223                 mfunc = mdb_cursor_last;
7224                 goto mmove;
7225         default:
7226                 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
7227                 rc = EINVAL;
7228                 break;
7229         }
7230
7231         if (mc->mc_flags & C_DEL)
7232                 mc->mc_flags ^= C_DEL;
7233
7234         return rc;
7235 }
7236
7237 /** Touch all the pages in the cursor stack. Set mc_top.
7238  *      Makes sure all the pages are writable, before attempting a write operation.
7239  * @param[in] mc The cursor to operate on.
7240  */
7241 static int
7242 mdb_cursor_touch(MDB_cursor *mc)
7243 {
7244         int rc = MDB_SUCCESS;
7245
7246         if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & (DB_DIRTY|DB_DUPDATA))) {
7247                 /* Touch DB record of named DB */
7248                 MDB_cursor mc2;
7249                 MDB_xcursor mcx;
7250                 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
7251                         return MDB_BAD_DBI;
7252                 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
7253                 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
7254                 if (rc)
7255                          return rc;
7256                 *mc->mc_dbflag |= DB_DIRTY;
7257         }
7258         mc->mc_top = 0;
7259         if (mc->mc_snum) {
7260                 do {
7261                         rc = mdb_page_touch(mc);
7262                 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
7263                 mc->mc_top = mc->mc_snum-1;
7264         }
7265         return rc;
7266 }
7267
7268 /** Do not spill pages to disk if txn is getting full, may fail instead */
7269 #define MDB_NOSPILL     0x8000
7270
7271 int
7272 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7273     unsigned int flags)
7274 {
7275         MDB_env         *env;
7276         MDB_node        *leaf = NULL;
7277         MDB_page        *fp, *mp, *sub_root = NULL;
7278         uint16_t        fp_flags;
7279         MDB_val         xdata, *rdata, dkey, olddata;
7280         MDB_db dummy;
7281         int do_sub = 0, insert_key, insert_data;
7282         unsigned int mcount = 0, dcount = 0, nospill;
7283         size_t nsize;
7284         int rc, rc2;
7285         unsigned int nflags;
7286         DKBUF;
7287
7288         if (mc == NULL || key == NULL)
7289                 return EINVAL;
7290
7291         env = mc->mc_txn->mt_env;
7292
7293         /* Check this first so counter will always be zero on any
7294          * early failures.
7295          */
7296         if (flags & MDB_MULTIPLE) {
7297                 dcount = data[1].mv_size;
7298                 data[1].mv_size = 0;
7299                 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
7300                         return MDB_INCOMPATIBLE;
7301         }
7302
7303         nospill = flags & MDB_NOSPILL;
7304         flags &= ~MDB_NOSPILL;
7305
7306         if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7307                 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7308
7309         if (key->mv_size-1 >= ENV_MAXKEY(env))
7310                 return MDB_BAD_VALSIZE;
7311
7312 #if SIZE_MAX > MAXDATASIZE
7313         if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
7314                 return MDB_BAD_VALSIZE;
7315 #else
7316         if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
7317                 return MDB_BAD_VALSIZE;
7318 #endif
7319
7320         DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
7321                 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
7322
7323         dkey.mv_size = 0;
7324
7325         if (flags == MDB_CURRENT) {
7326                 if (!(mc->mc_flags & C_INITIALIZED))
7327                         return EINVAL;
7328                 rc = MDB_SUCCESS;
7329         } else if (mc->mc_db->md_root == P_INVALID) {
7330                 /* new database, cursor has nothing to point to */
7331                 mc->mc_snum = 0;
7332                 mc->mc_top = 0;
7333                 mc->mc_flags &= ~C_INITIALIZED;
7334                 rc = MDB_NO_ROOT;
7335         } else {
7336                 int exact = 0;
7337                 MDB_val d2;
7338                 if (flags & MDB_APPEND) {
7339                         MDB_val k2;
7340                         rc = mdb_cursor_last(mc, &k2, &d2);
7341                         if (rc == 0) {
7342                                 rc = mc->mc_dbx->md_cmp(key, &k2);
7343                                 if (rc > 0) {
7344                                         rc = MDB_NOTFOUND;
7345                                         mc->mc_ki[mc->mc_top]++;
7346                                 } else {
7347                                         /* new key is <= last key */
7348                                         rc = MDB_KEYEXIST;
7349                                 }
7350                         }
7351                 } else {
7352                         rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
7353                 }
7354                 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
7355                         DPRINTF(("duplicate key [%s]", DKEY(key)));
7356                         *data = d2;
7357                         return MDB_KEYEXIST;
7358                 }
7359                 if (rc && rc != MDB_NOTFOUND)
7360                         return rc;
7361         }
7362
7363         if (mc->mc_flags & C_DEL)
7364                 mc->mc_flags ^= C_DEL;
7365
7366         /* Cursor is positioned, check for room in the dirty list */
7367         if (!nospill) {
7368                 if (flags & MDB_MULTIPLE) {
7369                         rdata = &xdata;
7370                         xdata.mv_size = data->mv_size * dcount;
7371                 } else {
7372                         rdata = data;
7373                 }
7374                 if ((rc2 = mdb_page_spill(mc, key, rdata)))
7375                         return rc2;
7376         }
7377
7378         if (rc == MDB_NO_ROOT) {
7379                 MDB_page *np;
7380                 /* new database, write a root leaf page */
7381                 DPUTS("allocating new root leaf page");
7382                 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
7383                         return rc2;
7384                 }
7385                 mdb_cursor_push(mc, np);
7386                 mc->mc_db->md_root = np->mp_pgno;
7387                 mc->mc_db->md_depth++;
7388                 *mc->mc_dbflag |= DB_DIRTY;
7389                 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
7390                         == MDB_DUPFIXED)
7391                         np->mp_flags |= P_LEAF2;
7392                 mc->mc_flags |= C_INITIALIZED;
7393         } else {
7394                 /* make sure all cursor pages are writable */
7395                 rc2 = mdb_cursor_touch(mc);
7396                 if (rc2)
7397                         return rc2;
7398         }
7399
7400         insert_key = insert_data = rc;
7401         if (insert_key) {
7402                 /* The key does not exist */
7403                 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
7404                 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
7405                         LEAFSIZE(key, data) > env->me_nodemax)
7406                 {
7407                         /* Too big for a node, insert in sub-DB.  Set up an empty
7408                          * "old sub-page" for prep_subDB to expand to a full page.
7409                          */
7410                         fp_flags = P_LEAF|P_DIRTY;
7411                         fp = env->me_pbuf;
7412                         fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
7413                         fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
7414                         olddata.mv_size = PAGEHDRSZ;
7415                         goto prep_subDB;
7416                 }
7417         } else {
7418                 /* there's only a key anyway, so this is a no-op */
7419                 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7420                         char *ptr;
7421                         unsigned int ksize = mc->mc_db->md_pad;
7422                         if (key->mv_size != ksize)
7423                                 return MDB_BAD_VALSIZE;
7424                         ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
7425                         memcpy(ptr, key->mv_data, ksize);
7426 fix_parent:
7427                         /* if overwriting slot 0 of leaf, need to
7428                          * update branch key if there is a parent page
7429                          */
7430                         if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7431                                 unsigned short dtop = 1;
7432                                 mc->mc_top--;
7433                                 /* slot 0 is always an empty key, find real slot */
7434                                 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7435                                         mc->mc_top--;
7436                                         dtop++;
7437                                 }
7438                                 if (mc->mc_ki[mc->mc_top])
7439                                         rc2 = mdb_update_key(mc, key);
7440                                 else
7441                                         rc2 = MDB_SUCCESS;
7442                                 mc->mc_top += dtop;
7443                                 if (rc2)
7444                                         return rc2;
7445                         }
7446                         return MDB_SUCCESS;
7447                 }
7448
7449 more:
7450                 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7451                 olddata.mv_size = NODEDSZ(leaf);
7452                 olddata.mv_data = NODEDATA(leaf);
7453
7454                 /* DB has dups? */
7455                 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
7456                         /* Prepare (sub-)page/sub-DB to accept the new item,
7457                          * if needed.  fp: old sub-page or a header faking
7458                          * it.  mp: new (sub-)page.  offset: growth in page
7459                          * size.  xdata: node data with new page or DB.
7460                          */
7461                         unsigned        i, offset = 0;
7462                         mp = fp = xdata.mv_data = env->me_pbuf;
7463                         mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
7464
7465                         /* Was a single item before, must convert now */
7466                         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7467                                 MDB_cmp_func *dcmp;
7468                                 /* Just overwrite the current item */
7469                                 if (flags == MDB_CURRENT)
7470                                         goto current;
7471                                 dcmp = mc->mc_dbx->md_dcmp;
7472                                 if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
7473                                         dcmp = mdb_cmp_clong;
7474                                 /* does data match? */
7475                                 if (!dcmp(data, &olddata)) {
7476                                         if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
7477                                                 return MDB_KEYEXIST;
7478                                         /* overwrite it */
7479                                         goto current;
7480                                 }
7481
7482                                 /* Back up original data item */
7483                                 dkey.mv_size = olddata.mv_size;
7484                                 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
7485
7486                                 /* Make sub-page header for the dup items, with dummy body */
7487                                 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
7488                                 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
7489                                 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
7490                                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7491                                         fp->mp_flags |= P_LEAF2;
7492                                         fp->mp_pad = data->mv_size;
7493                                         xdata.mv_size += 2 * data->mv_size;     /* leave space for 2 more */
7494                                 } else {
7495                                         xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
7496                                                 (dkey.mv_size & 1) + (data->mv_size & 1);
7497                                 }
7498                                 fp->mp_upper = xdata.mv_size - PAGEBASE;
7499                                 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
7500                         } else if (leaf->mn_flags & F_SUBDATA) {
7501                                 /* Data is on sub-DB, just store it */
7502                                 flags |= F_DUPDATA|F_SUBDATA;
7503                                 goto put_sub;
7504                         } else {
7505                                 /* Data is on sub-page */
7506                                 fp = olddata.mv_data;
7507                                 switch (flags) {
7508                                 default:
7509                                         if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7510                                                 offset = EVEN(NODESIZE + sizeof(indx_t) +
7511                                                         data->mv_size);
7512                                                 break;
7513                                         }
7514                                         offset = fp->mp_pad;
7515                                         if (SIZELEFT(fp) < offset) {
7516                                                 offset *= 4; /* space for 4 more */
7517                                                 break;
7518                                         }
7519                                         /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
7520                                 case MDB_CURRENT:
7521                                         fp->mp_flags |= P_DIRTY;
7522                                         COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
7523                                         mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
7524                                         flags |= F_DUPDATA;
7525                                         goto put_sub;
7526                                 }
7527                                 xdata.mv_size = olddata.mv_size + offset;
7528                         }
7529
7530                         fp_flags = fp->mp_flags;
7531                         if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
7532                                         /* Too big for a sub-page, convert to sub-DB */
7533                                         fp_flags &= ~P_SUBP;
7534 prep_subDB:
7535                                         if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7536                                                 fp_flags |= P_LEAF2;
7537                                                 dummy.md_pad = fp->mp_pad;
7538                                                 dummy.md_flags = MDB_DUPFIXED;
7539                                                 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7540                                                         dummy.md_flags |= MDB_INTEGERKEY;
7541                                         } else {
7542                                                 dummy.md_pad = 0;
7543                                                 dummy.md_flags = 0;
7544                                         }
7545                                         dummy.md_depth = 1;
7546                                         dummy.md_branch_pages = 0;
7547                                         dummy.md_leaf_pages = 1;
7548                                         dummy.md_overflow_pages = 0;
7549                                         dummy.md_entries = NUMKEYS(fp);
7550                                         xdata.mv_size = sizeof(MDB_db);
7551                                         xdata.mv_data = &dummy;
7552                                         if ((rc = mdb_page_alloc(mc, 1, &mp)))
7553                                                 return rc;
7554                                         offset = env->me_psize - olddata.mv_size;
7555                                         flags |= F_DUPDATA|F_SUBDATA;
7556                                         dummy.md_root = mp->mp_pgno;
7557                                         sub_root = mp;
7558                         }
7559                         if (mp != fp) {
7560                                 mp->mp_flags = fp_flags | P_DIRTY;
7561                                 mp->mp_pad   = fp->mp_pad;
7562                                 mp->mp_lower = fp->mp_lower;
7563                                 mp->mp_upper = fp->mp_upper + offset;
7564                                 if (fp_flags & P_LEAF2) {
7565                                         memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
7566                                 } else {
7567                                         memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
7568                                                 olddata.mv_size - fp->mp_upper - PAGEBASE);
7569                                         for (i=0; i<NUMKEYS(fp); i++)
7570                                                 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
7571                                 }
7572                         }
7573
7574                         rdata = &xdata;
7575                         flags |= F_DUPDATA;
7576                         do_sub = 1;
7577                         if (!insert_key)
7578                                 mdb_node_del(mc, 0);
7579                         goto new_sub;
7580                 }
7581 current:
7582                 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
7583                 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
7584                         return MDB_INCOMPATIBLE;
7585                 /* overflow page overwrites need special handling */
7586                 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7587                         MDB_page *omp;
7588                         pgno_t pg;
7589                         int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
7590
7591                         memcpy(&pg, olddata.mv_data, sizeof(pg));
7592                         if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
7593                                 return rc2;
7594                         ovpages = omp->mp_pages;
7595
7596                         /* Is the ov page large enough? */
7597                         if (ovpages >= dpages) {
7598                           if (!(omp->mp_flags & P_DIRTY) &&
7599                                   (level || (env->me_flags & MDB_WRITEMAP)))
7600                           {
7601                                 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
7602                                 if (rc)
7603                                         return rc;
7604                                 level = 0;              /* dirty in this txn or clean */
7605                           }
7606                           /* Is it dirty? */
7607                           if (omp->mp_flags & P_DIRTY) {
7608                                 /* yes, overwrite it. Note in this case we don't
7609                                  * bother to try shrinking the page if the new data
7610                                  * is smaller than the overflow threshold.
7611                                  */
7612                                 if (level > 1) {
7613                                         /* It is writable only in a parent txn */
7614                                         size_t sz = (size_t) env->me_psize * ovpages, off;
7615                                         MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
7616                                         MDB_ID2 id2;
7617                                         if (!np)
7618                                                 return ENOMEM;
7619                                         id2.mid = pg;
7620                                         id2.mptr = np;
7621                                         /* Note - this page is already counted in parent's dirty_room */
7622                                         rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
7623                                         mdb_cassert(mc, rc2 == 0);
7624                                         /* Currently we make the page look as with put() in the
7625                                          * parent txn, in case the user peeks at MDB_RESERVEd
7626                                          * or unused parts. Some users treat ovpages specially.
7627                                          */
7628                                         if (!(flags & MDB_RESERVE)) {
7629                                                 /* Skip the part where LMDB will put *data.
7630                                                  * Copy end of page, adjusting alignment so
7631                                                  * compiler may copy words instead of bytes.
7632                                                  */
7633                                                 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
7634                                                 memcpy((size_t *)((char *)np + off),
7635                                                         (size_t *)((char *)omp + off), sz - off);
7636                                                 sz = PAGEHDRSZ;
7637                                         }
7638                                         memcpy(np, omp, sz); /* Copy beginning of page */
7639                                         omp = np;
7640                                 }
7641                                 SETDSZ(leaf, data->mv_size);
7642                                 if (F_ISSET(flags, MDB_RESERVE))
7643                                         data->mv_data = METADATA(omp);
7644                                 else
7645                                         memcpy(METADATA(omp), data->mv_data, data->mv_size);
7646                                 return MDB_SUCCESS;
7647                           }
7648                         }
7649                         if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
7650                                 return rc2;
7651                 } else if (data->mv_size == olddata.mv_size) {
7652                         /* same size, just replace it. Note that we could
7653                          * also reuse this node if the new data is smaller,
7654                          * but instead we opt to shrink the node in that case.
7655                          */
7656                         if (F_ISSET(flags, MDB_RESERVE))
7657                                 data->mv_data = olddata.mv_data;
7658                         else if (!(mc->mc_flags & C_SUB))
7659                                 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
7660                         else {
7661                                 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
7662                                 goto fix_parent;
7663                         }
7664                         return MDB_SUCCESS;
7665                 }
7666                 mdb_node_del(mc, 0);
7667         }
7668
7669         rdata = data;
7670
7671 new_sub:
7672         nflags = flags & NODE_ADD_FLAGS;
7673         nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
7674         if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
7675                 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
7676                         nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
7677                 if (!insert_key)
7678                         nflags |= MDB_SPLIT_REPLACE;
7679                 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
7680         } else {
7681                 /* There is room already in this leaf page. */
7682                 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
7683                 if (rc == 0) {
7684                         /* Adjust other cursors pointing to mp */
7685                         MDB_cursor *m2, *m3;
7686                         MDB_dbi dbi = mc->mc_dbi;
7687                         unsigned i = mc->mc_top;
7688                         MDB_page *mp = mc->mc_pg[i];
7689
7690                         for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7691                                 if (mc->mc_flags & C_SUB)
7692                                         m3 = &m2->mc_xcursor->mx_cursor;
7693                                 else
7694                                         m3 = m2;
7695                                 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
7696                                 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
7697                                         m3->mc_ki[i]++;
7698                                 }
7699                                 if (XCURSOR_INITED(m3))
7700                                         XCURSOR_REFRESH(m3, mp, m3->mc_ki[i]);
7701                         }
7702                 }
7703         }
7704
7705         if (rc == MDB_SUCCESS) {
7706                 /* Now store the actual data in the child DB. Note that we're
7707                  * storing the user data in the keys field, so there are strict
7708                  * size limits on dupdata. The actual data fields of the child
7709                  * DB are all zero size.
7710                  */
7711                 if (do_sub) {
7712                         int xflags, new_dupdata;
7713                         mdb_size_t ecount;
7714 put_sub:
7715                         xdata.mv_size = 0;
7716                         xdata.mv_data = "";
7717                         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7718                         if (flags & MDB_CURRENT) {
7719                                 xflags = MDB_CURRENT|MDB_NOSPILL;
7720                         } else {
7721                                 mdb_xcursor_init1(mc, leaf);
7722                                 xflags = (flags & MDB_NODUPDATA) ?
7723                                         MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
7724                         }
7725                         if (sub_root)
7726                                 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
7727                         new_dupdata = (int)dkey.mv_size;
7728                         /* converted, write the original data first */
7729                         if (dkey.mv_size) {
7730                                 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
7731                                 if (rc)
7732                                         goto bad_sub;
7733                                 /* we've done our job */
7734                                 dkey.mv_size = 0;
7735                         }
7736                         if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
7737                                 /* Adjust other cursors pointing to mp */
7738                                 MDB_cursor *m2;
7739                                 MDB_xcursor *mx = mc->mc_xcursor;
7740                                 unsigned i = mc->mc_top;
7741                                 MDB_page *mp = mc->mc_pg[i];
7742                                 int nkeys = NUMKEYS(mp);
7743
7744                                 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7745                                         if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7746                                         if (!(m2->mc_flags & C_INITIALIZED)) continue;
7747                                         if (m2->mc_pg[i] == mp) {
7748                                                 if (m2->mc_ki[i] == mc->mc_ki[i]) {
7749                                                         mdb_xcursor_init2(m2, mx, new_dupdata);
7750                                                 } else if (!insert_key && m2->mc_ki[i] < nkeys) {
7751                                                         XCURSOR_REFRESH(m2, mp, m2->mc_ki[i]);
7752                                                 }
7753                                         }
7754                                 }
7755                         }
7756                         ecount = mc->mc_xcursor->mx_db.md_entries;
7757                         if (flags & MDB_APPENDDUP)
7758                                 xflags |= MDB_APPEND;
7759                         rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
7760                         if (flags & F_SUBDATA) {
7761                                 void *db = NODEDATA(leaf);
7762                                 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7763                         }
7764                         insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
7765                 }
7766                 /* Increment count unless we just replaced an existing item. */
7767                 if (insert_data)
7768                         mc->mc_db->md_entries++;
7769                 if (insert_key) {
7770                         /* Invalidate txn if we created an empty sub-DB */
7771                         if (rc)
7772                                 goto bad_sub;
7773                         /* If we succeeded and the key didn't exist before,
7774                          * make sure the cursor is marked valid.
7775                          */
7776                         mc->mc_flags |= C_INITIALIZED;
7777                 }
7778                 if (flags & MDB_MULTIPLE) {
7779                         if (!rc) {
7780                                 mcount++;
7781                                 /* let caller know how many succeeded, if any */
7782                                 data[1].mv_size = mcount;
7783                                 if (mcount < dcount) {
7784                                         data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
7785                                         insert_key = insert_data = 0;
7786                                         goto more;
7787                                 }
7788                         }
7789                 }
7790                 return rc;
7791 bad_sub:
7792                 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
7793                         rc = MDB_PROBLEM;
7794         }
7795         mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7796         return rc;
7797 }
7798
7799 int
7800 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
7801 {
7802         MDB_node        *leaf;
7803         MDB_page        *mp;
7804         int rc;
7805
7806         if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7807                 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7808
7809         if (!(mc->mc_flags & C_INITIALIZED))
7810                 return EINVAL;
7811
7812         if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
7813                 return MDB_NOTFOUND;
7814
7815         if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
7816                 return rc;
7817
7818         rc = mdb_cursor_touch(mc);
7819         if (rc)
7820                 return rc;
7821
7822         mp = mc->mc_pg[mc->mc_top];
7823         if (IS_LEAF2(mp))
7824                 goto del_key;
7825         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7826
7827         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7828                 if (flags & MDB_NODUPDATA) {
7829                         /* mdb_cursor_del0() will subtract the final entry */
7830                         mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
7831                         mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7832                 } else {
7833                         if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
7834                                 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7835                         }
7836                         rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
7837                         if (rc)
7838                                 return rc;
7839                         /* If sub-DB still has entries, we're done */
7840                         if (mc->mc_xcursor->mx_db.md_entries) {
7841                                 if (leaf->mn_flags & F_SUBDATA) {
7842                                         /* update subDB info */
7843                                         void *db = NODEDATA(leaf);
7844                                         memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7845                                 } else {
7846                                         MDB_cursor *m2;
7847                                         /* shrink fake page */
7848                                         mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
7849                                         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7850                                         mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7851                                         /* fix other sub-DB cursors pointed at fake pages on this page */
7852                                         for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7853                                                 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7854                                                 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7855                                                 if (m2->mc_pg[mc->mc_top] == mp) {
7856                                                         MDB_node *n2 = leaf;
7857                                                         if (m2->mc_ki[mc->mc_top] != mc->mc_ki[mc->mc_top]) {
7858                                                                 n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
7859                                                                 if (n2->mn_flags & F_SUBDATA) continue;
7860                                                         }
7861                                                         m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7862                                                 }
7863                                         }
7864                                 }
7865                                 mc->mc_db->md_entries--;
7866                                 return rc;
7867                         } else {
7868                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7869                         }
7870                         /* otherwise fall thru and delete the sub-DB */
7871                 }
7872
7873                 if (leaf->mn_flags & F_SUBDATA) {
7874                         /* add all the child DB's pages to the free list */
7875                         rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7876                         if (rc)
7877                                 goto fail;
7878                 }
7879         }
7880         /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
7881         else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
7882                 rc = MDB_INCOMPATIBLE;
7883                 goto fail;
7884         }
7885
7886         /* add overflow pages to free list */
7887         if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7888                 MDB_page *omp;
7889                 pgno_t pg;
7890
7891                 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7892                 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
7893                         (rc = mdb_ovpage_free(mc, omp)))
7894                         goto fail;
7895         }
7896
7897 del_key:
7898         return mdb_cursor_del0(mc);
7899
7900 fail:
7901         mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7902         return rc;
7903 }
7904
7905 /** Allocate and initialize new pages for a database.
7906  * Set #MDB_TXN_ERROR on failure.
7907  * @param[in] mc a cursor on the database being added to.
7908  * @param[in] flags flags defining what type of page is being allocated.
7909  * @param[in] num the number of pages to allocate. This is usually 1,
7910  * unless allocating overflow pages for a large record.
7911  * @param[out] mp Address of a page, or NULL on failure.
7912  * @return 0 on success, non-zero on failure.
7913  */
7914 static int
7915 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
7916 {
7917         MDB_page        *np;
7918         int rc;
7919
7920         if ((rc = mdb_page_alloc(mc, num, &np)))
7921                 return rc;
7922         DPRINTF(("allocated new mpage %"Yu", page size %u",
7923             np->mp_pgno, mc->mc_txn->mt_env->me_psize));
7924         np->mp_flags = flags | P_DIRTY;
7925         np->mp_lower = (PAGEHDRSZ-PAGEBASE);
7926         np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
7927
7928         if (IS_BRANCH(np))
7929                 mc->mc_db->md_branch_pages++;
7930         else if (IS_LEAF(np))
7931                 mc->mc_db->md_leaf_pages++;
7932         else if (IS_OVERFLOW(np)) {
7933                 mc->mc_db->md_overflow_pages += num;
7934                 np->mp_pages = num;
7935         }
7936         *mp = np;
7937
7938         return 0;
7939 }
7940
7941 /** Calculate the size of a leaf node.
7942  * The size depends on the environment's page size; if a data item
7943  * is too large it will be put onto an overflow page and the node
7944  * size will only include the key and not the data. Sizes are always
7945  * rounded up to an even number of bytes, to guarantee 2-byte alignment
7946  * of the #MDB_node headers.
7947  * @param[in] env The environment handle.
7948  * @param[in] key The key for the node.
7949  * @param[in] data The data for the node.
7950  * @return The number of bytes needed to store the node.
7951  */
7952 static size_t
7953 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
7954 {
7955         size_t           sz;
7956
7957         sz = LEAFSIZE(key, data);
7958         if (sz > env->me_nodemax) {
7959                 /* put on overflow page */
7960                 sz -= data->mv_size - sizeof(pgno_t);
7961         }
7962
7963         return EVEN(sz + sizeof(indx_t));
7964 }
7965
7966 /** Calculate the size of a branch node.
7967  * The size should depend on the environment's page size but since
7968  * we currently don't support spilling large keys onto overflow
7969  * pages, it's simply the size of the #MDB_node header plus the
7970  * size of the key. Sizes are always rounded up to an even number
7971  * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7972  * @param[in] env The environment handle.
7973  * @param[in] key The key for the node.
7974  * @return The number of bytes needed to store the node.
7975  */
7976 static size_t
7977 mdb_branch_size(MDB_env *env, MDB_val *key)
7978 {
7979         size_t           sz;
7980
7981         sz = INDXSIZE(key);
7982         if (sz > env->me_nodemax) {
7983                 /* put on overflow page */
7984                 /* not implemented */
7985                 /* sz -= key->size - sizeof(pgno_t); */
7986         }
7987
7988         return sz + sizeof(indx_t);
7989 }
7990
7991 /** Add a node to the page pointed to by the cursor.
7992  * Set #MDB_TXN_ERROR on failure.
7993  * @param[in] mc The cursor for this operation.
7994  * @param[in] indx The index on the page where the new node should be added.
7995  * @param[in] key The key for the new node.
7996  * @param[in] data The data for the new node, if any.
7997  * @param[in] pgno The page number, if adding a branch node.
7998  * @param[in] flags Flags for the node.
7999  * @return 0 on success, non-zero on failure. Possible errors are:
8000  * <ul>
8001  *      <li>ENOMEM - failed to allocate overflow pages for the node.
8002  *      <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
8003  *      should never happen since all callers already calculate the
8004  *      page's free space before calling this function.
8005  * </ul>
8006  */
8007 static int
8008 mdb_node_add(MDB_cursor *mc, indx_t indx,
8009     MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
8010 {
8011         unsigned int     i;
8012         size_t           node_size = NODESIZE;
8013         ssize_t          room;
8014         indx_t           ofs;
8015         MDB_node        *node;
8016         MDB_page        *mp = mc->mc_pg[mc->mc_top];
8017         MDB_page        *ofp = NULL;            /* overflow page */
8018         void            *ndata;
8019         DKBUF;
8020
8021         mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
8022
8023         DPRINTF(("add to %s %spage %"Yu" index %i, data size %"Z"u key size %"Z"u [%s]",
8024             IS_LEAF(mp) ? "leaf" : "branch",
8025                 IS_SUBP(mp) ? "sub-" : "",
8026                 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
8027                 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
8028
8029         if (IS_LEAF2(mp)) {
8030                 /* Move higher keys up one slot. */
8031                 int ksize = mc->mc_db->md_pad, dif;
8032                 char *ptr = LEAF2KEY(mp, indx, ksize);
8033                 dif = NUMKEYS(mp) - indx;
8034                 if (dif > 0)
8035                         memmove(ptr+ksize, ptr, dif*ksize);
8036                 /* insert new key */
8037                 memcpy(ptr, key->mv_data, ksize);
8038
8039                 /* Just using these for counting */
8040                 mp->mp_lower += sizeof(indx_t);
8041                 mp->mp_upper -= ksize - sizeof(indx_t);
8042                 return MDB_SUCCESS;
8043         }
8044
8045         room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
8046         if (key != NULL)
8047                 node_size += key->mv_size;
8048         if (IS_LEAF(mp)) {
8049                 mdb_cassert(mc, key && data);
8050                 if (F_ISSET(flags, F_BIGDATA)) {
8051                         /* Data already on overflow page. */
8052                         node_size += sizeof(pgno_t);
8053                 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
8054                         int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
8055                         int rc;
8056                         /* Put data on overflow page. */
8057                         DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
8058                             data->mv_size, node_size+data->mv_size));
8059                         node_size = EVEN(node_size + sizeof(pgno_t));
8060                         if ((ssize_t)node_size > room)
8061                                 goto full;
8062                         if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
8063                                 return rc;
8064                         DPRINTF(("allocated overflow page %"Yu, ofp->mp_pgno));
8065                         flags |= F_BIGDATA;
8066                         goto update;
8067                 } else {
8068                         node_size += data->mv_size;
8069                 }
8070         }
8071         node_size = EVEN(node_size);
8072         if ((ssize_t)node_size > room)
8073                 goto full;
8074
8075 update:
8076         /* Move higher pointers up one slot. */
8077         for (i = NUMKEYS(mp); i > indx; i--)
8078                 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
8079
8080         /* Adjust free space offsets. */
8081         ofs = mp->mp_upper - node_size;
8082         mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
8083         mp->mp_ptrs[indx] = ofs;
8084         mp->mp_upper = ofs;
8085         mp->mp_lower += sizeof(indx_t);
8086
8087         /* Write the node data. */
8088         node = NODEPTR(mp, indx);
8089         node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
8090         node->mn_flags = flags;
8091         if (IS_LEAF(mp))
8092                 SETDSZ(node,data->mv_size);
8093         else
8094                 SETPGNO(node,pgno);
8095
8096         if (key)
8097                 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8098
8099         if (IS_LEAF(mp)) {
8100                 ndata = NODEDATA(node);
8101                 if (ofp == NULL) {
8102                         if (F_ISSET(flags, F_BIGDATA))
8103                                 memcpy(ndata, data->mv_data, sizeof(pgno_t));
8104                         else if (F_ISSET(flags, MDB_RESERVE))
8105                                 data->mv_data = ndata;
8106                         else
8107                                 memcpy(ndata, data->mv_data, data->mv_size);
8108                 } else {
8109                         memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
8110                         ndata = METADATA(ofp);
8111                         if (F_ISSET(flags, MDB_RESERVE))
8112                                 data->mv_data = ndata;
8113                         else
8114                                 memcpy(ndata, data->mv_data, data->mv_size);
8115                 }
8116         }
8117
8118         return MDB_SUCCESS;
8119
8120 full:
8121         DPRINTF(("not enough room in page %"Yu", got %u ptrs",
8122                 mdb_dbg_pgno(mp), NUMKEYS(mp)));
8123         DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
8124         DPRINTF(("node size = %"Z"u", node_size));
8125         mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8126         return MDB_PAGE_FULL;
8127 }
8128
8129 /** Delete the specified node from a page.
8130  * @param[in] mc Cursor pointing to the node to delete.
8131  * @param[in] ksize The size of a node. Only used if the page is
8132  * part of a #MDB_DUPFIXED database.
8133  */
8134 static void
8135 mdb_node_del(MDB_cursor *mc, int ksize)
8136 {
8137         MDB_page *mp = mc->mc_pg[mc->mc_top];
8138         indx_t  indx = mc->mc_ki[mc->mc_top];
8139         unsigned int     sz;
8140         indx_t           i, j, numkeys, ptr;
8141         MDB_node        *node;
8142         char            *base;
8143
8144         DPRINTF(("delete node %u on %s page %"Yu, indx,
8145             IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
8146         numkeys = NUMKEYS(mp);
8147         mdb_cassert(mc, indx < numkeys);
8148
8149         if (IS_LEAF2(mp)) {
8150                 int x = numkeys - 1 - indx;
8151                 base = LEAF2KEY(mp, indx, ksize);
8152                 if (x)
8153                         memmove(base, base + ksize, x * ksize);
8154                 mp->mp_lower -= sizeof(indx_t);
8155                 mp->mp_upper += ksize - sizeof(indx_t);
8156                 return;
8157         }
8158
8159         node = NODEPTR(mp, indx);
8160         sz = NODESIZE + node->mn_ksize;
8161         if (IS_LEAF(mp)) {
8162                 if (F_ISSET(node->mn_flags, F_BIGDATA))
8163                         sz += sizeof(pgno_t);
8164                 else
8165                         sz += NODEDSZ(node);
8166         }
8167         sz = EVEN(sz);
8168
8169         ptr = mp->mp_ptrs[indx];
8170         for (i = j = 0; i < numkeys; i++) {
8171                 if (i != indx) {
8172                         mp->mp_ptrs[j] = mp->mp_ptrs[i];
8173                         if (mp->mp_ptrs[i] < ptr)
8174                                 mp->mp_ptrs[j] += sz;
8175                         j++;
8176                 }
8177         }
8178
8179         base = (char *)mp + mp->mp_upper + PAGEBASE;
8180         memmove(base + sz, base, ptr - mp->mp_upper);
8181
8182         mp->mp_lower -= sizeof(indx_t);
8183         mp->mp_upper += sz;
8184 }
8185
8186 /** Compact the main page after deleting a node on a subpage.
8187  * @param[in] mp The main page to operate on.
8188  * @param[in] indx The index of the subpage on the main page.
8189  */
8190 static void
8191 mdb_node_shrink(MDB_page *mp, indx_t indx)
8192 {
8193         MDB_node *node;
8194         MDB_page *sp, *xp;
8195         char *base;
8196         indx_t delta, nsize, len, ptr;
8197         int i;
8198
8199         node = NODEPTR(mp, indx);
8200         sp = (MDB_page *)NODEDATA(node);
8201         delta = SIZELEFT(sp);
8202         nsize = NODEDSZ(node) - delta;
8203
8204         /* Prepare to shift upward, set len = length(subpage part to shift) */
8205         if (IS_LEAF2(sp)) {
8206                 len = nsize;
8207                 if (nsize & 1)
8208                         return;         /* do not make the node uneven-sized */
8209         } else {
8210                 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
8211                 for (i = NUMKEYS(sp); --i >= 0; )
8212                         xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
8213                 len = PAGEHDRSZ;
8214         }
8215         sp->mp_upper = sp->mp_lower;
8216         COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
8217         SETDSZ(node, nsize);
8218
8219         /* Shift <lower nodes...initial part of subpage> upward */
8220         base = (char *)mp + mp->mp_upper + PAGEBASE;
8221         memmove(base + delta, base, (char *)sp + len - base);
8222
8223         ptr = mp->mp_ptrs[indx];
8224         for (i = NUMKEYS(mp); --i >= 0; ) {
8225                 if (mp->mp_ptrs[i] <= ptr)
8226                         mp->mp_ptrs[i] += delta;
8227         }
8228         mp->mp_upper += delta;
8229 }
8230
8231 /** Initial setup of a sorted-dups cursor.
8232  * Sorted duplicates are implemented as a sub-database for the given key.
8233  * The duplicate data items are actually keys of the sub-database.
8234  * Operations on the duplicate data items are performed using a sub-cursor
8235  * initialized when the sub-database is first accessed. This function does
8236  * the preliminary setup of the sub-cursor, filling in the fields that
8237  * depend only on the parent DB.
8238  * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8239  */
8240 static void
8241 mdb_xcursor_init0(MDB_cursor *mc)
8242 {
8243         MDB_xcursor *mx = mc->mc_xcursor;
8244
8245         mx->mx_cursor.mc_xcursor = NULL;
8246         mx->mx_cursor.mc_txn = mc->mc_txn;
8247         mx->mx_cursor.mc_db = &mx->mx_db;
8248         mx->mx_cursor.mc_dbx = &mx->mx_dbx;
8249         mx->mx_cursor.mc_dbi = mc->mc_dbi;
8250         mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
8251         mx->mx_cursor.mc_snum = 0;
8252         mx->mx_cursor.mc_top = 0;
8253         MC_SET_OVPG(&mx->mx_cursor, NULL);
8254         mx->mx_cursor.mc_flags = C_SUB | (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP));
8255         mx->mx_dbx.md_name.mv_size = 0;
8256         mx->mx_dbx.md_name.mv_data = NULL;
8257         mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
8258         mx->mx_dbx.md_dcmp = NULL;
8259         mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
8260 }
8261
8262 /** Final setup of a sorted-dups cursor.
8263  *      Sets up the fields that depend on the data from the main cursor.
8264  * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8265  * @param[in] node The data containing the #MDB_db record for the
8266  * sorted-dup database.
8267  */
8268 static void
8269 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
8270 {
8271         MDB_xcursor *mx = mc->mc_xcursor;
8272
8273         mx->mx_cursor.mc_flags &= C_SUB|C_ORIG_RDONLY|C_WRITEMAP;
8274         if (node->mn_flags & F_SUBDATA) {
8275                 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
8276                 mx->mx_cursor.mc_pg[0] = 0;
8277                 mx->mx_cursor.mc_snum = 0;
8278                 mx->mx_cursor.mc_top = 0;
8279         } else {
8280                 MDB_page *fp = NODEDATA(node);
8281                 mx->mx_db.md_pad = 0;
8282                 mx->mx_db.md_flags = 0;
8283                 mx->mx_db.md_depth = 1;
8284                 mx->mx_db.md_branch_pages = 0;
8285                 mx->mx_db.md_leaf_pages = 1;
8286                 mx->mx_db.md_overflow_pages = 0;
8287                 mx->mx_db.md_entries = NUMKEYS(fp);
8288                 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
8289                 mx->mx_cursor.mc_snum = 1;
8290                 mx->mx_cursor.mc_top = 0;
8291                 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8292                 mx->mx_cursor.mc_pg[0] = fp;
8293                 mx->mx_cursor.mc_ki[0] = 0;
8294                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
8295                         mx->mx_db.md_flags = MDB_DUPFIXED;
8296                         mx->mx_db.md_pad = fp->mp_pad;
8297                         if (mc->mc_db->md_flags & MDB_INTEGERDUP)
8298                                 mx->mx_db.md_flags |= MDB_INTEGERKEY;
8299                 }
8300         }
8301         DPRINTF(("Sub-db -%u root page %"Yu, mx->mx_cursor.mc_dbi,
8302                 mx->mx_db.md_root));
8303         mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
8304         if (NEED_CMP_CLONG(mx->mx_dbx.md_cmp, mx->mx_db.md_pad))
8305                 mx->mx_dbx.md_cmp = mdb_cmp_clong;
8306 }
8307
8308
8309 /** Fixup a sorted-dups cursor due to underlying update.
8310  *      Sets up some fields that depend on the data from the main cursor.
8311  *      Almost the same as init1, but skips initialization steps if the
8312  *      xcursor had already been used.
8313  * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
8314  * @param[in] src_mx The xcursor of an up-to-date cursor.
8315  * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
8316  */
8317 static void
8318 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
8319 {
8320         MDB_xcursor *mx = mc->mc_xcursor;
8321
8322         if (new_dupdata) {
8323                 mx->mx_cursor.mc_snum = 1;
8324                 mx->mx_cursor.mc_top = 0;
8325                 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8326                 mx->mx_cursor.mc_ki[0] = 0;
8327                 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
8328 #if UINT_MAX < MDB_SIZE_MAX     /* matches mdb_xcursor_init1:NEED_CMP_CLONG() */
8329                 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
8330 #endif
8331         } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
8332                 return;
8333         }
8334         mx->mx_db = src_mx->mx_db;
8335         mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
8336         DPRINTF(("Sub-db -%u root page %"Yu, mx->mx_cursor.mc_dbi,
8337                 mx->mx_db.md_root));
8338 }
8339
8340 /** Initialize a cursor for a given transaction and database. */
8341 static void
8342 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
8343 {
8344         mc->mc_next = NULL;
8345         mc->mc_backup = NULL;
8346         mc->mc_dbi = dbi;
8347         mc->mc_txn = txn;
8348         mc->mc_db = &txn->mt_dbs[dbi];
8349         mc->mc_dbx = &txn->mt_dbxs[dbi];
8350         mc->mc_dbflag = &txn->mt_dbflags[dbi];
8351         mc->mc_snum = 0;
8352         mc->mc_top = 0;
8353         mc->mc_pg[0] = 0;
8354         mc->mc_ki[0] = 0;
8355         MC_SET_OVPG(mc, NULL);
8356         mc->mc_flags = txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
8357         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
8358                 mdb_tassert(txn, mx != NULL);
8359                 mc->mc_xcursor = mx;
8360                 mdb_xcursor_init0(mc);
8361         } else {
8362                 mc->mc_xcursor = NULL;
8363         }
8364         if (*mc->mc_dbflag & DB_STALE) {
8365                 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
8366         }
8367 }
8368
8369 int
8370 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
8371 {
8372         MDB_cursor      *mc;
8373         size_t size = sizeof(MDB_cursor);
8374
8375         if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
8376                 return EINVAL;
8377
8378         if (txn->mt_flags & MDB_TXN_BLOCKED)
8379                 return MDB_BAD_TXN;
8380
8381         if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8382                 return EINVAL;
8383
8384         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
8385                 size += sizeof(MDB_xcursor);
8386
8387         if ((mc = malloc(size)) != NULL) {
8388                 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
8389                 if (txn->mt_cursors) {
8390                         mc->mc_next = txn->mt_cursors[dbi];
8391                         txn->mt_cursors[dbi] = mc;
8392                         mc->mc_flags |= C_UNTRACK;
8393                 }
8394         } else {
8395                 return ENOMEM;
8396         }
8397
8398         *ret = mc;
8399
8400         return MDB_SUCCESS;
8401 }
8402
8403 int
8404 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
8405 {
8406         if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
8407                 return EINVAL;
8408
8409         if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
8410                 return EINVAL;
8411
8412         if (txn->mt_flags & MDB_TXN_BLOCKED)
8413                 return MDB_BAD_TXN;
8414
8415         mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
8416         return MDB_SUCCESS;
8417 }
8418
8419 /* Return the count of duplicate data items for the current key */
8420 int
8421 mdb_cursor_count(MDB_cursor *mc, mdb_size_t *countp)
8422 {
8423         MDB_node        *leaf;
8424
8425         if (mc == NULL || countp == NULL)
8426                 return EINVAL;
8427
8428         if (mc->mc_xcursor == NULL)
8429                 return MDB_INCOMPATIBLE;
8430
8431         if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
8432                 return MDB_BAD_TXN;
8433
8434         if (!(mc->mc_flags & C_INITIALIZED))
8435                 return EINVAL;
8436
8437         if (!mc->mc_snum || (mc->mc_flags & C_EOF))
8438                 return MDB_NOTFOUND;
8439
8440         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8441         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
8442                 *countp = 1;
8443         } else {
8444                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
8445                         return EINVAL;
8446
8447                 *countp = mc->mc_xcursor->mx_db.md_entries;
8448         }
8449         return MDB_SUCCESS;
8450 }
8451
8452 void
8453 mdb_cursor_close(MDB_cursor *mc)
8454 {
8455         if (mc) {
8456                 MDB_CURSOR_UNREF(mc, 0);
8457         }
8458         if (mc && !mc->mc_backup) {
8459                 /* Remove from txn, if tracked.
8460                  * A read-only txn (!C_UNTRACK) may have been freed already,
8461                  * so do not peek inside it.  Only write txns track cursors.
8462                  */
8463                 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
8464                         MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
8465                         while (*prev && *prev != mc) prev = &(*prev)->mc_next;
8466                         if (*prev == mc)
8467                                 *prev = mc->mc_next;
8468                 }
8469                 free(mc);
8470         }
8471 }
8472
8473 MDB_txn *
8474 mdb_cursor_txn(MDB_cursor *mc)
8475 {
8476         if (!mc) return NULL;
8477         return mc->mc_txn;
8478 }
8479
8480 MDB_dbi
8481 mdb_cursor_dbi(MDB_cursor *mc)
8482 {
8483         return mc->mc_dbi;
8484 }
8485
8486 /** Replace the key for a branch node with a new key.
8487  * Set #MDB_TXN_ERROR on failure.
8488  * @param[in] mc Cursor pointing to the node to operate on.
8489  * @param[in] key The new key to use.
8490  * @return 0 on success, non-zero on failure.
8491  */
8492 static int
8493 mdb_update_key(MDB_cursor *mc, MDB_val *key)
8494 {
8495         MDB_page                *mp;
8496         MDB_node                *node;
8497         char                    *base;
8498         size_t                   len;
8499         int                              delta, ksize, oksize;
8500         indx_t                   ptr, i, numkeys, indx;
8501         DKBUF;
8502
8503         indx = mc->mc_ki[mc->mc_top];
8504         mp = mc->mc_pg[mc->mc_top];
8505         node = NODEPTR(mp, indx);
8506         ptr = mp->mp_ptrs[indx];
8507 #if MDB_DEBUG
8508         {
8509                 MDB_val k2;
8510                 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
8511                 k2.mv_data = NODEKEY(node);
8512                 k2.mv_size = node->mn_ksize;
8513                 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Yu,
8514                         indx, ptr,
8515                         mdb_dkey(&k2, kbuf2),
8516                         DKEY(key),
8517                         mp->mp_pgno));
8518         }
8519 #endif
8520
8521         /* Sizes must be 2-byte aligned. */
8522         ksize = EVEN(key->mv_size);
8523         oksize = EVEN(node->mn_ksize);
8524         delta = ksize - oksize;
8525
8526         /* Shift node contents if EVEN(key length) changed. */
8527         if (delta) {
8528                 if (delta > 0 && SIZELEFT(mp) < delta) {
8529                         pgno_t pgno;
8530                         /* not enough space left, do a delete and split */
8531                         DPRINTF(("Not enough room, delta = %d, splitting...", delta));
8532                         pgno = NODEPGNO(node);
8533                         mdb_node_del(mc, 0);
8534                         return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
8535                 }
8536
8537                 numkeys = NUMKEYS(mp);
8538                 for (i = 0; i < numkeys; i++) {
8539                         if (mp->mp_ptrs[i] <= ptr)
8540                                 mp->mp_ptrs[i] -= delta;
8541                 }
8542
8543                 base = (char *)mp + mp->mp_upper + PAGEBASE;
8544                 len = ptr - mp->mp_upper + NODESIZE;
8545                 memmove(base - delta, base, len);
8546                 mp->mp_upper -= delta;
8547
8548                 node = NODEPTR(mp, indx);
8549         }
8550
8551         /* But even if no shift was needed, update ksize */
8552         if (node->mn_ksize != key->mv_size)
8553                 node->mn_ksize = key->mv_size;
8554
8555         if (key->mv_size)
8556                 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8557
8558         return MDB_SUCCESS;
8559 }
8560
8561 static void
8562 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
8563
8564 /** Perform \b act while tracking temporary cursor \b mn */
8565 #define WITH_CURSOR_TRACKING(mn, act) do { \
8566         MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
8567         if ((mn).mc_flags & C_SUB) { \
8568                 dummy.mc_flags =  C_INITIALIZED; \
8569                 dummy.mc_xcursor = (MDB_xcursor *)&(mn);        \
8570                 tracked = &dummy; \
8571         } else { \
8572                 tracked = &(mn); \
8573         } \
8574         tracked->mc_next = *tp; \
8575         *tp = tracked; \
8576         { act; } \
8577         *tp = tracked->mc_next; \
8578 } while (0)
8579
8580 /** Move a node from csrc to cdst.
8581  */
8582 static int
8583 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
8584 {
8585         MDB_node                *srcnode;
8586         MDB_val          key, data;
8587         pgno_t  srcpg;
8588         MDB_cursor mn;
8589         int                      rc;
8590         unsigned short flags;
8591
8592         DKBUF;
8593
8594         /* Mark src and dst as dirty. */
8595         if ((rc = mdb_page_touch(csrc)) ||
8596             (rc = mdb_page_touch(cdst)))
8597                 return rc;
8598
8599         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8600                 key.mv_size = csrc->mc_db->md_pad;
8601                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
8602                 data.mv_size = 0;
8603                 data.mv_data = NULL;
8604                 srcpg = 0;
8605                 flags = 0;
8606         } else {
8607                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
8608                 mdb_cassert(csrc, !((size_t)srcnode & 1));
8609                 srcpg = NODEPGNO(srcnode);
8610                 flags = srcnode->mn_flags;
8611                 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8612                         unsigned int snum = csrc->mc_snum;
8613                         MDB_node *s2;
8614                         /* must find the lowest key below src */
8615                         rc = mdb_page_search_lowest(csrc);
8616                         if (rc)
8617                                 return rc;
8618                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8619                                 key.mv_size = csrc->mc_db->md_pad;
8620                                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8621                         } else {
8622                                 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8623                                 key.mv_size = NODEKSZ(s2);
8624                                 key.mv_data = NODEKEY(s2);
8625                         }
8626                         csrc->mc_snum = snum--;
8627                         csrc->mc_top = snum;
8628                 } else {
8629                         key.mv_size = NODEKSZ(srcnode);
8630                         key.mv_data = NODEKEY(srcnode);
8631                 }
8632                 data.mv_size = NODEDSZ(srcnode);
8633                 data.mv_data = NODEDATA(srcnode);
8634         }
8635         mn.mc_xcursor = NULL;
8636         if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
8637                 unsigned int snum = cdst->mc_snum;
8638                 MDB_node *s2;
8639                 MDB_val bkey;
8640                 /* must find the lowest key below dst */
8641                 mdb_cursor_copy(cdst, &mn);
8642                 rc = mdb_page_search_lowest(&mn);
8643                 if (rc)
8644                         return rc;
8645                 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8646                         bkey.mv_size = mn.mc_db->md_pad;
8647                         bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
8648                 } else {
8649                         s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8650                         bkey.mv_size = NODEKSZ(s2);
8651                         bkey.mv_data = NODEKEY(s2);
8652                 }
8653                 mn.mc_snum = snum--;
8654                 mn.mc_top = snum;
8655                 mn.mc_ki[snum] = 0;
8656                 rc = mdb_update_key(&mn, &bkey);
8657                 if (rc)
8658                         return rc;
8659         }
8660
8661         DPRINTF(("moving %s node %u [%s] on page %"Yu" to node %u on page %"Yu,
8662             IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
8663             csrc->mc_ki[csrc->mc_top],
8664                 DKEY(&key),
8665             csrc->mc_pg[csrc->mc_top]->mp_pgno,
8666             cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
8667
8668         /* Add the node to the destination page.
8669          */
8670         rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
8671         if (rc != MDB_SUCCESS)
8672                 return rc;
8673
8674         /* Delete the node from the source page.
8675          */
8676         mdb_node_del(csrc, key.mv_size);
8677
8678         {
8679                 /* Adjust other cursors pointing to mp */
8680                 MDB_cursor *m2, *m3;
8681                 MDB_dbi dbi = csrc->mc_dbi;
8682                 MDB_page *mpd, *mps;
8683
8684                 mps = csrc->mc_pg[csrc->mc_top];
8685                 /* If we're adding on the left, bump others up */
8686                 if (fromleft) {
8687                         mpd = cdst->mc_pg[csrc->mc_top];
8688                         for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8689                                 if (csrc->mc_flags & C_SUB)
8690                                         m3 = &m2->mc_xcursor->mx_cursor;
8691                                 else
8692                                         m3 = m2;
8693                                 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8694                                         continue;
8695                                 if (m3 != cdst &&
8696                                         m3->mc_pg[csrc->mc_top] == mpd &&
8697                                         m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
8698                                         m3->mc_ki[csrc->mc_top]++;
8699                                 }
8700                                 if (m3 !=csrc &&
8701                                         m3->mc_pg[csrc->mc_top] == mps &&
8702                                         m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
8703                                         m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8704                                         m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8705                                         m3->mc_ki[csrc->mc_top-1]++;
8706                                 }
8707                                 if (XCURSOR_INITED(m3) && IS_LEAF(mps))
8708                                         XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8709                         }
8710                 } else
8711                 /* Adding on the right, bump others down */
8712                 {
8713                         for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8714                                 if (csrc->mc_flags & C_SUB)
8715                                         m3 = &m2->mc_xcursor->mx_cursor;
8716                                 else
8717                                         m3 = m2;
8718                                 if (m3 == csrc) continue;
8719                                 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8720                                         continue;
8721                                 if (m3->mc_pg[csrc->mc_top] == mps) {
8722                                         if (!m3->mc_ki[csrc->mc_top]) {
8723                                                 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8724                                                 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8725                                                 m3->mc_ki[csrc->mc_top-1]--;
8726                                         } else {
8727                                                 m3->mc_ki[csrc->mc_top]--;
8728                                         }
8729                                         if (XCURSOR_INITED(m3) && IS_LEAF(mps))
8730                                                 XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8731                                 }
8732                         }
8733                 }
8734         }
8735
8736         /* Update the parent separators.
8737          */
8738         if (csrc->mc_ki[csrc->mc_top] == 0) {
8739                 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
8740                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8741                                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8742                         } else {
8743                                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8744                                 key.mv_size = NODEKSZ(srcnode);
8745                                 key.mv_data = NODEKEY(srcnode);
8746                         }
8747                         DPRINTF(("update separator for source page %"Yu" to [%s]",
8748                                 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
8749                         mdb_cursor_copy(csrc, &mn);
8750                         mn.mc_snum--;
8751                         mn.mc_top--;
8752                         /* We want mdb_rebalance to find mn when doing fixups */
8753                         WITH_CURSOR_TRACKING(mn,
8754                                 rc = mdb_update_key(&mn, &key));
8755                         if (rc)
8756                                 return rc;
8757                 }
8758                 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8759                         MDB_val  nullkey;
8760                         indx_t  ix = csrc->mc_ki[csrc->mc_top];
8761                         nullkey.mv_size = 0;
8762                         csrc->mc_ki[csrc->mc_top] = 0;
8763                         rc = mdb_update_key(csrc, &nullkey);
8764                         csrc->mc_ki[csrc->mc_top] = ix;
8765                         mdb_cassert(csrc, rc == MDB_SUCCESS);
8766                 }
8767         }
8768
8769         if (cdst->mc_ki[cdst->mc_top] == 0) {
8770                 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
8771                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8772                                 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
8773                         } else {
8774                                 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
8775                                 key.mv_size = NODEKSZ(srcnode);
8776                                 key.mv_data = NODEKEY(srcnode);
8777                         }
8778                         DPRINTF(("update separator for destination page %"Yu" to [%s]",
8779                                 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
8780                         mdb_cursor_copy(cdst, &mn);
8781                         mn.mc_snum--;
8782                         mn.mc_top--;
8783                         /* We want mdb_rebalance to find mn when doing fixups */
8784                         WITH_CURSOR_TRACKING(mn,
8785                                 rc = mdb_update_key(&mn, &key));
8786                         if (rc)
8787                                 return rc;
8788                 }
8789                 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
8790                         MDB_val  nullkey;
8791                         indx_t  ix = cdst->mc_ki[cdst->mc_top];
8792                         nullkey.mv_size = 0;
8793                         cdst->mc_ki[cdst->mc_top] = 0;
8794                         rc = mdb_update_key(cdst, &nullkey);
8795                         cdst->mc_ki[cdst->mc_top] = ix;
8796                         mdb_cassert(cdst, rc == MDB_SUCCESS);
8797                 }
8798         }
8799
8800         return MDB_SUCCESS;
8801 }
8802
8803 /** Merge one page into another.
8804  *  The nodes from the page pointed to by \b csrc will
8805  *      be copied to the page pointed to by \b cdst and then
8806  *      the \b csrc page will be freed.
8807  * @param[in] csrc Cursor pointing to the source page.
8808  * @param[in] cdst Cursor pointing to the destination page.
8809  * @return 0 on success, non-zero on failure.
8810  */
8811 static int
8812 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
8813 {
8814         MDB_page        *psrc, *pdst;
8815         MDB_node        *srcnode;
8816         MDB_val          key, data;
8817         unsigned         nkeys;
8818         int                      rc;
8819         indx_t           i, j;
8820
8821         psrc = csrc->mc_pg[csrc->mc_top];
8822         pdst = cdst->mc_pg[cdst->mc_top];
8823
8824         DPRINTF(("merging page %"Yu" into %"Yu, psrc->mp_pgno, pdst->mp_pgno));
8825
8826         mdb_cassert(csrc, csrc->mc_snum > 1);   /* can't merge root page */
8827         mdb_cassert(csrc, cdst->mc_snum > 1);
8828
8829         /* Mark dst as dirty. */
8830         if ((rc = mdb_page_touch(cdst)))
8831                 return rc;
8832
8833         /* get dst page again now that we've touched it. */
8834         pdst = cdst->mc_pg[cdst->mc_top];
8835
8836         /* Move all nodes from src to dst.
8837          */
8838         j = nkeys = NUMKEYS(pdst);
8839         if (IS_LEAF2(psrc)) {
8840                 key.mv_size = csrc->mc_db->md_pad;
8841                 key.mv_data = METADATA(psrc);
8842                 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8843                         rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
8844                         if (rc != MDB_SUCCESS)
8845                                 return rc;
8846                         key.mv_data = (char *)key.mv_data + key.mv_size;
8847                 }
8848         } else {
8849                 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8850                         srcnode = NODEPTR(psrc, i);
8851                         if (i == 0 && IS_BRANCH(psrc)) {
8852                                 MDB_cursor mn;
8853                                 MDB_node *s2;
8854                                 mdb_cursor_copy(csrc, &mn);
8855                                 mn.mc_xcursor = NULL;
8856                                 /* must find the lowest key below src */
8857                                 rc = mdb_page_search_lowest(&mn);
8858                                 if (rc)
8859                                         return rc;
8860                                 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8861                                         key.mv_size = mn.mc_db->md_pad;
8862                                         key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
8863                                 } else {
8864                                         s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8865                                         key.mv_size = NODEKSZ(s2);
8866                                         key.mv_data = NODEKEY(s2);
8867                                 }
8868                         } else {
8869                                 key.mv_size = srcnode->mn_ksize;
8870                                 key.mv_data = NODEKEY(srcnode);
8871                         }
8872
8873                         data.mv_size = NODEDSZ(srcnode);
8874                         data.mv_data = NODEDATA(srcnode);
8875                         rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
8876                         if (rc != MDB_SUCCESS)
8877                                 return rc;
8878                 }
8879         }
8880
8881         DPRINTF(("dst page %"Yu" now has %u keys (%.1f%% filled)",
8882             pdst->mp_pgno, NUMKEYS(pdst),
8883                 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
8884
8885         /* Unlink the src page from parent and add to free list.
8886          */
8887         csrc->mc_top--;
8888         mdb_node_del(csrc, 0);
8889         if (csrc->mc_ki[csrc->mc_top] == 0) {
8890                 key.mv_size = 0;
8891                 rc = mdb_update_key(csrc, &key);
8892                 if (rc) {
8893                         csrc->mc_top++;
8894                         return rc;
8895                 }
8896         }
8897         csrc->mc_top++;
8898
8899         psrc = csrc->mc_pg[csrc->mc_top];
8900         /* If not operating on FreeDB, allow this page to be reused
8901          * in this txn. Otherwise just add to free list.
8902          */
8903         rc = mdb_page_loose(csrc, psrc);
8904         if (rc)
8905                 return rc;
8906         if (IS_LEAF(psrc))
8907                 csrc->mc_db->md_leaf_pages--;
8908         else
8909                 csrc->mc_db->md_branch_pages--;
8910         {
8911                 /* Adjust other cursors pointing to mp */
8912                 MDB_cursor *m2, *m3;
8913                 MDB_dbi dbi = csrc->mc_dbi;
8914                 unsigned int top = csrc->mc_top;
8915
8916                 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8917                         if (csrc->mc_flags & C_SUB)
8918                                 m3 = &m2->mc_xcursor->mx_cursor;
8919                         else
8920                                 m3 = m2;
8921                         if (m3 == csrc) continue;
8922                         if (m3->mc_snum < csrc->mc_snum) continue;
8923                         if (m3->mc_pg[top] == psrc) {
8924                                 m3->mc_pg[top] = pdst;
8925                                 m3->mc_ki[top] += nkeys;
8926                                 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
8927                         } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
8928                                 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
8929                                 m3->mc_ki[top-1]--;
8930                         }
8931                         if (XCURSOR_INITED(m3) && IS_LEAF(psrc))
8932                                 XCURSOR_REFRESH(m3, m3->mc_pg[top], m3->mc_ki[top]);
8933                 }
8934         }
8935         {
8936                 unsigned int snum = cdst->mc_snum;
8937                 uint16_t depth = cdst->mc_db->md_depth;
8938                 mdb_cursor_pop(cdst);
8939                 rc = mdb_rebalance(cdst);
8940                 /* Did the tree height change? */
8941                 if (depth != cdst->mc_db->md_depth)
8942                         snum += cdst->mc_db->md_depth - depth;
8943                 cdst->mc_snum = snum;
8944                 cdst->mc_top = snum-1;
8945         }
8946         return rc;
8947 }
8948
8949 /** Copy the contents of a cursor.
8950  * @param[in] csrc The cursor to copy from.
8951  * @param[out] cdst The cursor to copy to.
8952  */
8953 static void
8954 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
8955 {
8956         unsigned int i;
8957
8958         cdst->mc_txn = csrc->mc_txn;
8959         cdst->mc_dbi = csrc->mc_dbi;
8960         cdst->mc_db  = csrc->mc_db;
8961         cdst->mc_dbx = csrc->mc_dbx;
8962         cdst->mc_snum = csrc->mc_snum;
8963         cdst->mc_top = csrc->mc_top;
8964         cdst->mc_flags = csrc->mc_flags;
8965         MC_SET_OVPG(cdst, MC_OVPG(csrc));
8966
8967         for (i=0; i<csrc->mc_snum; i++) {
8968                 cdst->mc_pg[i] = csrc->mc_pg[i];
8969                 cdst->mc_ki[i] = csrc->mc_ki[i];
8970         }
8971 }
8972
8973 /** Rebalance the tree after a delete operation.
8974  * @param[in] mc Cursor pointing to the page where rebalancing
8975  * should begin.
8976  * @return 0 on success, non-zero on failure.
8977  */
8978 static int
8979 mdb_rebalance(MDB_cursor *mc)
8980 {
8981         MDB_node        *node;
8982         int rc, fromleft;
8983         unsigned int ptop, minkeys, thresh;
8984         MDB_cursor      mn;
8985         indx_t oldki;
8986
8987         if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
8988                 minkeys = 2;
8989                 thresh = 1;
8990         } else {
8991                 minkeys = 1;
8992                 thresh = FILL_THRESHOLD;
8993         }
8994         DPRINTF(("rebalancing %s page %"Yu" (has %u keys, %.1f%% full)",
8995             IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
8996             mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
8997                 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
8998
8999         if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
9000                 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
9001                 DPRINTF(("no need to rebalance page %"Yu", above fill threshold",
9002                     mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
9003                 return MDB_SUCCESS;
9004         }
9005
9006         if (mc->mc_snum < 2) {
9007                 MDB_page *mp = mc->mc_pg[0];
9008                 if (IS_SUBP(mp)) {
9009                         DPUTS("Can't rebalance a subpage, ignoring");
9010                         return MDB_SUCCESS;
9011                 }
9012                 if (NUMKEYS(mp) == 0) {
9013                         DPUTS("tree is completely empty");
9014                         mc->mc_db->md_root = P_INVALID;
9015                         mc->mc_db->md_depth = 0;
9016                         mc->mc_db->md_leaf_pages = 0;
9017                         rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
9018                         if (rc)
9019                                 return rc;
9020                         /* Adjust cursors pointing to mp */
9021                         mc->mc_snum = 0;
9022                         mc->mc_top = 0;
9023                         mc->mc_flags &= ~C_INITIALIZED;
9024                         {
9025                                 MDB_cursor *m2, *m3;
9026                                 MDB_dbi dbi = mc->mc_dbi;
9027
9028                                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9029                                         if (mc->mc_flags & C_SUB)
9030                                                 m3 = &m2->mc_xcursor->mx_cursor;
9031                                         else
9032                                                 m3 = m2;
9033                                         if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
9034                                                 continue;
9035                                         if (m3->mc_pg[0] == mp) {
9036                                                 m3->mc_snum = 0;
9037                                                 m3->mc_top = 0;
9038                                                 m3->mc_flags &= ~C_INITIALIZED;
9039                                         }
9040                                 }
9041                         }
9042                 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
9043                         int i;
9044                         DPUTS("collapsing root page!");
9045                         rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
9046                         if (rc)
9047                                 return rc;
9048                         mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
9049                         rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
9050                         if (rc)
9051                                 return rc;
9052                         mc->mc_db->md_depth--;
9053                         mc->mc_db->md_branch_pages--;
9054                         mc->mc_ki[0] = mc->mc_ki[1];
9055                         for (i = 1; i<mc->mc_db->md_depth; i++) {
9056                                 mc->mc_pg[i] = mc->mc_pg[i+1];
9057                                 mc->mc_ki[i] = mc->mc_ki[i+1];
9058                         }
9059                         {
9060                                 /* Adjust other cursors pointing to mp */
9061                                 MDB_cursor *m2, *m3;
9062                                 MDB_dbi dbi = mc->mc_dbi;
9063
9064                                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9065                                         if (mc->mc_flags & C_SUB)
9066                                                 m3 = &m2->mc_xcursor->mx_cursor;
9067                                         else
9068                                                 m3 = m2;
9069                                         if (m3 == mc) continue;
9070                                         if (!(m3->mc_flags & C_INITIALIZED))
9071                                                 continue;
9072                                         if (m3->mc_pg[0] == mp) {
9073                                                 for (i=0; i<mc->mc_db->md_depth; i++) {
9074                                                         m3->mc_pg[i] = m3->mc_pg[i+1];
9075                                                         m3->mc_ki[i] = m3->mc_ki[i+1];
9076                                                 }
9077                                                 m3->mc_snum--;
9078                                                 m3->mc_top--;
9079                                         }
9080                                 }
9081                         }
9082                 } else
9083                         DPUTS("root page doesn't need rebalancing");
9084                 return MDB_SUCCESS;
9085         }
9086
9087         /* The parent (branch page) must have at least 2 pointers,
9088          * otherwise the tree is invalid.
9089          */
9090         ptop = mc->mc_top-1;
9091         mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
9092
9093         /* Leaf page fill factor is below the threshold.
9094          * Try to move keys from left or right neighbor, or
9095          * merge with a neighbor page.
9096          */
9097
9098         /* Find neighbors.
9099          */
9100         mdb_cursor_copy(mc, &mn);
9101         mn.mc_xcursor = NULL;
9102
9103         oldki = mc->mc_ki[mc->mc_top];
9104         if (mc->mc_ki[ptop] == 0) {
9105                 /* We're the leftmost leaf in our parent.
9106                  */
9107                 DPUTS("reading right neighbor");
9108                 mn.mc_ki[ptop]++;
9109                 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
9110                 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
9111                 if (rc)
9112                         return rc;
9113                 mn.mc_ki[mn.mc_top] = 0;
9114                 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
9115                 fromleft = 0;
9116         } else {
9117                 /* There is at least one neighbor to the left.
9118                  */
9119                 DPUTS("reading left neighbor");
9120                 mn.mc_ki[ptop]--;
9121                 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
9122                 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
9123                 if (rc)
9124                         return rc;
9125                 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
9126                 mc->mc_ki[mc->mc_top] = 0;
9127                 fromleft = 1;
9128         }
9129
9130         DPRINTF(("found neighbor page %"Yu" (%u keys, %.1f%% full)",
9131             mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
9132                 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
9133
9134         /* If the neighbor page is above threshold and has enough keys,
9135          * move one key from it. Otherwise we should try to merge them.
9136          * (A branch page must never have less than 2 keys.)
9137          */
9138         if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
9139                 rc = mdb_node_move(&mn, mc, fromleft);
9140                 if (fromleft) {
9141                         /* if we inserted on left, bump position up */
9142                         oldki++;
9143                 }
9144         } else {
9145                 if (!fromleft) {
9146                         rc = mdb_page_merge(&mn, mc);
9147                 } else {
9148                         oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
9149                         mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
9150                         /* We want mdb_rebalance to find mn when doing fixups */
9151                         WITH_CURSOR_TRACKING(mn,
9152                                 rc = mdb_page_merge(mc, &mn));
9153                         mdb_cursor_copy(&mn, mc);
9154                 }
9155                 mc->mc_flags &= ~C_EOF;
9156         }
9157         mc->mc_ki[mc->mc_top] = oldki;
9158         return rc;
9159 }
9160
9161 /** Complete a delete operation started by #mdb_cursor_del(). */
9162 static int
9163 mdb_cursor_del0(MDB_cursor *mc)
9164 {
9165         int rc;
9166         MDB_page *mp;
9167         indx_t ki;
9168         unsigned int nkeys;
9169         MDB_cursor *m2, *m3;
9170         MDB_dbi dbi = mc->mc_dbi;
9171
9172         ki = mc->mc_ki[mc->mc_top];
9173         mp = mc->mc_pg[mc->mc_top];
9174         mdb_node_del(mc, mc->mc_db->md_pad);
9175         mc->mc_db->md_entries--;
9176         {
9177                 /* Adjust other cursors pointing to mp */
9178                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9179                         m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9180                         if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9181                                 continue;
9182                         if (m3 == mc || m3->mc_snum < mc->mc_snum)
9183                                 continue;
9184                         if (m3->mc_pg[mc->mc_top] == mp) {
9185                                 if (m3->mc_ki[mc->mc_top] == ki) {
9186                                         m3->mc_flags |= C_DEL;
9187                                         if (mc->mc_db->md_flags & MDB_DUPSORT) {
9188                                                 /* Sub-cursor referred into dataset which is gone */
9189                                                 m3->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
9190                                         }
9191                                         continue;
9192                                 } else if (m3->mc_ki[mc->mc_top] > ki) {
9193                                         m3->mc_ki[mc->mc_top]--;
9194                                 }
9195                                 if (XCURSOR_INITED(m3))
9196                                         XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9197                         }
9198                 }
9199         }
9200         rc = mdb_rebalance(mc);
9201
9202         if (rc == MDB_SUCCESS) {
9203                 /* DB is totally empty now, just bail out.
9204                  * Other cursors adjustments were already done
9205                  * by mdb_rebalance and aren't needed here.
9206                  */
9207                 if (!mc->mc_snum)
9208                         return rc;
9209
9210                 mp = mc->mc_pg[mc->mc_top];
9211                 nkeys = NUMKEYS(mp);
9212
9213                 /* Adjust other cursors pointing to mp */
9214                 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
9215                         m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9216                         if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9217                                 continue;
9218                         if (m3->mc_snum < mc->mc_snum)
9219                                 continue;
9220                         if (m3->mc_pg[mc->mc_top] == mp) {
9221                                 /* if m3 points past last node in page, find next sibling */
9222                                 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
9223                                         if (m3->mc_ki[mc->mc_top] >= nkeys) {
9224                                                 rc = mdb_cursor_sibling(m3, 1);
9225                                                 if (rc == MDB_NOTFOUND) {
9226                                                         m3->mc_flags |= C_EOF;
9227                                                         rc = MDB_SUCCESS;
9228                                                         continue;
9229                                                 }
9230                                         }
9231                                         if (mc->mc_db->md_flags & MDB_DUPSORT) {
9232                                                 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
9233                                                 /* If this node is a fake page, it needs to be reinited
9234                                                  * because its data has moved. But just reset mc_pg[0]
9235                                                  * if the xcursor is already live.
9236                                                  */
9237                                                 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) {
9238                                                         if (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)
9239                                                                 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
9240                                                         else
9241                                                                 mdb_xcursor_init1(m3, node);
9242                                                 }
9243                                         }
9244                                 }
9245                         }
9246                 }
9247                 mc->mc_flags |= C_DEL;
9248         }
9249
9250         if (rc)
9251                 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9252         return rc;
9253 }
9254
9255 int
9256 mdb_del(MDB_txn *txn, MDB_dbi dbi,
9257     MDB_val *key, MDB_val *data)
9258 {
9259         if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9260                 return EINVAL;
9261
9262         if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9263                 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9264
9265         if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
9266                 /* must ignore any data */
9267                 data = NULL;
9268         }
9269
9270         return mdb_del0(txn, dbi, key, data, 0);
9271 }
9272
9273 static int
9274 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
9275         MDB_val *key, MDB_val *data, unsigned flags)
9276 {
9277         MDB_cursor mc;
9278         MDB_xcursor mx;
9279         MDB_cursor_op op;
9280         MDB_val rdata, *xdata;
9281         int              rc, exact = 0;
9282         DKBUF;
9283
9284         DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
9285
9286         mdb_cursor_init(&mc, txn, dbi, &mx);
9287
9288         if (data) {
9289                 op = MDB_GET_BOTH;
9290                 rdata = *data;
9291                 xdata = &rdata;
9292         } else {
9293                 op = MDB_SET;
9294                 xdata = NULL;
9295                 flags |= MDB_NODUPDATA;
9296         }
9297         rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
9298         if (rc == 0) {
9299                 /* let mdb_page_split know about this cursor if needed:
9300                  * delete will trigger a rebalance; if it needs to move
9301                  * a node from one page to another, it will have to
9302                  * update the parent's separator key(s). If the new sepkey
9303                  * is larger than the current one, the parent page may
9304                  * run out of space, triggering a split. We need this
9305                  * cursor to be consistent until the end of the rebalance.
9306                  */
9307                 mc.mc_next = txn->mt_cursors[dbi];
9308                 txn->mt_cursors[dbi] = &mc;
9309                 rc = mdb_cursor_del(&mc, flags);
9310                 txn->mt_cursors[dbi] = mc.mc_next;
9311         }
9312         return rc;
9313 }
9314
9315 /** Split a page and insert a new node.
9316  * Set #MDB_TXN_ERROR on failure.
9317  * @param[in,out] mc Cursor pointing to the page and desired insertion index.
9318  * The cursor will be updated to point to the actual page and index where
9319  * the node got inserted after the split.
9320  * @param[in] newkey The key for the newly inserted node.
9321  * @param[in] newdata The data for the newly inserted node.
9322  * @param[in] newpgno The page number, if the new node is a branch node.
9323  * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
9324  * @return 0 on success, non-zero on failure.
9325  */
9326 static int
9327 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
9328         unsigned int nflags)
9329 {
9330         unsigned int flags;
9331         int              rc = MDB_SUCCESS, new_root = 0, did_split = 0;
9332         indx_t           newindx;
9333         pgno_t           pgno = 0;
9334         int      i, j, split_indx, nkeys, pmax;
9335         MDB_env         *env = mc->mc_txn->mt_env;
9336         MDB_node        *node;
9337         MDB_val  sepkey, rkey, xdata, *rdata = &xdata;
9338         MDB_page        *copy = NULL;
9339         MDB_page        *mp, *rp, *pp;
9340         int ptop;
9341         MDB_cursor      mn;
9342         DKBUF;
9343
9344         mp = mc->mc_pg[mc->mc_top];
9345         newindx = mc->mc_ki[mc->mc_top];
9346         nkeys = NUMKEYS(mp);
9347
9348         DPRINTF(("-----> splitting %s page %"Yu" and adding [%s] at index %i/%i",
9349             IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
9350             DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
9351
9352         /* Create a right sibling. */
9353         if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
9354                 return rc;
9355         rp->mp_pad = mp->mp_pad;
9356         DPRINTF(("new right sibling: page %"Yu, rp->mp_pgno));
9357
9358         /* Usually when splitting the root page, the cursor
9359          * height is 1. But when called from mdb_update_key,
9360          * the cursor height may be greater because it walks
9361          * up the stack while finding the branch slot to update.
9362          */
9363         if (mc->mc_top < 1) {
9364                 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
9365                         goto done;
9366                 /* shift current top to make room for new parent */
9367                 for (i=mc->mc_snum; i>0; i--) {
9368                         mc->mc_pg[i] = mc->mc_pg[i-1];
9369                         mc->mc_ki[i] = mc->mc_ki[i-1];
9370                 }
9371                 mc->mc_pg[0] = pp;
9372                 mc->mc_ki[0] = 0;
9373                 mc->mc_db->md_root = pp->mp_pgno;
9374                 DPRINTF(("root split! new root = %"Yu, pp->mp_pgno));
9375                 new_root = mc->mc_db->md_depth++;
9376
9377                 /* Add left (implicit) pointer. */
9378                 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
9379                         /* undo the pre-push */
9380                         mc->mc_pg[0] = mc->mc_pg[1];
9381                         mc->mc_ki[0] = mc->mc_ki[1];
9382                         mc->mc_db->md_root = mp->mp_pgno;
9383                         mc->mc_db->md_depth--;
9384                         goto done;
9385                 }
9386                 mc->mc_snum++;
9387                 mc->mc_top++;
9388                 ptop = 0;
9389         } else {
9390                 ptop = mc->mc_top-1;
9391                 DPRINTF(("parent branch page is %"Yu, mc->mc_pg[ptop]->mp_pgno));
9392         }
9393
9394         mdb_cursor_copy(mc, &mn);
9395         mn.mc_xcursor = NULL;
9396         mn.mc_pg[mn.mc_top] = rp;
9397         mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
9398
9399         if (nflags & MDB_APPEND) {
9400                 mn.mc_ki[mn.mc_top] = 0;
9401                 sepkey = *newkey;
9402                 split_indx = newindx;
9403                 nkeys = 0;
9404         } else {
9405
9406                 split_indx = (nkeys+1) / 2;
9407
9408                 if (IS_LEAF2(rp)) {
9409                         char *split, *ins;
9410                         int x;
9411                         unsigned int lsize, rsize, ksize;
9412                         /* Move half of the keys to the right sibling */
9413                         x = mc->mc_ki[mc->mc_top] - split_indx;
9414                         ksize = mc->mc_db->md_pad;
9415                         split = LEAF2KEY(mp, split_indx, ksize);
9416                         rsize = (nkeys - split_indx) * ksize;
9417                         lsize = (nkeys - split_indx) * sizeof(indx_t);
9418                         mp->mp_lower -= lsize;
9419                         rp->mp_lower += lsize;
9420                         mp->mp_upper += rsize - lsize;
9421                         rp->mp_upper -= rsize - lsize;
9422                         sepkey.mv_size = ksize;
9423                         if (newindx == split_indx) {
9424                                 sepkey.mv_data = newkey->mv_data;
9425                         } else {
9426                                 sepkey.mv_data = split;
9427                         }
9428                         if (x<0) {
9429                                 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
9430                                 memcpy(rp->mp_ptrs, split, rsize);
9431                                 sepkey.mv_data = rp->mp_ptrs;
9432                                 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
9433                                 memcpy(ins, newkey->mv_data, ksize);
9434                                 mp->mp_lower += sizeof(indx_t);
9435                                 mp->mp_upper -= ksize - sizeof(indx_t);
9436                         } else {
9437                                 if (x)
9438                                         memcpy(rp->mp_ptrs, split, x * ksize);
9439                                 ins = LEAF2KEY(rp, x, ksize);
9440                                 memcpy(ins, newkey->mv_data, ksize);
9441                                 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
9442                                 rp->mp_lower += sizeof(indx_t);
9443                                 rp->mp_upper -= ksize - sizeof(indx_t);
9444                                 mc->mc_ki[mc->mc_top] = x;
9445                         }
9446                 } else {
9447                         int psize, nsize, k;
9448                         /* Maximum free space in an empty page */
9449                         pmax = env->me_psize - PAGEHDRSZ;
9450                         if (IS_LEAF(mp))
9451                                 nsize = mdb_leaf_size(env, newkey, newdata);
9452                         else
9453                                 nsize = mdb_branch_size(env, newkey);
9454                         nsize = EVEN(nsize);
9455
9456                         /* grab a page to hold a temporary copy */
9457                         copy = mdb_page_malloc(mc->mc_txn, 1);
9458                         if (copy == NULL) {
9459                                 rc = ENOMEM;
9460                                 goto done;
9461                         }
9462                         copy->mp_pgno  = mp->mp_pgno;
9463                         copy->mp_flags = mp->mp_flags;
9464                         copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
9465                         copy->mp_upper = env->me_psize - PAGEBASE;
9466
9467                         /* prepare to insert */
9468                         for (i=0, j=0; i<nkeys; i++) {
9469                                 if (i == newindx) {
9470                                         copy->mp_ptrs[j++] = 0;
9471                                 }
9472                                 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
9473                         }
9474
9475                         /* When items are relatively large the split point needs
9476                          * to be checked, because being off-by-one will make the
9477                          * difference between success or failure in mdb_node_add.
9478                          *
9479                          * It's also relevant if a page happens to be laid out
9480                          * such that one half of its nodes are all "small" and
9481                          * the other half of its nodes are "large." If the new
9482                          * item is also "large" and falls on the half with
9483                          * "large" nodes, it also may not fit.
9484                          *
9485                          * As a final tweak, if the new item goes on the last
9486                          * spot on the page (and thus, onto the new page), bias
9487                          * the split so the new page is emptier than the old page.
9488                          * This yields better packing during sequential inserts.
9489                          */
9490                         if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
9491                                 /* Find split point */
9492                                 psize = 0;
9493                                 if (newindx <= split_indx || newindx >= nkeys) {
9494                                         i = 0; j = 1;
9495                                         k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
9496                                 } else {
9497                                         i = nkeys; j = -1;
9498                                         k = split_indx-1;
9499                                 }
9500                                 for (; i!=k; i+=j) {
9501                                         if (i == newindx) {
9502                                                 psize += nsize;
9503                                                 node = NULL;
9504                                         } else {
9505                                                 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9506                                                 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
9507                                                 if (IS_LEAF(mp)) {
9508                                                         if (F_ISSET(node->mn_flags, F_BIGDATA))
9509                                                                 psize += sizeof(pgno_t);
9510                                                         else
9511                                                                 psize += NODEDSZ(node);
9512                                                 }
9513                                                 psize = EVEN(psize);
9514                                         }
9515                                         if (psize > pmax || i == k-j) {
9516                                                 split_indx = i + (j<0);
9517                                                 break;
9518                                         }
9519                                 }
9520                         }
9521                         if (split_indx == newindx) {
9522                                 sepkey.mv_size = newkey->mv_size;
9523                                 sepkey.mv_data = newkey->mv_data;
9524                         } else {
9525                                 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
9526                                 sepkey.mv_size = node->mn_ksize;
9527                                 sepkey.mv_data = NODEKEY(node);
9528                         }
9529                 }
9530         }
9531
9532         DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
9533
9534         /* Copy separator key to the parent.
9535          */
9536         if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
9537                 int snum = mc->mc_snum;
9538                 mn.mc_snum--;
9539                 mn.mc_top--;
9540                 did_split = 1;
9541                 /* We want other splits to find mn when doing fixups */
9542                 WITH_CURSOR_TRACKING(mn,
9543                         rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
9544                 if (rc)
9545                         goto done;
9546
9547                 /* root split? */
9548                 if (mc->mc_snum > snum) {
9549                         ptop++;
9550                 }
9551                 /* Right page might now have changed parent.
9552                  * Check if left page also changed parent.
9553                  */
9554                 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9555                     mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9556                         for (i=0; i<ptop; i++) {
9557                                 mc->mc_pg[i] = mn.mc_pg[i];
9558                                 mc->mc_ki[i] = mn.mc_ki[i];
9559                         }
9560                         mc->mc_pg[ptop] = mn.mc_pg[ptop];
9561                         if (mn.mc_ki[ptop]) {
9562                                 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
9563                         } else {
9564                                 /* find right page's left sibling */
9565                                 mc->mc_ki[ptop] = mn.mc_ki[ptop];
9566                                 rc = mdb_cursor_sibling(mc, 0);
9567                         }
9568                 }
9569         } else {
9570                 mn.mc_top--;
9571                 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
9572                 mn.mc_top++;
9573         }
9574         if (rc != MDB_SUCCESS) {
9575                 if (rc == MDB_NOTFOUND) /* improper mdb_cursor_sibling() result */
9576                         rc = MDB_PROBLEM;
9577                 goto done;
9578         }
9579         if (nflags & MDB_APPEND) {
9580                 mc->mc_pg[mc->mc_top] = rp;
9581                 mc->mc_ki[mc->mc_top] = 0;
9582                 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
9583                 if (rc)
9584                         goto done;
9585                 for (i=0; i<mc->mc_top; i++)
9586                         mc->mc_ki[i] = mn.mc_ki[i];
9587         } else if (!IS_LEAF2(mp)) {
9588                 /* Move nodes */
9589                 mc->mc_pg[mc->mc_top] = rp;
9590                 i = split_indx;
9591                 j = 0;
9592                 do {
9593                         if (i == newindx) {
9594                                 rkey.mv_data = newkey->mv_data;
9595                                 rkey.mv_size = newkey->mv_size;
9596                                 if (IS_LEAF(mp)) {
9597                                         rdata = newdata;
9598                                 } else
9599                                         pgno = newpgno;
9600                                 flags = nflags;
9601                                 /* Update index for the new key. */
9602                                 mc->mc_ki[mc->mc_top] = j;
9603                         } else {
9604                                 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9605                                 rkey.mv_data = NODEKEY(node);
9606                                 rkey.mv_size = node->mn_ksize;
9607                                 if (IS_LEAF(mp)) {
9608                                         xdata.mv_data = NODEDATA(node);
9609                                         xdata.mv_size = NODEDSZ(node);
9610                                         rdata = &xdata;
9611                                 } else
9612                                         pgno = NODEPGNO(node);
9613                                 flags = node->mn_flags;
9614                         }
9615
9616                         if (!IS_LEAF(mp) && j == 0) {
9617                                 /* First branch index doesn't need key data. */
9618                                 rkey.mv_size = 0;
9619                         }
9620
9621                         rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
9622                         if (rc)
9623                                 goto done;
9624                         if (i == nkeys) {
9625                                 i = 0;
9626                                 j = 0;
9627                                 mc->mc_pg[mc->mc_top] = copy;
9628                         } else {
9629                                 i++;
9630                                 j++;
9631                         }
9632                 } while (i != split_indx);
9633
9634                 nkeys = NUMKEYS(copy);
9635                 for (i=0; i<nkeys; i++)
9636                         mp->mp_ptrs[i] = copy->mp_ptrs[i];
9637                 mp->mp_lower = copy->mp_lower;
9638                 mp->mp_upper = copy->mp_upper;
9639                 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
9640                         env->me_psize - copy->mp_upper - PAGEBASE);
9641
9642                 /* reset back to original page */
9643                 if (newindx < split_indx) {
9644                         mc->mc_pg[mc->mc_top] = mp;
9645                 } else {
9646                         mc->mc_pg[mc->mc_top] = rp;
9647                         mc->mc_ki[ptop]++;
9648                         /* Make sure mc_ki is still valid.
9649                          */
9650                         if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9651                                 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9652                                 for (i=0; i<=ptop; i++) {
9653                                         mc->mc_pg[i] = mn.mc_pg[i];
9654                                         mc->mc_ki[i] = mn.mc_ki[i];
9655                                 }
9656                         }
9657                 }
9658                 if (nflags & MDB_RESERVE) {
9659                         node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
9660                         if (!(node->mn_flags & F_BIGDATA))
9661                                 newdata->mv_data = NODEDATA(node);
9662                 }
9663         } else {
9664                 if (newindx >= split_indx) {
9665                         mc->mc_pg[mc->mc_top] = rp;
9666                         mc->mc_ki[ptop]++;
9667                         /* Make sure mc_ki is still valid.
9668                          */
9669                         if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9670                                 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9671                                 for (i=0; i<=ptop; i++) {
9672                                         mc->mc_pg[i] = mn.mc_pg[i];
9673                                         mc->mc_ki[i] = mn.mc_ki[i];
9674                                 }
9675                         }
9676                 }
9677         }
9678
9679         {
9680                 /* Adjust other cursors pointing to mp */
9681                 MDB_cursor *m2, *m3;
9682                 MDB_dbi dbi = mc->mc_dbi;
9683                 nkeys = NUMKEYS(mp);
9684
9685                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9686                         if (mc->mc_flags & C_SUB)
9687                                 m3 = &m2->mc_xcursor->mx_cursor;
9688                         else
9689                                 m3 = m2;
9690                         if (m3 == mc)
9691                                 continue;
9692                         if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9693                                 continue;
9694                         if (new_root) {
9695                                 int k;
9696                                 /* sub cursors may be on different DB */
9697                                 if (m3->mc_pg[0] != mp)
9698                                         continue;
9699                                 /* root split */
9700                                 for (k=new_root; k>=0; k--) {
9701                                         m3->mc_ki[k+1] = m3->mc_ki[k];
9702                                         m3->mc_pg[k+1] = m3->mc_pg[k];
9703                                 }
9704                                 if (m3->mc_ki[0] >= nkeys) {
9705                                         m3->mc_ki[0] = 1;
9706                                 } else {
9707                                         m3->mc_ki[0] = 0;
9708                                 }
9709                                 m3->mc_pg[0] = mc->mc_pg[0];
9710                                 m3->mc_snum++;
9711                                 m3->mc_top++;
9712                         }
9713                         if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
9714                                 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
9715                                         m3->mc_ki[mc->mc_top]++;
9716                                 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9717                                         m3->mc_pg[mc->mc_top] = rp;
9718                                         m3->mc_ki[mc->mc_top] -= nkeys;
9719                                         for (i=0; i<mc->mc_top; i++) {
9720                                                 m3->mc_ki[i] = mn.mc_ki[i];
9721                                                 m3->mc_pg[i] = mn.mc_pg[i];
9722                                         }
9723                                 }
9724                         } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
9725                                 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
9726                                 m3->mc_ki[ptop]++;
9727                         }
9728                         if (XCURSOR_INITED(m3) && IS_LEAF(mp))
9729                                 XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9730                 }
9731         }
9732         DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
9733
9734 done:
9735         if (copy)                                       /* tmp page */
9736                 mdb_page_free(env, copy);
9737         if (rc)
9738                 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9739         return rc;
9740 }
9741
9742 int
9743 mdb_put(MDB_txn *txn, MDB_dbi dbi,
9744     MDB_val *key, MDB_val *data, unsigned int flags)
9745 {
9746         MDB_cursor mc;
9747         MDB_xcursor mx;
9748         int rc;
9749
9750         if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9751                 return EINVAL;
9752
9753         if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
9754                 return EINVAL;
9755
9756         if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9757                 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9758
9759         mdb_cursor_init(&mc, txn, dbi, &mx);
9760         mc.mc_next = txn->mt_cursors[dbi];
9761         txn->mt_cursors[dbi] = &mc;
9762         rc = mdb_cursor_put(&mc, key, data, flags);
9763         txn->mt_cursors[dbi] = mc.mc_next;
9764         return rc;
9765 }
9766
9767 #ifndef MDB_WBUF
9768 #define MDB_WBUF        (1024*1024)
9769 #endif
9770 #define MDB_EOF         0x10    /**< #mdb_env_copyfd1() is done reading */
9771
9772         /** State needed for a double-buffering compacting copy. */
9773 typedef struct mdb_copy {
9774         MDB_env *mc_env;
9775         MDB_txn *mc_txn;
9776         pthread_mutex_t mc_mutex;
9777         pthread_cond_t mc_cond; /**< Condition variable for #mc_new */
9778         char *mc_wbuf[2];
9779         char *mc_over[2];
9780         int mc_wlen[2];
9781         int mc_olen[2];
9782         pgno_t mc_next_pgno;
9783         HANDLE mc_fd;
9784         int mc_toggle;                  /**< Buffer number in provider */
9785         int mc_new;                             /**< (0-2 buffers to write) | (#MDB_EOF at end) */
9786         /** Error code.  Never cleared if set.  Both threads can set nonzero
9787          *      to fail the copy.  Not mutex-protected, LMDB expects atomic int.
9788          */
9789         volatile int mc_error;
9790 } mdb_copy;
9791
9792         /** Dedicated writer thread for compacting copy. */
9793 static THREAD_RET ESECT CALL_CONV
9794 mdb_env_copythr(void *arg)
9795 {
9796         mdb_copy *my = arg;
9797         char *ptr;
9798         int toggle = 0, wsize, rc;
9799 #ifdef _WIN32
9800         DWORD len;
9801 #define DO_WRITE(rc, fd, ptr, w2, len)  rc = WriteFile(fd, ptr, w2, &len, NULL)
9802 #else
9803         int len;
9804 #define DO_WRITE(rc, fd, ptr, w2, len)  len = write(fd, ptr, w2); rc = (len >= 0)
9805 #ifdef SIGPIPE
9806         sigset_t set;
9807         sigemptyset(&set);
9808         sigaddset(&set, SIGPIPE);
9809         if ((rc = pthread_sigmask(SIG_BLOCK, &set, NULL)) != 0)
9810                 my->mc_error = rc;
9811 #endif
9812 #endif
9813
9814         pthread_mutex_lock(&my->mc_mutex);
9815         for(;;) {
9816                 while (!my->mc_new)
9817                         pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9818                 if (my->mc_new == 0 + MDB_EOF) /* 0 buffers, just EOF */
9819                         break;
9820                 wsize = my->mc_wlen[toggle];
9821                 ptr = my->mc_wbuf[toggle];
9822 again:
9823                 rc = MDB_SUCCESS;
9824                 while (wsize > 0 && !my->mc_error) {
9825                         DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
9826                         if (!rc) {
9827                                 rc = ErrCode();
9828 #if defined(SIGPIPE) && !defined(_WIN32)
9829                                 if (rc == EPIPE) {
9830                                         /* Collect the pending SIGPIPE, otherwise at least OS X
9831                                          * gives it to the process on thread-exit (ITS#8504).
9832                                          */
9833                                         int tmp;
9834                                         sigwait(&set, &tmp);
9835                                 }
9836 #endif
9837                                 break;
9838                         } else if (len > 0) {
9839                                 rc = MDB_SUCCESS;
9840                                 ptr += len;
9841                                 wsize -= len;
9842                                 continue;
9843                         } else {
9844                                 rc = EIO;
9845                                 break;
9846                         }
9847                 }
9848                 if (rc) {
9849                         my->mc_error = rc;
9850                 }
9851                 /* If there's an overflow page tail, write it too */
9852                 if (my->mc_olen[toggle]) {
9853                         wsize = my->mc_olen[toggle];
9854                         ptr = my->mc_over[toggle];
9855                         my->mc_olen[toggle] = 0;
9856                         goto again;
9857                 }
9858                 my->mc_wlen[toggle] = 0;
9859                 toggle ^= 1;
9860                 /* Return the empty buffer to provider */
9861                 my->mc_new--;
9862                 pthread_cond_signal(&my->mc_cond);
9863         }
9864         pthread_mutex_unlock(&my->mc_mutex);
9865         return (THREAD_RET)0;
9866 #undef DO_WRITE
9867 }
9868
9869         /** Give buffer and/or #MDB_EOF to writer thread, await unused buffer.
9870          *
9871          * @param[in] my control structure.
9872          * @param[in] adjust (1 to hand off 1 buffer) | (MDB_EOF when ending).
9873          */
9874 static int ESECT
9875 mdb_env_cthr_toggle(mdb_copy *my, int adjust)
9876 {
9877         pthread_mutex_lock(&my->mc_mutex);
9878         my->mc_new += adjust;
9879         pthread_cond_signal(&my->mc_cond);
9880         while (my->mc_new & 2)          /* both buffers in use */
9881                 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9882         pthread_mutex_unlock(&my->mc_mutex);
9883
9884         my->mc_toggle ^= (adjust & 1);
9885         /* Both threads reset mc_wlen, to be safe from threading errors */
9886         my->mc_wlen[my->mc_toggle] = 0;
9887         return my->mc_error;
9888 }
9889
9890         /** Depth-first tree traversal for compacting copy.
9891          * @param[in] my control structure.
9892          * @param[in,out] pg database root.
9893          * @param[in] flags includes #F_DUPDATA if it is a sorted-duplicate sub-DB.
9894          */
9895 static int ESECT
9896 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
9897 {
9898         MDB_cursor mc = {0};
9899         MDB_node *ni;
9900         MDB_page *mo, *mp, *leaf;
9901         char *buf, *ptr;
9902         int rc, toggle;
9903         unsigned int i;
9904
9905         /* Empty DB, nothing to do */
9906         if (*pg == P_INVALID)
9907                 return MDB_SUCCESS;
9908
9909         mc.mc_snum = 1;
9910         mc.mc_txn = my->mc_txn;
9911         mc.mc_flags = my->mc_txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
9912
9913         rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
9914         if (rc)
9915                 return rc;
9916         rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
9917         if (rc)
9918                 return rc;
9919
9920         /* Make cursor pages writable */
9921         buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
9922         if (buf == NULL)
9923                 return ENOMEM;
9924
9925         for (i=0; i<mc.mc_top; i++) {
9926                 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
9927                 mc.mc_pg[i] = (MDB_page *)ptr;
9928                 ptr += my->mc_env->me_psize;
9929         }
9930
9931         /* This is writable space for a leaf page. Usually not needed. */
9932         leaf = (MDB_page *)ptr;
9933
9934         toggle = my->mc_toggle;
9935         while (mc.mc_snum > 0) {
9936                 unsigned n;
9937                 mp = mc.mc_pg[mc.mc_top];
9938                 n = NUMKEYS(mp);
9939
9940                 if (IS_LEAF(mp)) {
9941                         if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
9942                                 for (i=0; i<n; i++) {
9943                                         ni = NODEPTR(mp, i);
9944                                         if (ni->mn_flags & F_BIGDATA) {
9945                                                 MDB_page *omp;
9946                                                 pgno_t pg;
9947
9948                                                 /* Need writable leaf */
9949                                                 if (mp != leaf) {
9950                                                         mc.mc_pg[mc.mc_top] = leaf;
9951                                                         mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9952                                                         mp = leaf;
9953                                                         ni = NODEPTR(mp, i);
9954                                                 }
9955
9956                                                 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9957                                                 memcpy(NODEDATA(ni), &my->mc_next_pgno, sizeof(pgno_t));
9958                                                 rc = mdb_page_get(&mc, pg, &omp, NULL);
9959                                                 if (rc)
9960                                                         goto done;
9961                                                 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9962                                                         rc = mdb_env_cthr_toggle(my, 1);
9963                                                         if (rc)
9964                                                                 goto done;
9965                                                         toggle = my->mc_toggle;
9966                                                 }
9967                                                 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9968                                                 memcpy(mo, omp, my->mc_env->me_psize);
9969                                                 mo->mp_pgno = my->mc_next_pgno;
9970                                                 my->mc_next_pgno += omp->mp_pages;
9971                                                 my->mc_wlen[toggle] += my->mc_env->me_psize;
9972                                                 if (omp->mp_pages > 1) {
9973                                                         my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
9974                                                         my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
9975                                                         rc = mdb_env_cthr_toggle(my, 1);
9976                                                         if (rc)
9977                                                                 goto done;
9978                                                         toggle = my->mc_toggle;
9979                                                 }
9980                                         } else if (ni->mn_flags & F_SUBDATA) {
9981                                                 MDB_db db;
9982
9983                                                 /* Need writable leaf */
9984                                                 if (mp != leaf) {
9985                                                         mc.mc_pg[mc.mc_top] = leaf;
9986                                                         mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9987                                                         mp = leaf;
9988                                                         ni = NODEPTR(mp, i);
9989                                                 }
9990
9991                                                 memcpy(&db, NODEDATA(ni), sizeof(db));
9992                                                 my->mc_toggle = toggle;
9993                                                 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
9994                                                 if (rc)
9995                                                         goto done;
9996                                                 toggle = my->mc_toggle;
9997                                                 memcpy(NODEDATA(ni), &db, sizeof(db));
9998                                         }
9999                                 }
10000                         }
10001                 } else {
10002                         mc.mc_ki[mc.mc_top]++;
10003                         if (mc.mc_ki[mc.mc_top] < n) {
10004                                 pgno_t pg;
10005 again:
10006                                 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
10007                                 pg = NODEPGNO(ni);
10008                                 rc = mdb_page_get(&mc, pg, &mp, NULL);
10009                                 if (rc)
10010                                         goto done;
10011                                 mc.mc_top++;
10012                                 mc.mc_snum++;
10013                                 mc.mc_ki[mc.mc_top] = 0;
10014                                 if (IS_BRANCH(mp)) {
10015                                         /* Whenever we advance to a sibling branch page,
10016                                          * we must proceed all the way down to its first leaf.
10017                                          */
10018                                         mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
10019                                         goto again;
10020                                 } else
10021                                         mc.mc_pg[mc.mc_top] = mp;
10022                                 continue;
10023                         }
10024                 }
10025                 if (my->mc_wlen[toggle] >= MDB_WBUF) {
10026                         rc = mdb_env_cthr_toggle(my, 1);
10027                         if (rc)
10028                                 goto done;
10029                         toggle = my->mc_toggle;
10030                 }
10031                 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
10032                 mdb_page_copy(mo, mp, my->mc_env->me_psize);
10033                 mo->mp_pgno = my->mc_next_pgno++;
10034                 my->mc_wlen[toggle] += my->mc_env->me_psize;
10035                 if (mc.mc_top) {
10036                         /* Update parent if there is one */
10037                         ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
10038                         SETPGNO(ni, mo->mp_pgno);
10039                         mdb_cursor_pop(&mc);
10040                 } else {
10041                         /* Otherwise we're done */
10042                         *pg = mo->mp_pgno;
10043                         break;
10044                 }
10045         }
10046 done:
10047         free(buf);
10048         return rc;
10049 }
10050
10051         /** Copy environment with compaction. */
10052 static int ESECT
10053 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
10054 {
10055         MDB_meta *mm;
10056         MDB_page *mp;
10057         mdb_copy my = {0};
10058         MDB_txn *txn = NULL;
10059         pthread_t thr;
10060         pgno_t root, new_root;
10061         int rc = MDB_SUCCESS;
10062
10063 #ifdef _WIN32
10064         if (!(my.mc_mutex = CreateMutex(NULL, FALSE, NULL)) ||
10065                 !(my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL))) {
10066                 rc = ErrCode();
10067                 goto done;
10068         }
10069         my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
10070         if (my.mc_wbuf[0] == NULL) {
10071                 /* _aligned_malloc() sets errno, but we use Windows error codes */
10072                 rc = ERROR_NOT_ENOUGH_MEMORY;
10073                 goto done;
10074         }
10075 #else
10076         if ((rc = pthread_mutex_init(&my.mc_mutex, NULL)) != 0)
10077                 return rc;
10078         if ((rc = pthread_cond_init(&my.mc_cond, NULL)) != 0)
10079                 goto done2;
10080 #ifdef HAVE_MEMALIGN
10081         my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
10082         if (my.mc_wbuf[0] == NULL) {
10083                 rc = errno;
10084                 goto done;
10085         }
10086 #else
10087         {
10088                 void *p;
10089                 if ((rc = posix_memalign(&p, env->me_os_psize, MDB_WBUF*2)) != 0)
10090                         goto done;
10091                 my.mc_wbuf[0] = p;
10092         }
10093 #endif
10094 #endif
10095         memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
10096         my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
10097         my.mc_next_pgno = NUM_METAS;
10098         my.mc_env = env;
10099         my.mc_fd = fd;
10100         rc = THREAD_CREATE(thr, mdb_env_copythr, &my);
10101         if (rc)
10102                 goto done;
10103
10104         rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10105         if (rc)
10106                 goto finish;
10107
10108         mp = (MDB_page *)my.mc_wbuf[0];
10109         memset(mp, 0, NUM_METAS * env->me_psize);
10110         mp->mp_pgno = 0;
10111         mp->mp_flags = P_META;
10112         mm = (MDB_meta *)METADATA(mp);
10113         mdb_env_init_meta0(env, mm);
10114         mm->mm_address = env->me_metas[0]->mm_address;
10115
10116         mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
10117         mp->mp_pgno = 1;
10118         mp->mp_flags = P_META;
10119         *(MDB_meta *)METADATA(mp) = *mm;
10120         mm = (MDB_meta *)METADATA(mp);
10121
10122         /* Set metapage 1 with current main DB */
10123         root = new_root = txn->mt_dbs[MAIN_DBI].md_root;
10124         if (root != P_INVALID) {
10125                 /* Count free pages + freeDB pages.  Subtract from last_pg
10126                  * to find the new last_pg, which also becomes the new root.
10127                  */
10128                 MDB_ID freecount = 0;
10129                 MDB_cursor mc;
10130                 MDB_val key, data;
10131                 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
10132                 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
10133                         freecount += *(MDB_ID *)data.mv_data;
10134                 if (rc != MDB_NOTFOUND)
10135                         goto finish;
10136                 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
10137                         txn->mt_dbs[FREE_DBI].md_leaf_pages +
10138                         txn->mt_dbs[FREE_DBI].md_overflow_pages;
10139
10140                 new_root = txn->mt_next_pgno - 1 - freecount;
10141                 mm->mm_last_pg = new_root;
10142                 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
10143                 mm->mm_dbs[MAIN_DBI].md_root = new_root;
10144         } else {
10145                 /* When the DB is empty, handle it specially to
10146                  * fix any breakage like page leaks from ITS#8174.
10147                  */
10148                 mm->mm_dbs[MAIN_DBI].md_flags = txn->mt_dbs[MAIN_DBI].md_flags;
10149         }
10150         if (root != P_INVALID || mm->mm_dbs[MAIN_DBI].md_flags) {
10151                 mm->mm_txnid = 1;               /* use metapage 1 */
10152         }
10153
10154         my.mc_wlen[0] = env->me_psize * NUM_METAS;
10155         my.mc_txn = txn;
10156         rc = mdb_env_cwalk(&my, &root, 0);
10157         if (rc == MDB_SUCCESS && root != new_root) {
10158                 rc = MDB_INCOMPATIBLE;  /* page leak or corrupt DB */
10159         }
10160
10161 finish:
10162         if (rc)
10163                 my.mc_error = rc;
10164         mdb_env_cthr_toggle(&my, 1 | MDB_EOF);
10165         rc = THREAD_FINISH(thr);
10166         mdb_txn_abort(txn);
10167
10168 done:
10169 #ifdef _WIN32
10170         if (my.mc_wbuf[0]) _aligned_free(my.mc_wbuf[0]);
10171         if (my.mc_cond)  CloseHandle(my.mc_cond);
10172         if (my.mc_mutex) CloseHandle(my.mc_mutex);
10173 #else
10174         free(my.mc_wbuf[0]);
10175         pthread_cond_destroy(&my.mc_cond);
10176 done2:
10177         pthread_mutex_destroy(&my.mc_mutex);
10178 #endif
10179         return rc ? rc : my.mc_error;
10180 }
10181
10182         /** Copy environment as-is. */
10183 static int ESECT
10184 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
10185 {
10186         MDB_txn *txn = NULL;
10187         mdb_mutexref_t wmutex = NULL;
10188         int rc;
10189         mdb_size_t wsize, w3;
10190         char *ptr;
10191 #ifdef _WIN32
10192         DWORD len, w2;
10193 #define DO_WRITE(rc, fd, ptr, w2, len)  rc = WriteFile(fd, ptr, w2, &len, NULL)
10194 #else
10195         ssize_t len;
10196         size_t w2;
10197 #define DO_WRITE(rc, fd, ptr, w2, len)  len = write(fd, ptr, w2); rc = (len >= 0)
10198 #endif
10199
10200         /* Do the lock/unlock of the reader mutex before starting the
10201          * write txn.  Otherwise other read txns could block writers.
10202          */
10203         rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10204         if (rc)
10205                 return rc;
10206
10207         if (env->me_txns) {
10208                 /* We must start the actual read txn after blocking writers */
10209                 mdb_txn_end(txn, MDB_END_RESET_TMP);
10210
10211                 /* Temporarily block writers until we snapshot the meta pages */
10212                 wmutex = env->me_wmutex;
10213                 if (LOCK_MUTEX(rc, env, wmutex))
10214                         goto leave;
10215
10216                 rc = mdb_txn_renew0(txn);
10217                 if (rc) {
10218                         UNLOCK_MUTEX(wmutex);
10219                         goto leave;
10220                 }
10221         }
10222
10223         wsize = env->me_psize * NUM_METAS;
10224         ptr = env->me_map;
10225         w2 = wsize;
10226         while (w2 > 0) {
10227                 DO_WRITE(rc, fd, ptr, w2, len);
10228                 if (!rc) {
10229                         rc = ErrCode();
10230                         break;
10231                 } else if (len > 0) {
10232                         rc = MDB_SUCCESS;
10233                         ptr += len;
10234                         w2 -= len;
10235                         continue;
10236                 } else {
10237                         /* Non-blocking or async handles are not supported */
10238                         rc = EIO;
10239                         break;
10240                 }
10241         }
10242         if (wmutex)
10243                 UNLOCK_MUTEX(wmutex);
10244
10245         if (rc)
10246                 goto leave;
10247
10248         w3 = txn->mt_next_pgno * env->me_psize;
10249         {
10250                 mdb_size_t fsize = 0;
10251                 if ((rc = mdb_fsize(env->me_fd, &fsize)))
10252                         goto leave;
10253                 if (w3 > fsize)
10254                         w3 = fsize;
10255         }
10256         wsize = w3 - wsize;
10257         while (wsize > 0) {
10258                 if (wsize > MAX_WRITE)
10259                         w2 = MAX_WRITE;
10260                 else
10261                         w2 = wsize;
10262                 DO_WRITE(rc, fd, ptr, w2, len);
10263                 if (!rc) {
10264                         rc = ErrCode();
10265                         break;
10266                 } else if (len > 0) {
10267                         rc = MDB_SUCCESS;
10268                         ptr += len;
10269                         wsize -= len;
10270                         continue;
10271                 } else {
10272                         rc = EIO;
10273                         break;
10274                 }
10275         }
10276
10277 leave:
10278         mdb_txn_abort(txn);
10279         return rc;
10280 }
10281
10282 int ESECT
10283 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
10284 {
10285         if (flags & MDB_CP_COMPACT)
10286                 return mdb_env_copyfd1(env, fd);
10287         else
10288                 return mdb_env_copyfd0(env, fd);
10289 }
10290
10291 int ESECT
10292 mdb_env_copyfd(MDB_env *env, HANDLE fd)
10293 {
10294         return mdb_env_copyfd2(env, fd, 0);
10295 }
10296
10297 int ESECT
10298 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
10299 {
10300         int rc;
10301         MDB_name fname;
10302         HANDLE newfd = INVALID_HANDLE_VALUE;
10303
10304         rc = mdb_fname_init(path, env->me_flags | MDB_NOLOCK, &fname);
10305         if (rc == MDB_SUCCESS) {
10306                 rc = mdb_fopen(env, &fname, MDB_O_COPY, 0666, &newfd);
10307                 mdb_fname_destroy(fname);
10308         }
10309         if (rc == MDB_SUCCESS) {
10310                 rc = mdb_env_copyfd2(env, newfd, flags);
10311                 if (close(newfd) < 0 && rc == MDB_SUCCESS)
10312                         rc = ErrCode();
10313         }
10314         return rc;
10315 }
10316
10317 int ESECT
10318 mdb_env_copy(MDB_env *env, const char *path)
10319 {
10320         return mdb_env_copy2(env, path, 0);
10321 }
10322
10323 int ESECT
10324 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
10325 {
10326         if (flag & ~CHANGEABLE)
10327                 return EINVAL;
10328         if (onoff)
10329                 env->me_flags |= flag;
10330         else
10331                 env->me_flags &= ~flag;
10332         return MDB_SUCCESS;
10333 }
10334
10335 int ESECT
10336 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
10337 {
10338         if (!env || !arg)
10339                 return EINVAL;
10340
10341         *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
10342         return MDB_SUCCESS;
10343 }
10344
10345 int ESECT
10346 mdb_env_set_userctx(MDB_env *env, void *ctx)
10347 {
10348         if (!env)
10349                 return EINVAL;
10350         env->me_userctx = ctx;
10351         return MDB_SUCCESS;
10352 }
10353
10354 void * ESECT
10355 mdb_env_get_userctx(MDB_env *env)
10356 {
10357         return env ? env->me_userctx : NULL;
10358 }
10359
10360 int ESECT
10361 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
10362 {
10363         if (!env)
10364                 return EINVAL;
10365 #ifndef NDEBUG
10366         env->me_assert_func = func;
10367 #endif
10368         return MDB_SUCCESS;
10369 }
10370
10371 int ESECT
10372 mdb_env_get_path(MDB_env *env, const char **arg)
10373 {
10374         if (!env || !arg)
10375                 return EINVAL;
10376
10377         *arg = env->me_path;
10378         return MDB_SUCCESS;
10379 }
10380
10381 int ESECT
10382 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
10383 {
10384         if (!env || !arg)
10385                 return EINVAL;
10386
10387         *arg = env->me_fd;
10388         return MDB_SUCCESS;
10389 }
10390
10391 /** Common code for #mdb_stat() and #mdb_env_stat().
10392  * @param[in] env the environment to operate in.
10393  * @param[in] db the #MDB_db record containing the stats to return.
10394  * @param[out] arg the address of an #MDB_stat structure to receive the stats.
10395  * @return 0, this function always succeeds.
10396  */
10397 static int ESECT
10398 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
10399 {
10400         arg->ms_psize = env->me_psize;
10401         arg->ms_depth = db->md_depth;
10402         arg->ms_branch_pages = db->md_branch_pages;
10403         arg->ms_leaf_pages = db->md_leaf_pages;
10404         arg->ms_overflow_pages = db->md_overflow_pages;
10405         arg->ms_entries = db->md_entries;
10406
10407         return MDB_SUCCESS;
10408 }
10409
10410 int ESECT
10411 mdb_env_stat(MDB_env *env, MDB_stat *arg)
10412 {
10413         MDB_meta *meta;
10414
10415         if (env == NULL || arg == NULL)
10416                 return EINVAL;
10417
10418         meta = mdb_env_pick_meta(env);
10419
10420         return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
10421 }
10422
10423 int ESECT
10424 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
10425 {
10426         MDB_meta *meta;
10427
10428         if (env == NULL || arg == NULL)
10429                 return EINVAL;
10430
10431         meta = mdb_env_pick_meta(env);
10432         arg->me_mapaddr = meta->mm_address;
10433         arg->me_last_pgno = meta->mm_last_pg;
10434         arg->me_last_txnid = meta->mm_txnid;
10435
10436         arg->me_mapsize = env->me_mapsize;
10437         arg->me_maxreaders = env->me_maxreaders;
10438         arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
10439         return MDB_SUCCESS;
10440 }
10441
10442 /** Set the default comparison functions for a database.
10443  * Called immediately after a database is opened to set the defaults.
10444  * The user can then override them with #mdb_set_compare() or
10445  * #mdb_set_dupsort().
10446  * @param[in] txn A transaction handle returned by #mdb_txn_begin()
10447  * @param[in] dbi A database handle returned by #mdb_dbi_open()
10448  */
10449 static void
10450 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
10451 {
10452         uint16_t f = txn->mt_dbs[dbi].md_flags;
10453
10454         txn->mt_dbxs[dbi].md_cmp =
10455                 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
10456                 (f & MDB_INTEGERKEY) ? mdb_cmp_cint  : mdb_cmp_memn;
10457
10458         txn->mt_dbxs[dbi].md_dcmp =
10459                 !(f & MDB_DUPSORT) ? 0 :
10460                 ((f & MDB_INTEGERDUP)
10461                  ? ((f & MDB_DUPFIXED)   ? mdb_cmp_int   : mdb_cmp_cint)
10462                  : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
10463 }
10464
10465 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
10466 {
10467         MDB_val key, data;
10468         MDB_dbi i;
10469         MDB_cursor mc;
10470         MDB_db dummy;
10471         int rc, dbflag, exact;
10472         unsigned int unused = 0, seq;
10473         char *namedup;
10474         size_t len;
10475
10476         if (flags & ~VALID_FLAGS)
10477                 return EINVAL;
10478         if (txn->mt_flags & MDB_TXN_BLOCKED)
10479                 return MDB_BAD_TXN;
10480
10481         /* main DB? */
10482         if (!name) {
10483                 *dbi = MAIN_DBI;
10484                 if (flags & PERSISTENT_FLAGS) {
10485                         uint16_t f2 = flags & PERSISTENT_FLAGS;
10486                         /* make sure flag changes get committed */
10487                         if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
10488                                 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
10489                                 txn->mt_flags |= MDB_TXN_DIRTY;
10490                         }
10491                 }
10492                 mdb_default_cmp(txn, MAIN_DBI);
10493                 return MDB_SUCCESS;
10494         }
10495
10496         if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
10497                 mdb_default_cmp(txn, MAIN_DBI);
10498         }
10499
10500         /* Is the DB already open? */
10501         len = strlen(name);
10502         for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
10503                 if (!txn->mt_dbxs[i].md_name.mv_size) {
10504                         /* Remember this free slot */
10505                         if (!unused) unused = i;
10506                         continue;
10507                 }
10508                 if (len == txn->mt_dbxs[i].md_name.mv_size &&
10509                         !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
10510                         *dbi = i;
10511                         return MDB_SUCCESS;
10512                 }
10513         }
10514
10515         /* If no free slot and max hit, fail */
10516         if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
10517                 return MDB_DBS_FULL;
10518
10519         /* Cannot mix named databases with some mainDB flags */
10520         if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
10521                 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
10522
10523         /* Find the DB info */
10524         dbflag = DB_NEW|DB_VALID|DB_USRVALID;
10525         exact = 0;
10526         key.mv_size = len;
10527         key.mv_data = (void *)name;
10528         mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
10529         rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
10530         if (rc == MDB_SUCCESS) {
10531                 /* make sure this is actually a DB */
10532                 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
10533                 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
10534                         return MDB_INCOMPATIBLE;
10535         } else if (! (rc == MDB_NOTFOUND && (flags & MDB_CREATE))) {
10536                 return rc;
10537         }
10538
10539         /* Done here so we cannot fail after creating a new DB */
10540         if ((namedup = strdup(name)) == NULL)
10541                 return ENOMEM;
10542
10543         if (rc) {
10544                 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
10545                 data.mv_size = sizeof(MDB_db);
10546                 data.mv_data = &dummy;
10547                 memset(&dummy, 0, sizeof(dummy));
10548                 dummy.md_root = P_INVALID;
10549                 dummy.md_flags = flags & PERSISTENT_FLAGS;
10550                 WITH_CURSOR_TRACKING(mc,
10551                         rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA));
10552                 dbflag |= DB_DIRTY;
10553         }
10554
10555         if (rc) {
10556                 free(namedup);
10557         } else {
10558                 /* Got info, register DBI in this txn */
10559                 unsigned int slot = unused ? unused : txn->mt_numdbs;
10560                 txn->mt_dbxs[slot].md_name.mv_data = namedup;
10561                 txn->mt_dbxs[slot].md_name.mv_size = len;
10562                 txn->mt_dbxs[slot].md_rel = NULL;
10563                 txn->mt_dbflags[slot] = dbflag;
10564                 /* txn-> and env-> are the same in read txns, use
10565                  * tmp variable to avoid undefined assignment
10566                  */
10567                 seq = ++txn->mt_env->me_dbiseqs[slot];
10568                 txn->mt_dbiseqs[slot] = seq;
10569
10570                 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
10571                 *dbi = slot;
10572                 mdb_default_cmp(txn, slot);
10573                 if (!unused) {
10574                         txn->mt_numdbs++;
10575                 }
10576         }
10577
10578         return rc;
10579 }
10580
10581 int ESECT
10582 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
10583 {
10584         if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
10585                 return EINVAL;
10586
10587         if (txn->mt_flags & MDB_TXN_BLOCKED)
10588                 return MDB_BAD_TXN;
10589
10590         if (txn->mt_dbflags[dbi] & DB_STALE) {
10591                 MDB_cursor mc;
10592                 MDB_xcursor mx;
10593                 /* Stale, must read the DB's root. cursor_init does it for us. */
10594                 mdb_cursor_init(&mc, txn, dbi, &mx);
10595         }
10596         return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
10597 }
10598
10599 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
10600 {
10601         char *ptr;
10602         if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
10603                 return;
10604         ptr = env->me_dbxs[dbi].md_name.mv_data;
10605         /* If there was no name, this was already closed */
10606         if (ptr) {
10607                 env->me_dbxs[dbi].md_name.mv_data = NULL;
10608                 env->me_dbxs[dbi].md_name.mv_size = 0;
10609                 env->me_dbflags[dbi] = 0;
10610                 env->me_dbiseqs[dbi]++;
10611                 free(ptr);
10612         }
10613 }
10614
10615 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
10616 {
10617         /* We could return the flags for the FREE_DBI too but what's the point? */
10618         if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10619                 return EINVAL;
10620         *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
10621         return MDB_SUCCESS;
10622 }
10623
10624 /** Add all the DB's pages to the free list.
10625  * @param[in] mc Cursor on the DB to free.
10626  * @param[in] subs non-Zero to check for sub-DBs in this DB.
10627  * @return 0 on success, non-zero on failure.
10628  */
10629 static int
10630 mdb_drop0(MDB_cursor *mc, int subs)
10631 {
10632         int rc;
10633
10634         rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
10635         if (rc == MDB_SUCCESS) {
10636                 MDB_txn *txn = mc->mc_txn;
10637                 MDB_node *ni;
10638                 MDB_cursor mx;
10639                 unsigned int i;
10640
10641                 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
10642                  * This also avoids any P_LEAF2 pages, which have no nodes.
10643                  * Also if the DB doesn't have sub-DBs and has no overflow
10644                  * pages, omit scanning leaves.
10645                  */
10646                 if ((mc->mc_flags & C_SUB) ||
10647                         (!subs && !mc->mc_db->md_overflow_pages))
10648                         mdb_cursor_pop(mc);
10649
10650                 mdb_cursor_copy(mc, &mx);
10651 #ifdef MDB_VL32
10652                 /* bump refcount for mx's pages */
10653                 for (i=0; i<mc->mc_snum; i++)
10654                         mdb_page_get(&mx, mc->mc_pg[i]->mp_pgno, &mx.mc_pg[i], NULL);
10655 #endif
10656                 while (mc->mc_snum > 0) {
10657                         MDB_page *mp = mc->mc_pg[mc->mc_top];
10658                         unsigned n = NUMKEYS(mp);
10659                         if (IS_LEAF(mp)) {
10660                                 for (i=0; i<n; i++) {
10661                                         ni = NODEPTR(mp, i);
10662                                         if (ni->mn_flags & F_BIGDATA) {
10663                                                 MDB_page *omp;
10664                                                 pgno_t pg;
10665                                                 memcpy(&pg, NODEDATA(ni), sizeof(pg));
10666                                                 rc = mdb_page_get(mc, pg, &omp, NULL);
10667                                                 if (rc != 0)
10668                                                         goto done;
10669                                                 mdb_cassert(mc, IS_OVERFLOW(omp));
10670                                                 rc = mdb_midl_append_range(&txn->mt_free_pgs,
10671                                                         pg, omp->mp_pages);
10672                                                 if (rc)
10673                                                         goto done;
10674                                                 mc->mc_db->md_overflow_pages -= omp->mp_pages;
10675                                                 if (!mc->mc_db->md_overflow_pages && !subs)
10676                                                         break;
10677                                         } else if (subs && (ni->mn_flags & F_SUBDATA)) {
10678                                                 mdb_xcursor_init1(mc, ni);
10679                                                 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
10680                                                 if (rc)
10681                                                         goto done;
10682                                         }
10683                                 }
10684                                 if (!subs && !mc->mc_db->md_overflow_pages)
10685                                         goto pop;
10686                         } else {
10687                                 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
10688                                         goto done;
10689                                 for (i=0; i<n; i++) {
10690                                         pgno_t pg;
10691                                         ni = NODEPTR(mp, i);
10692                                         pg = NODEPGNO(ni);
10693                                         /* free it */
10694                                         mdb_midl_xappend(txn->mt_free_pgs, pg);
10695                                 }
10696                         }
10697                         if (!mc->mc_top)
10698                                 break;
10699                         mc->mc_ki[mc->mc_top] = i;
10700                         rc = mdb_cursor_sibling(mc, 1);
10701                         if (rc) {
10702                                 if (rc != MDB_NOTFOUND)
10703                                         goto done;
10704                                 /* no more siblings, go back to beginning
10705                                  * of previous level.
10706                                  */
10707 pop:
10708                                 mdb_cursor_pop(mc);
10709                                 mc->mc_ki[0] = 0;
10710                                 for (i=1; i<mc->mc_snum; i++) {
10711                                         mc->mc_ki[i] = 0;
10712                                         mc->mc_pg[i] = mx.mc_pg[i];
10713                                 }
10714                         }
10715                 }
10716                 /* free it */
10717                 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
10718 done:
10719                 if (rc)
10720                         txn->mt_flags |= MDB_TXN_ERROR;
10721                 /* drop refcount for mx's pages */
10722                 MDB_CURSOR_UNREF(&mx, 0);
10723         } else if (rc == MDB_NOTFOUND) {
10724                 rc = MDB_SUCCESS;
10725         }
10726         mc->mc_flags &= ~C_INITIALIZED;
10727         return rc;
10728 }
10729
10730 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
10731 {
10732         MDB_cursor *mc, *m2;
10733         int rc;
10734
10735         if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10736                 return EINVAL;
10737
10738         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
10739                 return EACCES;
10740
10741         if (TXN_DBI_CHANGED(txn, dbi))
10742                 return MDB_BAD_DBI;
10743
10744         rc = mdb_cursor_open(txn, dbi, &mc);
10745         if (rc)
10746                 return rc;
10747
10748         rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
10749         /* Invalidate the dropped DB's cursors */
10750         for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
10751                 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
10752         if (rc)
10753                 goto leave;
10754
10755         /* Can't delete the main DB */
10756         if (del && dbi >= CORE_DBS) {
10757                 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
10758                 if (!rc) {
10759                         txn->mt_dbflags[dbi] = DB_STALE;
10760                         mdb_dbi_close(txn->mt_env, dbi);
10761                 } else {
10762                         txn->mt_flags |= MDB_TXN_ERROR;
10763                 }
10764         } else {
10765                 /* reset the DB record, mark it dirty */
10766                 txn->mt_dbflags[dbi] |= DB_DIRTY;
10767                 txn->mt_dbs[dbi].md_depth = 0;
10768                 txn->mt_dbs[dbi].md_branch_pages = 0;
10769                 txn->mt_dbs[dbi].md_leaf_pages = 0;
10770                 txn->mt_dbs[dbi].md_overflow_pages = 0;
10771                 txn->mt_dbs[dbi].md_entries = 0;
10772                 txn->mt_dbs[dbi].md_root = P_INVALID;
10773
10774                 txn->mt_flags |= MDB_TXN_DIRTY;
10775         }
10776 leave:
10777         mdb_cursor_close(mc);
10778         return rc;
10779 }
10780
10781 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10782 {
10783         if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10784                 return EINVAL;
10785
10786         txn->mt_dbxs[dbi].md_cmp = cmp;
10787         return MDB_SUCCESS;
10788 }
10789
10790 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10791 {
10792         if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10793                 return EINVAL;
10794
10795         txn->mt_dbxs[dbi].md_dcmp = cmp;
10796         return MDB_SUCCESS;
10797 }
10798
10799 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
10800 {
10801         if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10802                 return EINVAL;
10803
10804         txn->mt_dbxs[dbi].md_rel = rel;
10805         return MDB_SUCCESS;
10806 }
10807
10808 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
10809 {
10810         if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10811                 return EINVAL;
10812
10813         txn->mt_dbxs[dbi].md_relctx = ctx;
10814         return MDB_SUCCESS;
10815 }
10816
10817 int ESECT
10818 mdb_env_get_maxkeysize(MDB_env *env)
10819 {
10820         return ENV_MAXKEY(env);
10821 }
10822
10823 int ESECT
10824 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
10825 {
10826         unsigned int i, rdrs;
10827         MDB_reader *mr;
10828         char buf[64];
10829         int rc = 0, first = 1;
10830
10831         if (!env || !func)
10832                 return -1;
10833         if (!env->me_txns) {
10834                 return func("(no reader locks)\n", ctx);
10835         }
10836         rdrs = env->me_txns->mti_numreaders;
10837         mr = env->me_txns->mti_readers;
10838         for (i=0; i<rdrs; i++) {
10839                 if (mr[i].mr_pid) {
10840                         txnid_t txnid = mr[i].mr_txnid;
10841                         sprintf(buf, txnid == (txnid_t)-1 ?
10842                                 "%10d %"Z"x -\n" : "%10d %"Z"x %"Yu"\n",
10843                                 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
10844                         if (first) {
10845                                 first = 0;
10846                                 rc = func("    pid     thread     txnid\n", ctx);
10847                                 if (rc < 0)
10848                                         break;
10849                         }
10850                         rc = func(buf, ctx);
10851                         if (rc < 0)
10852                                 break;
10853                 }
10854         }
10855         if (first) {
10856                 rc = func("(no active readers)\n", ctx);
10857         }
10858         return rc;
10859 }
10860
10861 /** Insert pid into list if not already present.
10862  * return -1 if already present.
10863  */
10864 static int ESECT
10865 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
10866 {
10867         /* binary search of pid in list */
10868         unsigned base = 0;
10869         unsigned cursor = 1;
10870         int val = 0;
10871         unsigned n = ids[0];
10872
10873         while( 0 < n ) {
10874                 unsigned pivot = n >> 1;
10875                 cursor = base + pivot + 1;
10876                 val = pid - ids[cursor];
10877
10878                 if( val < 0 ) {
10879                         n = pivot;
10880
10881                 } else if ( val > 0 ) {
10882                         base = cursor;
10883                         n -= pivot + 1;
10884
10885                 } else {
10886                         /* found, so it's a duplicate */
10887                         return -1;
10888                 }
10889         }
10890
10891         if( val > 0 ) {
10892                 ++cursor;
10893         }
10894         ids[0]++;
10895         for (n = ids[0]; n > cursor; n--)
10896                 ids[n] = ids[n-1];
10897         ids[n] = pid;
10898         return 0;
10899 }
10900
10901 int ESECT
10902 mdb_reader_check(MDB_env *env, int *dead)
10903 {
10904         if (!env)
10905                 return EINVAL;
10906         if (dead)
10907                 *dead = 0;
10908         return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
10909 }
10910
10911 /** As #mdb_reader_check(). \b rlocked is set if caller locked #me_rmutex. */
10912 static int ESECT
10913 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
10914 {
10915         mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
10916         unsigned int i, j, rdrs;
10917         MDB_reader *mr;
10918         MDB_PID_T *pids, pid;
10919         int rc = MDB_SUCCESS, count = 0;
10920
10921         rdrs = env->me_txns->mti_numreaders;
10922         pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
10923         if (!pids)
10924                 return ENOMEM;
10925         pids[0] = 0;
10926         mr = env->me_txns->mti_readers;
10927         for (i=0; i<rdrs; i++) {
10928                 pid = mr[i].mr_pid;
10929                 if (pid && pid != env->me_pid) {
10930                         if (mdb_pid_insert(pids, pid) == 0) {
10931                                 if (!mdb_reader_pid(env, Pidcheck, pid)) {
10932                                         /* Stale reader found */
10933                                         j = i;
10934                                         if (rmutex) {
10935                                                 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
10936                                                         if ((rc = mdb_mutex_failed(env, rmutex, rc)))
10937                                                                 break;
10938                                                         rdrs = 0; /* the above checked all readers */
10939                                                 } else {
10940                                                         /* Recheck, a new process may have reused pid */
10941                                                         if (mdb_reader_pid(env, Pidcheck, pid))
10942                                                                 j = rdrs;
10943                                                 }
10944                                         }
10945                                         for (; j<rdrs; j++)
10946                                                         if (mr[j].mr_pid == pid) {
10947                                                                 DPRINTF(("clear stale reader pid %u txn %"Yd,
10948                                                                         (unsigned) pid, mr[j].mr_txnid));
10949                                                                 mr[j].mr_pid = 0;
10950                                                                 count++;
10951                                                         }
10952                                         if (rmutex)
10953                                                 UNLOCK_MUTEX(rmutex);
10954                                 }
10955                         }
10956                 }
10957         }
10958         free(pids);
10959         if (dead)
10960                 *dead = count;
10961         return rc;
10962 }
10963
10964 #ifdef MDB_ROBUST_SUPPORTED
10965 /** Handle #LOCK_MUTEX0() failure.
10966  * Try to repair the lock file if the mutex owner died.
10967  * @param[in] env       the environment handle
10968  * @param[in] mutex     LOCK_MUTEX0() mutex
10969  * @param[in] rc        LOCK_MUTEX0() error (nonzero)
10970  * @return 0 on success with the mutex locked, or an error code on failure.
10971  */
10972 static int ESECT
10973 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10974 {
10975         int rlocked, rc2;
10976         MDB_meta *meta;
10977
10978         if (rc == MDB_OWNERDEAD) {
10979                 /* We own the mutex. Clean up after dead previous owner. */
10980                 rc = MDB_SUCCESS;
10981                 rlocked = (mutex == env->me_rmutex);
10982                 if (!rlocked) {
10983                         /* Keep mti_txnid updated, otherwise next writer can
10984                          * overwrite data which latest meta page refers to.
10985                          */
10986                         meta = mdb_env_pick_meta(env);
10987                         env->me_txns->mti_txnid = meta->mm_txnid;
10988                         /* env is hosed if the dead thread was ours */
10989                         if (env->me_txn) {
10990                                 env->me_flags |= MDB_FATAL_ERROR;
10991                                 env->me_txn = NULL;
10992                                 rc = MDB_PANIC;
10993                         }
10994                 }
10995                 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
10996                         (rc ? "this process' env is hosed" : "recovering")));
10997                 rc2 = mdb_reader_check0(env, rlocked, NULL);
10998                 if (rc2 == 0)
10999                         rc2 = mdb_mutex_consistent(mutex);
11000                 if (rc || (rc = rc2)) {
11001                         DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
11002                         UNLOCK_MUTEX(mutex);
11003                 }
11004         } else {
11005 #ifdef _WIN32
11006                 rc = ErrCode();
11007 #endif
11008                 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
11009         }
11010
11011         return rc;
11012 }
11013 #endif  /* MDB_ROBUST_SUPPORTED */
11014
11015 #if defined(_WIN32)
11016 /** Convert \b src to new wchar_t[] string with room for \b xtra extra chars */
11017 static int ESECT
11018 utf8_to_utf16(const char *src, MDB_name *dst, int xtra)
11019 {
11020         int rc, need = 0;
11021         wchar_t *result = NULL;
11022         for (;;) {                                      /* malloc result, then fill it in */
11023                 need = MultiByteToWideChar(CP_UTF8, 0, src, -1, result, need);
11024                 if (!need) {
11025                         rc = ErrCode();
11026                         free(result);
11027                         return rc;
11028                 }
11029                 if (!result) {
11030                         result = malloc(sizeof(wchar_t) * (need + xtra));
11031                         if (!result)
11032                                 return ENOMEM;
11033                         continue;
11034                 }
11035                 dst->mn_alloced = 1;
11036                 dst->mn_len = need - 1;
11037                 dst->mn_val = result;
11038                 return MDB_SUCCESS;
11039         }
11040 }
11041 #endif /* defined(_WIN32) */
11042 /** @} */