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