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