damus

nostr ios client
git clone git://jb55.com/damus
Log | Files | Refs | README | LICENSE

mdb.c (293055B)


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