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