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