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