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