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