2 * @brief Lightning memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2017 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
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>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
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.
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.
38 #if defined(MDB_VL32) || defined(__WIN64__)
39 #define _FILE_OFFSET_BITS 64
44 #include <wchar.h> /* get wcscpy() */
46 /* We use native NT APIs to setup the memory map, so that we can
47 * let the DB file grow incrementally instead of always preallocating
48 * the full size. These APIs are defined in <wdm.h> and <ntifs.h>
49 * but those headers are meant for driver-level development and
50 * conflict with the regular user-level headers, so we explicitly
51 * declare them here. Using these APIs also means we must link to
52 * ntdll.dll, which is not linked by default in user code.
55 NtCreateSection(OUT PHANDLE sh, IN ACCESS_MASK acc,
56 IN void * oa OPTIONAL,
57 IN PLARGE_INTEGER ms OPTIONAL,
58 IN ULONG pp, IN ULONG aa, IN HANDLE fh OPTIONAL);
60 typedef enum _SECTION_INHERIT {
66 NtMapViewOfSection(IN PHANDLE sh, IN HANDLE ph,
67 IN OUT PVOID *addr, IN ULONG_PTR zbits,
68 IN SIZE_T cs, IN OUT PLARGE_INTEGER off OPTIONAL,
69 IN OUT PSIZE_T vs, IN SECTION_INHERIT ih,
70 IN ULONG at, IN ULONG pp);
75 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
76 * as int64 which is wrong. MSVC doesn't define it at all, so just
80 #define MDB_THR_T DWORD
81 #include <sys/types.h>
84 # include <sys/param.h>
86 # define LITTLE_ENDIAN 1234
87 # define BIG_ENDIAN 4321
88 # define BYTE_ORDER LITTLE_ENDIAN
90 # define SSIZE_MAX INT_MAX
94 #include <sys/types.h>
96 #define MDB_PID_T pid_t
97 #define MDB_THR_T pthread_t
98 #include <sys/param.h>
100 #include <sys/mman.h>
101 #ifdef HAVE_SYS_FILE_H
102 #include <sys/file.h>
107 #if defined(__mips) && defined(__linux)
108 /* MIPS has cache coherency issues, requires explicit cache control */
109 #include <asm/cachectl.h>
110 extern int cacheflush(char *addr, int nbytes, int cache);
111 #define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
113 #define CACHEFLUSH(addr, bytes, cache)
116 #if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
117 /** fdatasync is broken on ext3/ext4fs on older kernels, see
118 * description in #mdb_env_open2 comments. You can safely
119 * define MDB_FDATASYNC_WORKS if this code will only be run
120 * on kernels 3.6 and newer.
122 #define BROKEN_FDATASYNC
128 #include <inttypes.h>
136 typedef SSIZE_T ssize_t;
141 #if defined(__sun) || defined(ANDROID)
142 /* Most platforms have posix_memalign, older may only have memalign */
143 #define HAVE_MEMALIGN 1
147 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
148 #include <netinet/in.h>
149 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
152 #if defined(__APPLE__) || defined (BSD) || defined(__FreeBSD_kernel__)
153 # if !(defined(MDB_USE_POSIX_MUTEX) || defined(MDB_USE_POSIX_SEM))
154 # define MDB_USE_SYSV_SEM 1
156 # define MDB_FDATASYNC fsync
157 #elif defined(ANDROID)
158 # define MDB_FDATASYNC fsync
164 #ifdef MDB_USE_POSIX_SEM
165 # define MDB_USE_HASH 1
166 #include <semaphore.h>
167 #elif defined(MDB_USE_SYSV_SEM)
170 #ifdef _SEM_SEMUN_UNDEFINED
173 struct semid_ds *buf;
174 unsigned short *array;
176 #endif /* _SEM_SEMUN_UNDEFINED */
178 #define MDB_USE_POSIX_MUTEX 1
179 #endif /* MDB_USE_POSIX_SEM */
182 #if defined(_WIN32) + defined(MDB_USE_POSIX_SEM) + defined(MDB_USE_SYSV_SEM) \
183 + defined(MDB_USE_POSIX_MUTEX) != 1
184 # error "Ambiguous shared-lock implementation"
188 #include <valgrind/memcheck.h>
189 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
190 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
191 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
192 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
193 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
195 #define VGMEMP_CREATE(h,r,z)
196 #define VGMEMP_ALLOC(h,a,s)
197 #define VGMEMP_FREE(h,a)
198 #define VGMEMP_DESTROY(h)
199 #define VGMEMP_DEFINED(a,s)
203 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
204 /* Solaris just defines one or the other */
205 # define LITTLE_ENDIAN 1234
206 # define BIG_ENDIAN 4321
207 # ifdef _LITTLE_ENDIAN
208 # define BYTE_ORDER LITTLE_ENDIAN
210 # define BYTE_ORDER BIG_ENDIAN
213 # define BYTE_ORDER __BYTE_ORDER
217 #ifndef LITTLE_ENDIAN
218 #define LITTLE_ENDIAN __LITTLE_ENDIAN
221 #define BIG_ENDIAN __BIG_ENDIAN
224 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
225 #define MISALIGNED_OK 1
231 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
232 # error "Unknown or unsupported endianness (BYTE_ORDER)"
233 #elif (-6 & 5) || CHAR_BIT!=8 || UINT_MAX!=0xffffffff || MDB_SIZE_MAX%UINT_MAX
234 # error "Two's complement, reasonably sized integer types, please"
238 /** Put infrequently used env functions in separate section */
240 # define ESECT __attribute__ ((section("__TEXT,text_env")))
242 # define ESECT __attribute__ ((section("text_env")))
249 #define CALL_CONV WINAPI
254 /** @defgroup internal LMDB Internals
257 /** @defgroup compat Compatibility Macros
258 * A bunch of macros to minimize the amount of platform-specific ifdefs
259 * needed throughout the rest of the code. When the features this library
260 * needs are similar enough to POSIX to be hidden in a one-or-two line
261 * replacement, this macro approach is used.
265 /** Features under development */
270 /** Wrapper around __func__, which is a C99 feature */
271 #if __STDC_VERSION__ >= 199901L
272 # define mdb_func_ __func__
273 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
274 # define mdb_func_ __FUNCTION__
276 /* If a debug message says <mdb_unknown>(), update the #if statements above */
277 # define mdb_func_ "<mdb_unknown>"
280 /* Internal error codes, not exposed outside liblmdb */
281 #define MDB_NO_ROOT (MDB_LAST_ERRCODE + 10)
283 #define MDB_OWNERDEAD ((int) WAIT_ABANDONED)
284 #elif defined MDB_USE_SYSV_SEM
285 #define MDB_OWNERDEAD (MDB_LAST_ERRCODE + 11)
286 #elif defined(MDB_USE_POSIX_MUTEX) && defined(EOWNERDEAD)
287 #define MDB_OWNERDEAD EOWNERDEAD /**< #LOCK_MUTEX0() result if dead owner */
291 #define GLIBC_VER ((__GLIBC__ << 16 )| __GLIBC_MINOR__)
293 /** Some platforms define the EOWNERDEAD error code
294 * even though they don't support Robust Mutexes.
295 * Compile with -DMDB_USE_ROBUST=0, or use some other
296 * mechanism like -DMDB_USE_SYSV_SEM instead of
297 * -DMDB_USE_POSIX_MUTEX. (SysV semaphores are
298 * also Robust, but some systems don't support them
301 #ifndef MDB_USE_ROBUST
302 /* Android currently lacks Robust Mutex support. So does glibc < 2.4. */
303 # if defined(MDB_USE_POSIX_MUTEX) && (defined(ANDROID) || \
304 (defined(__GLIBC__) && GLIBC_VER < 0x020004))
305 # define MDB_USE_ROBUST 0
307 # define MDB_USE_ROBUST 1
309 #endif /* !MDB_USE_ROBUST */
311 #if defined(MDB_USE_POSIX_MUTEX) && (MDB_USE_ROBUST)
312 /* glibc < 2.12 only provided _np API */
313 # if (defined(__GLIBC__) && GLIBC_VER < 0x02000c) || \
314 (defined(PTHREAD_MUTEX_ROBUST_NP) && !defined(PTHREAD_MUTEX_ROBUST))
315 # define PTHREAD_MUTEX_ROBUST PTHREAD_MUTEX_ROBUST_NP
316 # define pthread_mutexattr_setrobust(attr, flag) pthread_mutexattr_setrobust_np(attr, flag)
317 # define pthread_mutex_consistent(mutex) pthread_mutex_consistent_np(mutex)
319 #endif /* MDB_USE_POSIX_MUTEX && MDB_USE_ROBUST */
321 #if defined(MDB_OWNERDEAD) && (MDB_USE_ROBUST)
322 #define MDB_ROBUST_SUPPORTED 1
326 #define MDB_USE_HASH 1
327 #define MDB_PIDLOCK 0
328 #define THREAD_RET DWORD
329 #define pthread_t HANDLE
330 #define pthread_mutex_t HANDLE
331 #define pthread_cond_t HANDLE
332 typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
333 #define pthread_key_t DWORD
334 #define pthread_self() GetCurrentThreadId()
335 #define pthread_key_create(x,y) \
336 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
337 #define pthread_key_delete(x) TlsFree(x)
338 #define pthread_getspecific(x) TlsGetValue(x)
339 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
340 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
341 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
342 #define pthread_cond_signal(x) SetEvent(*x)
343 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
344 #define THREAD_CREATE(thr,start,arg) \
345 (((thr) = CreateThread(NULL, 0, start, arg, 0, NULL)) ? 0 : ErrCode())
346 #define THREAD_FINISH(thr) \
347 (WaitForSingleObject(thr, INFINITE) ? ErrCode() : 0)
348 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
349 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
350 #define mdb_mutex_consistent(mutex) 0
351 #define getpid() GetCurrentProcessId()
352 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
353 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
354 #define ErrCode() GetLastError()
355 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
356 #define close(fd) (CloseHandle(fd) ? 0 : -1)
357 #define munmap(ptr,len) UnmapViewOfFile(ptr)
358 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
359 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
361 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
364 #define THREAD_RET void *
365 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
366 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
368 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
369 #define MDB_PIDLOCK 1
371 #ifdef MDB_USE_POSIX_SEM
373 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
374 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
375 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
378 mdb_sem_wait(sem_t *sem)
381 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
385 #elif defined MDB_USE_SYSV_SEM
387 typedef struct mdb_mutex {
391 } mdb_mutex_t[1], *mdb_mutexref_t;
393 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
394 #define UNLOCK_MUTEX(mutex) do { \
395 struct sembuf sb = { 0, 1, SEM_UNDO }; \
396 sb.sem_num = (mutex)->semnum; \
397 *(mutex)->locked = 0; \
398 semop((mutex)->semid, &sb, 1); \
402 mdb_sem_wait(mdb_mutexref_t sem)
404 int rc, *locked = sem->locked;
405 struct sembuf sb = { 0, -1, SEM_UNDO };
406 sb.sem_num = sem->semnum;
408 if (!semop(sem->semid, &sb, 1)) {
409 rc = *locked ? MDB_OWNERDEAD : MDB_SUCCESS;
413 } while ((rc = errno) == EINTR);
417 #define mdb_mutex_consistent(mutex) 0
419 #else /* MDB_USE_POSIX_MUTEX: */
420 /** Shared mutex/semaphore as the original is stored.
422 * Not for copies. Instead it can be assigned to an #mdb_mutexref_t.
423 * When mdb_mutexref_t is a pointer and mdb_mutex_t is not, then it
424 * is array[size 1] so it can be assigned to the pointer.
426 typedef pthread_mutex_t mdb_mutex_t[1];
427 /** Reference to an #mdb_mutex_t */
428 typedef pthread_mutex_t *mdb_mutexref_t;
429 /** Lock the reader or writer mutex.
430 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
432 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
433 /** Unlock the reader or writer mutex.
435 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
436 /** Mark mutex-protected data as repaired, after death of previous owner.
438 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
439 #endif /* MDB_USE_POSIX_SEM || MDB_USE_SYSV_SEM */
441 /** Get the error code for the last failed system function.
443 #define ErrCode() errno
445 /** An abstraction for a file handle.
446 * On POSIX systems file handles are small integers. On Windows
447 * they're opaque pointers.
451 /** A value for an invalid file handle.
452 * Mainly used to initialize file variables and signify that they are
455 #define INVALID_HANDLE_VALUE (-1)
457 /** Get the size of a memory page for the system.
458 * This is the basic size that the platform's memory manager uses, and is
459 * fundamental to the use of memory-mapped files.
461 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
464 #define Z MDB_FMT_Z /**< printf/scanf format modifier for size_t */
465 #define Yu MDB_PRIy(u) /**< printf format for #mdb_size_t */
466 #define Yd MDB_PRIy(d) /**< printf format for 'signed #mdb_size_t' */
468 #ifdef MDB_USE_SYSV_SEM
469 #define MNAME_LEN (sizeof(int))
471 #define MNAME_LEN (sizeof(pthread_mutex_t))
474 /** Initial part of #MDB_env.me_mutexname[].
475 * Changes to this code must be reflected in #MDB_LOCK_FORMAT.
478 #define MUTEXNAME_PREFIX "Global\\MDB"
479 #elif defined MDB_USE_POSIX_SEM
480 #define MUTEXNAME_PREFIX "/MDB"
485 #ifdef MDB_ROBUST_SUPPORTED
486 /** Lock mutex, handle any error, set rc = result.
487 * Return 0 on success, nonzero (not rc) on error.
489 #define LOCK_MUTEX(rc, env, mutex) \
490 (((rc) = LOCK_MUTEX0(mutex)) && \
491 ((rc) = mdb_mutex_failed(env, mutex, rc)))
492 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
494 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
495 #define mdb_mutex_failed(env, mutex, rc) (rc)
499 /** A flag for opening a file and requesting synchronous data writes.
500 * This is only used when writing a meta page. It's not strictly needed;
501 * we could just do a normal write and then immediately perform a flush.
502 * But if this flag is available it saves us an extra system call.
504 * @note If O_DSYNC is undefined but exists in /usr/include,
505 * preferably set some compiler flag to get the definition.
509 # define MDB_DSYNC O_DSYNC
511 # define MDB_DSYNC O_SYNC
516 /** Function for flushing the data of a file. Define this to fsync
517 * if fdatasync() is not supported.
519 #ifndef MDB_FDATASYNC
520 # define MDB_FDATASYNC fdatasync
524 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
535 /** A page number in the database.
536 * Note that 64 bit page numbers are overkill, since pages themselves
537 * already represent 12-13 bits of addressable memory, and the OS will
538 * always limit applications to a maximum of 63 bits of address space.
540 * @note In the #MDB_node structure, we only store 48 bits of this value,
541 * which thus limits us to only 60 bits of addressable data.
543 typedef MDB_ID pgno_t;
545 /** A transaction ID.
546 * See struct MDB_txn.mt_txnid for details.
548 typedef MDB_ID txnid_t;
550 /** @defgroup debug Debug Macros
554 /** Enable debug output. Needs variable argument macros (a C99 feature).
555 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
556 * read from and written to the database (used for free space management).
562 static int mdb_debug;
563 static txnid_t mdb_debug_start;
565 /** Print a debug message with printf formatting.
566 * Requires double parenthesis around 2 or more args.
568 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
569 # define DPRINTF0(fmt, ...) \
570 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
572 # define DPRINTF(args) ((void) 0)
574 /** Print a debug string.
575 * The string is printed literally, with no format processing.
577 #define DPUTS(arg) DPRINTF(("%s", arg))
578 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
580 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
583 /** @brief The maximum size of a database page.
585 * It is 32k or 64k, since value-PAGEBASE must fit in
586 * #MDB_page.%mp_upper.
588 * LMDB will use database pages < OS pages if needed.
589 * That causes more I/O in write transactions: The OS must
590 * know (read) the whole page before writing a partial page.
592 * Note that we don't currently support Huge pages. On Linux,
593 * regular data files cannot use Huge pages, and in general
594 * Huge pages aren't actually pageable. We rely on the OS
595 * demand-pager to read our data and page it out when memory
596 * pressure from other processes is high. So until OSs have
597 * actual paging support for Huge pages, they're not viable.
599 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
601 /** The minimum number of keys required in a database page.
602 * Setting this to a larger value will place a smaller bound on the
603 * maximum size of a data item. Data items larger than this size will
604 * be pushed into overflow pages instead of being stored directly in
605 * the B-tree node. This value used to default to 4. With a page size
606 * of 4096 bytes that meant that any item larger than 1024 bytes would
607 * go into an overflow page. That also meant that on average 2-3KB of
608 * each overflow page was wasted space. The value cannot be lower than
609 * 2 because then there would no longer be a tree structure. With this
610 * value, items larger than 2KB will go into overflow pages, and on
611 * average only 1KB will be wasted.
613 #define MDB_MINKEYS 2
615 /** A stamp that identifies a file as an LMDB file.
616 * There's nothing special about this value other than that it is easily
617 * recognizable, and it will reflect any byte order mismatches.
619 #define MDB_MAGIC 0xBEEFC0DE
621 /** The version number for a database's datafile format. */
622 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
623 /** The version number for a database's lockfile format. */
624 #define MDB_LOCK_VERSION ((MDB_DEVEL) ? 999 : 2)
625 /** Number of bits representing #MDB_LOCK_VERSION in #MDB_LOCK_FORMAT.
626 * The remaining bits must leave room for #MDB_lock_desc.
628 #define MDB_LOCK_VERSION_BITS 12
630 /** @brief The max size of a key we can write, or 0 for computed max.
632 * This macro should normally be left alone or set to 0.
633 * Note that a database with big keys or dupsort data cannot be
634 * reliably modified by a liblmdb which uses a smaller max.
635 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
637 * Other values are allowed, for backwards compat. However:
638 * A value bigger than the computed max can break if you do not
639 * know what you are doing, and liblmdb <= 0.9.10 can break when
640 * modifying a DB with keys/dupsort data bigger than its max.
642 * Data items in an #MDB_DUPSORT database are also limited to
643 * this size, since they're actually keys of a sub-DB. Keys and
644 * #MDB_DUPSORT data items must fit on a node in a regular page.
646 #ifndef MDB_MAXKEYSIZE
647 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
650 /** The maximum size of a key we can write to the environment. */
652 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
654 #define ENV_MAXKEY(env) ((env)->me_maxkey)
657 /** @brief The maximum size of a data item.
659 * We only store a 32 bit value for node sizes.
661 #define MAXDATASIZE 0xffffffffUL
664 /** Key size which fits in a #DKBUF.
667 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
670 * This is used for printing a hex dump of a key's contents.
672 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
673 /** Display a key in hex.
675 * Invoke a function to display a key in hex.
677 #define DKEY(x) mdb_dkey(x, kbuf)
683 /** An invalid page number.
684 * Mainly used to denote an empty tree.
686 #define P_INVALID (~(pgno_t)0)
688 /** Test if the flags \b f are set in a flag word \b w. */
689 #define F_ISSET(w, f) (((w) & (f)) == (f))
691 /** Round \b n up to an even number. */
692 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
694 /** Least significant 1-bit of \b n. n must be of an unsigned type. */
695 #define LOW_BIT(n) ((n) & (-(n)))
697 /** (log2(\b p2) % \b n), for p2 = power of 2 and 0 < n < 8. */
698 #define LOG2_MOD(p2, n) (7 - 86 / ((p2) % ((1U<<(n))-1) + 11))
699 /* Explanation: Let p2 = 2**(n*y + x), x<n and M = (1U<<n)-1. Now p2 =
700 * (M+1)**y * 2**x = 2**x (mod M). Finally "/" "happens" to return 7-x.
703 /** Should be alignment of \b type. Ensure it is a power of 2. */
704 #define ALIGNOF2(type) \
705 LOW_BIT(offsetof(struct { char ch_; type align_; }, align_))
707 /** Used for offsets within a single page.
708 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
711 typedef uint16_t indx_t;
713 typedef unsigned long long mdb_hash_t;
715 /** Default size of memory map.
716 * This is certainly too small for any actual applications. Apps should always set
717 * the size explicitly using #mdb_env_set_mapsize().
719 #define DEFAULT_MAPSIZE 1048576
721 /** @defgroup readers Reader Lock Table
722 * Readers don't acquire any locks for their data access. Instead, they
723 * simply record their transaction ID in the reader table. The reader
724 * mutex is needed just to find an empty slot in the reader table. The
725 * slot's address is saved in thread-specific data so that subsequent read
726 * transactions started by the same thread need no further locking to proceed.
728 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
730 * No reader table is used if the database is on a read-only filesystem, or
731 * if #MDB_NOLOCK is set.
733 * Since the database uses multi-version concurrency control, readers don't
734 * actually need any locking. This table is used to keep track of which
735 * readers are using data from which old transactions, so that we'll know
736 * when a particular old transaction is no longer in use. Old transactions
737 * that have discarded any data pages can then have those pages reclaimed
738 * for use by a later write transaction.
740 * The lock table is constructed such that reader slots are aligned with the
741 * processor's cache line size. Any slot is only ever used by one thread.
742 * This alignment guarantees that there will be no contention or cache
743 * thrashing as threads update their own slot info, and also eliminates
744 * any need for locking when accessing a slot.
746 * A writer thread will scan every slot in the table to determine the oldest
747 * outstanding reader transaction. Any freed pages older than this will be
748 * reclaimed by the writer. The writer doesn't use any locks when scanning
749 * this table. This means that there's no guarantee that the writer will
750 * see the most up-to-date reader info, but that's not required for correct
751 * operation - all we need is to know the upper bound on the oldest reader,
752 * we don't care at all about the newest reader. So the only consequence of
753 * reading stale information here is that old pages might hang around a
754 * while longer before being reclaimed. That's actually good anyway, because
755 * the longer we delay reclaiming old pages, the more likely it is that a
756 * string of contiguous pages can be found after coalescing old pages from
757 * many old transactions together.
760 /** Number of slots in the reader table.
761 * This value was chosen somewhat arbitrarily. 126 readers plus a
762 * couple mutexes fit exactly into 8KB on my development machine.
763 * Applications should set the table size using #mdb_env_set_maxreaders().
765 #define DEFAULT_READERS 126
767 /** The size of a CPU cache line in bytes. We want our lock structures
768 * aligned to this size to avoid false cache line sharing in the
770 * This value works for most CPUs. For Itanium this should be 128.
776 /** The information we store in a single slot of the reader table.
777 * In addition to a transaction ID, we also record the process and
778 * thread ID that owns a slot, so that we can detect stale information,
779 * e.g. threads or processes that went away without cleaning up.
780 * @note We currently don't check for stale records. We simply re-init
781 * the table when we know that we're the only process opening the
784 typedef struct MDB_rxbody {
785 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
786 * Multiple readers that start at the same time will probably have the
787 * same ID here. Again, it's not important to exclude them from
788 * anything; all we need to know is which version of the DB they
789 * started from so we can avoid overwriting any data used in that
790 * particular version.
792 volatile txnid_t mrb_txnid;
793 /** The process ID of the process owning this reader txn. */
794 volatile MDB_PID_T mrb_pid;
795 /** The thread ID of the thread owning this txn. */
796 volatile MDB_THR_T mrb_tid;
799 /** The actual reader record, with cacheline padding. */
800 typedef struct MDB_reader {
803 /** shorthand for mrb_txnid */
804 #define mr_txnid mru.mrx.mrb_txnid
805 #define mr_pid mru.mrx.mrb_pid
806 #define mr_tid mru.mrx.mrb_tid
807 /** cache line alignment */
808 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
812 /** The header for the reader table.
813 * The table resides in a memory-mapped file. (This is a different file
814 * than is used for the main database.)
816 * For POSIX the actual mutexes reside in the shared memory of this
817 * mapped file. On Windows, mutexes are named objects allocated by the
818 * kernel; we store the mutex names in this mapped file so that other
819 * processes can grab them. This same approach is also used on
820 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
821 * process-shared POSIX mutexes. For these cases where a named object
822 * is used, the object name is derived from a 64 bit FNV hash of the
823 * environment pathname. As such, naming collisions are extremely
824 * unlikely. If a collision occurs, the results are unpredictable.
826 typedef struct MDB_txbody {
827 /** Stamp identifying this as an LMDB file. It must be set
830 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
832 /** The ID of the last transaction committed to the database.
833 * This is recorded here only for convenience; the value can always
834 * be determined by reading the main database meta pages.
836 volatile txnid_t mtb_txnid;
837 /** The number of slots that have been used in the reader table.
838 * This always records the maximum count, it is not decremented
839 * when readers release their slots.
841 volatile unsigned mtb_numreaders;
842 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
843 /** Binary form of names of the reader/writer locks */
844 mdb_hash_t mtb_mutexid;
845 #elif defined(MDB_USE_SYSV_SEM)
849 /** Mutex protecting access to this table.
850 * This is the reader table lock used with LOCK_MUTEX().
852 mdb_mutex_t mtb_rmutex;
856 /** The actual reader table definition. */
857 typedef struct MDB_txninfo {
860 #define mti_magic mt1.mtb.mtb_magic
861 #define mti_format mt1.mtb.mtb_format
862 #define mti_rmutex mt1.mtb.mtb_rmutex
863 #define mti_txnid mt1.mtb.mtb_txnid
864 #define mti_numreaders mt1.mtb.mtb_numreaders
865 #define mti_mutexid mt1.mtb.mtb_mutexid
866 #ifdef MDB_USE_SYSV_SEM
867 #define mti_semid mt1.mtb.mtb_semid
868 #define mti_rlocked mt1.mtb.mtb_rlocked
870 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
872 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM))
874 #ifdef MDB_USE_SYSV_SEM
876 #define mti_wlocked mt2.mt2_wlocked
878 mdb_mutex_t mt2_wmutex;
879 #define mti_wmutex mt2.mt2_wmutex
881 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
884 MDB_reader mti_readers[1];
887 /** Lockfile format signature: version, features and field layout */
888 #define MDB_LOCK_FORMAT \
890 (((MDB_LOCK_VERSION) % (1U << MDB_LOCK_VERSION_BITS)) \
891 + MDB_lock_desc * (1U << MDB_LOCK_VERSION_BITS)))
893 /** Lock type and layout. Values 0-119. _WIN32 implies #MDB_PIDLOCK.
894 * Some low values are reserved for future tweaks.
897 # define MDB_LOCK_TYPE (0 + ALIGNOF2(mdb_hash_t)/8 % 2)
898 #elif defined MDB_USE_POSIX_SEM
899 # define MDB_LOCK_TYPE (4 + ALIGNOF2(mdb_hash_t)/8 % 2)
900 #elif defined MDB_USE_SYSV_SEM
901 # define MDB_LOCK_TYPE (8)
902 #elif defined MDB_USE_POSIX_MUTEX
903 /* We do not know the inside of a POSIX mutex and how to check if mutexes
904 * used by two executables are compatible. Just check alignment and size.
906 # define MDB_LOCK_TYPE (10 + \
907 LOG2_MOD(ALIGNOF2(pthread_mutex_t), 5) + \
908 sizeof(pthread_mutex_t) / 4U % 22 * 5)
912 /** Magic number for lockfile layout and features.
914 * This *attempts* to stop liblmdb variants compiled with conflicting
915 * options from using the lockfile at the same time and thus breaking
916 * it. It describes locking types, and sizes and sometimes alignment
917 * of the various lockfile items.
919 * The detected ranges are mostly guesswork, or based simply on how
920 * big they could be without using more bits. So we can tweak them
921 * in good conscience when updating #MDB_LOCK_VERSION.
924 /* Default CACHELINE=64 vs. other values (have seen mention of 32-256) */
925 (CACHELINE==64 ? 0 : 1 + LOG2_MOD(CACHELINE >> (CACHELINE>64), 5))
926 + 6 * (sizeof(MDB_PID_T)/4 % 3) /* legacy(2) to word(4/8)? */
927 + 18 * (sizeof(pthread_t)/4 % 5) /* can be struct{id, active data} */
928 + 90 * (sizeof(MDB_txbody) / CACHELINE % 3)
929 + 270 * (MDB_LOCK_TYPE % 120)
930 /* The above is < 270*120 < 2**15 */
931 + ((sizeof(txnid_t) == 8) << 15) /* 32bit/64bit */
932 + ((sizeof(MDB_reader) > CACHELINE) << 16)
933 /* Not really needed - implied by MDB_LOCK_TYPE != (_WIN32 locking) */
934 + (((MDB_PIDLOCK) != 0) << 17)
935 /* 18 bits total: Must be <= (32 - MDB_LOCK_VERSION_BITS). */
939 /** Common header for all page types. The page type depends on #mp_flags.
941 * #P_BRANCH and #P_LEAF pages have unsorted '#MDB_node's at the end, with
942 * sorted #mp_ptrs[] entries referring to them. Exception: #P_LEAF2 pages
943 * omit mp_ptrs and pack sorted #MDB_DUPFIXED values after the page header.
945 * #P_OVERFLOW records occupy one or more contiguous pages where only the
946 * first has a page header. They hold the real data of #F_BIGDATA nodes.
948 * #P_SUBP sub-pages are small leaf "pages" with duplicate data.
949 * A node with flag #F_DUPDATA but not #F_SUBDATA contains a sub-page.
950 * (Duplicate data can also go in sub-databases, which use normal pages.)
952 * #P_META pages contain #MDB_meta, the start point of an LMDB snapshot.
954 * Each non-metapage up to #MDB_meta.%mm_last_pg is reachable exactly once
955 * in the snapshot: Either used by a database or listed in a freeDB record.
957 typedef struct MDB_page {
958 #define mp_pgno mp_p.p_pgno
959 #define mp_next mp_p.p_next
961 pgno_t p_pgno; /**< page number */
962 struct MDB_page *p_next; /**< for in-memory list of freed pages */
964 uint16_t mp_pad; /**< key size if this is a LEAF2 page */
965 /** @defgroup mdb_page Page Flags
967 * Flags for the page headers.
970 #define P_BRANCH 0x01 /**< branch page */
971 #define P_LEAF 0x02 /**< leaf page */
972 #define P_OVERFLOW 0x04 /**< overflow page */
973 #define P_META 0x08 /**< meta page */
974 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
975 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
976 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
977 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
978 #define P_KEEP 0x8000 /**< leave this page alone during spill */
980 uint16_t mp_flags; /**< @ref mdb_page */
981 #define mp_lower mp_pb.pb.pb_lower
982 #define mp_upper mp_pb.pb.pb_upper
983 #define mp_pages mp_pb.pb_pages
986 indx_t pb_lower; /**< lower bound of free space */
987 indx_t pb_upper; /**< upper bound of free space */
989 uint32_t pb_pages; /**< number of overflow pages */
991 indx_t mp_ptrs[1]; /**< dynamic size */
994 /** Size of the page header, excluding dynamic data at the end */
995 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
997 /** Address of first usable data byte in a page, after the header */
998 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
1000 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
1001 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
1003 /** Number of nodes on a page */
1004 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
1006 /** The amount of space remaining in the page */
1007 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
1009 /** The percentage of space used in the page, in tenths of a percent. */
1010 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
1011 ((env)->me_psize - PAGEHDRSZ))
1012 /** The minimum page fill factor, in tenths of a percent.
1013 * Pages emptier than this are candidates for merging.
1015 #define FILL_THRESHOLD 250
1017 /** Test if a page is a leaf page */
1018 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
1019 /** Test if a page is a LEAF2 page */
1020 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
1021 /** Test if a page is a branch page */
1022 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
1023 /** Test if a page is an overflow page */
1024 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
1025 /** Test if a page is a sub page */
1026 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
1028 /** The number of overflow pages needed to store the given size. */
1029 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
1031 /** Link in #MDB_txn.%mt_loose_pgs list.
1032 * Kept outside the page header, which is needed when reusing the page.
1034 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
1036 /** Header for a single key/data pair within a page.
1037 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
1038 * We guarantee 2-byte alignment for 'MDB_node's.
1040 * #mn_lo and #mn_hi are used for data size on leaf nodes, and for child
1041 * pgno on branch nodes. On 64 bit platforms, #mn_flags is also used
1042 * for pgno. (Branch nodes have no flags). Lo and hi are in host byte
1043 * order in case some accesses can be optimized to 32-bit word access.
1045 * Leaf node flags describe node contents. #F_BIGDATA says the node's
1046 * data part is the page number of an overflow page with actual data.
1047 * #F_DUPDATA and #F_SUBDATA can be combined giving duplicate data in
1048 * a sub-page/sub-database, and named databases (just #F_SUBDATA).
1050 typedef struct MDB_node {
1051 /** part of data size or pgno
1053 #if BYTE_ORDER == LITTLE_ENDIAN
1054 unsigned short mn_lo, mn_hi;
1056 unsigned short mn_hi, mn_lo;
1059 /** @defgroup mdb_node Node Flags
1061 * Flags for node headers.
1064 #define F_BIGDATA 0x01 /**< data put on overflow page */
1065 #define F_SUBDATA 0x02 /**< data is a sub-database */
1066 #define F_DUPDATA 0x04 /**< data has duplicates */
1068 /** valid flags for #mdb_node_add() */
1069 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
1072 unsigned short mn_flags; /**< @ref mdb_node */
1073 unsigned short mn_ksize; /**< key size */
1074 char mn_data[1]; /**< key and data are appended here */
1077 /** Size of the node header, excluding dynamic data at the end */
1078 #define NODESIZE offsetof(MDB_node, mn_data)
1080 /** Bit position of top word in page number, for shifting mn_flags */
1081 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
1083 /** Size of a node in a branch page with a given key.
1084 * This is just the node header plus the key, there is no data.
1086 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
1088 /** Size of a node in a leaf page with a given key and data.
1089 * This is node header plus key plus data size.
1091 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
1093 /** Address of node \b i in page \b p */
1094 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
1096 /** Address of the key for the node */
1097 #define NODEKEY(node) (void *)((node)->mn_data)
1099 /** Address of the data for a node */
1100 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
1102 /** Get the page number pointed to by a branch node */
1103 #define NODEPGNO(node) \
1104 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
1105 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
1106 /** Set the page number in a branch node */
1107 #define SETPGNO(node,pgno) do { \
1108 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
1109 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
1111 /** Get the size of the data in a leaf node */
1112 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
1113 /** Set the size of the data for a leaf node */
1114 #define SETDSZ(node,size) do { \
1115 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
1116 /** The size of a key in a node */
1117 #define NODEKSZ(node) ((node)->mn_ksize)
1119 /** Copy a page number from src to dst */
1120 #ifdef MISALIGNED_OK
1121 #define COPY_PGNO(dst,src) dst = src
1123 #if MDB_SIZE_MAX > 0xffffffffU
1124 #define COPY_PGNO(dst,src) do { \
1125 unsigned short *s, *d; \
1126 s = (unsigned short *)&(src); \
1127 d = (unsigned short *)&(dst); \
1134 #define COPY_PGNO(dst,src) do { \
1135 unsigned short *s, *d; \
1136 s = (unsigned short *)&(src); \
1137 d = (unsigned short *)&(dst); \
1143 /** The address of a key in a LEAF2 page.
1144 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
1145 * There are no node headers, keys are stored contiguously.
1147 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
1149 /** Set the \b node's key into \b keyptr, if requested. */
1150 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
1151 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
1153 /** Set the \b node's key into \b key. */
1154 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
1156 /** Information about a single database in the environment. */
1157 typedef struct MDB_db {
1158 uint32_t md_pad; /**< also ksize for LEAF2 pages */
1159 uint16_t md_flags; /**< @ref mdb_dbi_open */
1160 uint16_t md_depth; /**< depth of this tree */
1161 pgno_t md_branch_pages; /**< number of internal pages */
1162 pgno_t md_leaf_pages; /**< number of leaf pages */
1163 pgno_t md_overflow_pages; /**< number of overflow pages */
1164 mdb_size_t md_entries; /**< number of data items */
1165 pgno_t md_root; /**< the root page of this tree */
1168 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
1169 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
1170 /** #mdb_dbi_open() flags */
1171 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
1172 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
1174 /** Handle for the DB used to track free pages. */
1176 /** Handle for the default DB. */
1178 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
1181 /** Number of meta pages - also hardcoded elsewhere */
1184 /** Meta page content.
1185 * A meta page is the start point for accessing a database snapshot.
1186 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
1188 typedef struct MDB_meta {
1189 /** Stamp identifying this as an LMDB file. It must be set
1192 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
1193 uint32_t mm_version;
1195 union { /* always zero since we don't support fixed mapping in MDB_VL32 */
1199 #define mm_address mm_un.mmun_address
1201 void *mm_address; /**< address for fixed mapping */
1203 mdb_size_t mm_mapsize; /**< size of mmap region */
1204 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
1205 /** The size of pages used in this DB */
1206 #define mm_psize mm_dbs[FREE_DBI].md_pad
1207 /** Any persistent environment flags. @ref mdb_env */
1208 #define mm_flags mm_dbs[FREE_DBI].md_flags
1209 /** Last used page in the datafile.
1210 * Actually the file may be shorter if the freeDB lists the final pages.
1213 volatile txnid_t mm_txnid; /**< txnid that committed this page */
1216 /** Buffer for a stack-allocated meta page.
1217 * The members define size and alignment, and silence type
1218 * aliasing warnings. They are not used directly; that could
1219 * mean incorrectly using several union members in parallel.
1221 typedef union MDB_metabuf {
1224 char mm_pad[PAGEHDRSZ];
1229 /** Auxiliary DB info.
1230 * The information here is mostly static/read-only. There is
1231 * only a single copy of this record in the environment.
1233 typedef struct MDB_dbx {
1234 MDB_val md_name; /**< name of the database */
1235 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1236 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1237 MDB_rel_func *md_rel; /**< user relocate function */
1238 void *md_relctx; /**< user-provided context for md_rel */
1241 /** A database transaction.
1242 * Every operation requires a transaction handle.
1245 MDB_txn *mt_parent; /**< parent of a nested txn */
1246 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1248 pgno_t mt_next_pgno; /**< next unallocated page */
1250 pgno_t mt_last_pgno; /**< last written page */
1252 /** The ID of this transaction. IDs are integers incrementing from 1.
1253 * Only committed write transactions increment the ID. If a transaction
1254 * aborts, the ID may be re-used by the next writer.
1257 MDB_env *mt_env; /**< the DB environment */
1258 /** The list of pages that became unused during this transaction.
1260 MDB_IDL mt_free_pgs;
1261 /** The list of loose pages that became unused and may be reused
1262 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1264 MDB_page *mt_loose_pgs;
1265 /** Number of loose pages (#mt_loose_pgs) */
1267 /** The sorted list of dirty pages we temporarily wrote to disk
1268 * because the dirty list was full. page numbers in here are
1269 * shifted left by 1, deleted slots have the LSB set.
1271 MDB_IDL mt_spill_pgs;
1273 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1274 MDB_ID2L dirty_list;
1275 /** For read txns: This thread/txn's reader table slot, or NULL. */
1278 /** Array of records for each DB known in the environment. */
1280 /** Array of MDB_db records for each known DB */
1282 /** Array of sequence numbers for each DB handle */
1283 unsigned int *mt_dbiseqs;
1284 /** @defgroup mt_dbflag Transaction DB Flags
1288 #define DB_DIRTY 0x01 /**< DB was written in this txn */
1289 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1290 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1291 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1292 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1293 #define DB_DUPDATA 0x20 /**< DB is #MDB_DUPSORT data */
1295 /** In write txns, array of cursors for each DB */
1296 MDB_cursor **mt_cursors;
1297 /** Array of flags for each DB */
1298 unsigned char *mt_dbflags;
1300 /** List of read-only pages (actually chunks) */
1302 /** We map chunks of 16 pages. Even though Windows uses 4KB pages, all
1303 * mappings must begin on 64KB boundaries. So we round off all pgnos to
1304 * a chunk boundary. We do the same on Linux for symmetry, and also to
1305 * reduce the frequency of mmap/munmap calls.
1307 #define MDB_RPAGE_CHUNK 16
1308 #define MDB_TRPAGE_SIZE 4096 /**< size of #mt_rpages array of chunks */
1309 #define MDB_TRPAGE_MAX (MDB_TRPAGE_SIZE-1) /**< maximum chunk index */
1310 unsigned int mt_rpcheck; /**< threshold for reclaiming unref'd chunks */
1312 /** Number of DB records in use, or 0 when the txn is finished.
1313 * This number only ever increments until the txn finishes; we
1314 * don't decrement it when individual DB handles are closed.
1318 /** @defgroup mdb_txn Transaction Flags
1322 /** #mdb_txn_begin() flags */
1323 #define MDB_TXN_BEGIN_FLAGS (MDB_NOMETASYNC|MDB_NOSYNC|MDB_RDONLY)
1324 #define MDB_TXN_NOMETASYNC MDB_NOMETASYNC /**< don't sync meta for this txn on commit */
1325 #define MDB_TXN_NOSYNC MDB_NOSYNC /**< don't sync this txn on commit */
1326 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1327 /* internal txn flags */
1328 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1329 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1330 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1331 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1332 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1333 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1334 /** most operations on the txn are currently illegal */
1335 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1337 unsigned int mt_flags; /**< @ref mdb_txn */
1338 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1339 * Includes ancestor txns' dirty pages not hidden by other txns'
1340 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1341 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1343 unsigned int mt_dirty_room;
1346 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1347 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1348 * raise this on a 64 bit machine.
1350 #define CURSOR_STACK 32
1354 /** Cursors are used for all DB operations.
1355 * A cursor holds a path of (page pointer, key index) from the DB
1356 * root to a position in the DB, plus other state. #MDB_DUPSORT
1357 * cursors include an xcursor to the current data item. Write txns
1358 * track their cursors and keep them up to date when data moves.
1359 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1360 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1363 /** Next cursor on this DB in this txn */
1364 MDB_cursor *mc_next;
1365 /** Backup of the original cursor if this cursor is a shadow */
1366 MDB_cursor *mc_backup;
1367 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1368 struct MDB_xcursor *mc_xcursor;
1369 /** The transaction that owns this cursor */
1371 /** The database handle this cursor operates on */
1373 /** The database record for this cursor */
1375 /** The database auxiliary record for this cursor */
1377 /** The @ref mt_dbflag for this database */
1378 unsigned char *mc_dbflag;
1379 unsigned short mc_snum; /**< number of pushed pages */
1380 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1381 /** @defgroup mdb_cursor Cursor Flags
1383 * Cursor state flags.
1386 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1387 #define C_EOF 0x02 /**< No more data */
1388 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1389 #define C_DEL 0x08 /**< last op was a cursor_del */
1390 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1391 #define C_WRITEMAP MDB_TXN_WRITEMAP /**< Copy of txn flag */
1392 /** Read-only cursor into the txn's original snapshot in the map.
1393 * Set for read-only txns, and in #mdb_page_alloc() for #FREE_DBI when
1394 * #MDB_DEVEL & 2. Only implements code which is necessary for this.
1396 #define C_ORIG_RDONLY MDB_TXN_RDONLY
1398 unsigned int mc_flags; /**< @ref mdb_cursor */
1399 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1400 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1402 MDB_page *mc_ovpg; /**< a referenced overflow page */
1403 # define MC_OVPG(mc) ((mc)->mc_ovpg)
1404 # define MC_SET_OVPG(mc, pg) ((mc)->mc_ovpg = (pg))
1406 # define MC_OVPG(mc) ((MDB_page *)0)
1407 # define MC_SET_OVPG(mc, pg) ((void)0)
1411 /** Context for sorted-dup records.
1412 * We could have gone to a fully recursive design, with arbitrarily
1413 * deep nesting of sub-databases. But for now we only handle these
1414 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1416 typedef struct MDB_xcursor {
1417 /** A sub-cursor for traversing the Dup DB */
1418 MDB_cursor mx_cursor;
1419 /** The database record for this Dup DB */
1421 /** The auxiliary DB record for this Dup DB */
1423 /** The @ref mt_dbflag for this Dup DB */
1424 unsigned char mx_dbflag;
1427 /** Check if there is an inited xcursor */
1428 #define XCURSOR_INITED(mc) \
1429 ((mc)->mc_xcursor && ((mc)->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
1431 /** Update the xcursor's sub-page pointer, if any, in \b mc. Needed
1432 * when the node which contains the sub-page may have moved. Called
1433 * with leaf page \b mp = mc->mc_pg[\b top].
1435 #define XCURSOR_REFRESH(mc, top, mp) do { \
1436 MDB_page *xr_pg = (mp); \
1437 MDB_node *xr_node; \
1438 if (!XCURSOR_INITED(mc) || (mc)->mc_ki[top] >= NUMKEYS(xr_pg)) break; \
1439 xr_node = NODEPTR(xr_pg, (mc)->mc_ki[top]); \
1440 if ((xr_node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) \
1441 (mc)->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(xr_node); \
1444 /** State of FreeDB old pages, stored in the MDB_env */
1445 typedef struct MDB_pgstate {
1446 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1447 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1450 /** The database environment. */
1452 HANDLE me_fd; /**< The main data file */
1453 HANDLE me_lfd; /**< The lock file */
1454 HANDLE me_mfd; /**< For writing and syncing the meta pages */
1455 #if defined(MDB_VL32) && defined(_WIN32)
1456 HANDLE me_fmh; /**< File Mapping handle */
1458 /** Failed to update the meta page. Probably an I/O error. */
1459 #define MDB_FATAL_ERROR 0x80000000U
1460 /** Some fields are initialized. */
1461 #define MDB_ENV_ACTIVE 0x20000000U
1462 /** me_txkey is set */
1463 #define MDB_ENV_TXKEY 0x10000000U
1464 /** fdatasync is unreliable */
1465 #define MDB_FSYNCONLY 0x08000000U
1466 uint32_t me_flags; /**< @ref mdb_env */
1467 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1468 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1469 unsigned int me_maxreaders; /**< size of the reader table */
1470 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1471 volatile int me_close_readers;
1472 MDB_dbi me_numdbs; /**< number of DBs opened */
1473 MDB_dbi me_maxdbs; /**< size of the DB table */
1474 MDB_PID_T me_pid; /**< process ID of this env */
1475 char *me_path; /**< path to the DB files */
1476 char *me_map; /**< the memory map of the data file */
1477 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1478 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1479 void *me_pbuf; /**< scratch area for DUPSORT put() */
1480 MDB_txn *me_txn; /**< current write transaction */
1481 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1482 mdb_size_t me_mapsize; /**< size of the data memory map */
1483 off_t me_size; /**< current file size */
1484 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1485 MDB_dbx *me_dbxs; /**< array of static DB info */
1486 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1487 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1488 pthread_key_t me_txkey; /**< thread-key for readers */
1489 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1490 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1491 # define me_pglast me_pgstate.mf_pglast
1492 # define me_pghead me_pgstate.mf_pghead
1493 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1494 /** IDL of pages that became unused in a write txn */
1495 MDB_IDL me_free_pgs;
1496 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1497 MDB_ID2L me_dirty_list;
1498 /** Max number of freelist items that can fit in a single overflow page */
1500 /** Max size of a node on a page */
1501 unsigned int me_nodemax;
1502 #if !(MDB_MAXKEYSIZE)
1503 unsigned int me_maxkey; /**< max size of a key */
1505 int me_live_reader; /**< have liveness lock in reader table */
1507 int me_pidquery; /**< Used in OpenProcess */
1509 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1510 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1511 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1513 mdb_mutex_t me_rmutex;
1514 mdb_mutex_t me_wmutex;
1515 # if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
1516 /** Half-initialized name of mutexes, to be completed by #MUTEXNAME() */
1517 char me_mutexname[sizeof(MUTEXNAME_PREFIX) + 11];
1521 MDB_ID3L me_rpages; /**< like #mt_rpages, but global to env */
1522 pthread_mutex_t me_rpmutex; /**< control access to #me_rpages */
1523 #define MDB_ERPAGE_SIZE 16384
1524 #define MDB_ERPAGE_MAX (MDB_ERPAGE_SIZE-1)
1525 unsigned int me_rpcheck;
1527 void *me_userctx; /**< User-settable context */
1528 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1531 /** Nested transaction */
1532 typedef struct MDB_ntxn {
1533 MDB_txn mnt_txn; /**< the transaction */
1534 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1537 /** max number of pages to commit in one writev() call */
1538 #define MDB_COMMIT_PAGES 64
1539 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1540 #undef MDB_COMMIT_PAGES
1541 #define MDB_COMMIT_PAGES IOV_MAX
1544 /** max bytes to write in one call */
1545 #define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
1547 /** Check \b txn and \b dbi arguments to a function */
1548 #define TXN_DBI_EXIST(txn, dbi, validity) \
1549 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1551 /** Check for misused \b dbi handles */
1552 #define TXN_DBI_CHANGED(txn, dbi) \
1553 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1555 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1556 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1557 static int mdb_page_touch(MDB_cursor *mc);
1559 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1560 "reset-tmp", "fail-begin", "fail-beginchild"}
1562 /* mdb_txn_end operation number, for logging */
1563 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1564 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1566 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1567 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1568 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1569 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1570 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1572 static int mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
1573 static int mdb_page_search_root(MDB_cursor *mc,
1574 MDB_val *key, int modify);
1575 #define MDB_PS_MODIFY 1
1576 #define MDB_PS_ROOTONLY 2
1577 #define MDB_PS_FIRST 4
1578 #define MDB_PS_LAST 8
1579 static int mdb_page_search(MDB_cursor *mc,
1580 MDB_val *key, int flags);
1581 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1583 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1584 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1585 pgno_t newpgno, unsigned int nflags);
1587 static int mdb_env_read_header(MDB_env *env, int prev, MDB_meta *meta);
1588 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1589 static int mdb_env_write_meta(MDB_txn *txn);
1590 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1591 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1593 static void mdb_env_close0(MDB_env *env, int excl);
1595 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1596 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1597 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1598 static void mdb_node_del(MDB_cursor *mc, int ksize);
1599 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1600 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1601 static int mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
1602 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1603 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1605 static int mdb_rebalance(MDB_cursor *mc);
1606 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1608 static void mdb_cursor_pop(MDB_cursor *mc);
1609 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1611 static int mdb_cursor_del0(MDB_cursor *mc);
1612 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1613 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1614 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1615 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1616 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1618 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1619 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1621 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1622 static void mdb_xcursor_init0(MDB_cursor *mc);
1623 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1624 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1626 static int mdb_drop0(MDB_cursor *mc, int subs);
1627 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1628 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1631 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1634 /** Compare two items pointing at '#mdb_size_t's of unknown alignment. */
1635 #ifdef MISALIGNED_OK
1636 # define mdb_cmp_clong mdb_cmp_long
1638 # define mdb_cmp_clong mdb_cmp_cint
1641 /** True if we need #mdb_cmp_clong() instead of \b cmp for #MDB_INTEGERDUP */
1642 #define NEED_CMP_CLONG(cmp, ksize) \
1643 (UINT_MAX < MDB_SIZE_MAX && \
1644 (cmp) == mdb_cmp_int && (ksize) == sizeof(mdb_size_t))
1647 static SECURITY_DESCRIPTOR mdb_null_sd;
1648 static SECURITY_ATTRIBUTES mdb_all_sa;
1649 static int mdb_sec_inited;
1652 static int utf8_to_utf16(const char *src, struct MDB_name *dst, int xtra);
1655 /** Return the library version info. */
1657 mdb_version(int *major, int *minor, int *patch)
1659 if (major) *major = MDB_VERSION_MAJOR;
1660 if (minor) *minor = MDB_VERSION_MINOR;
1661 if (patch) *patch = MDB_VERSION_PATCH;
1662 return MDB_VERSION_STRING;
1665 /** Table of descriptions for LMDB @ref errors */
1666 static char *const mdb_errstr[] = {
1667 "MDB_KEYEXIST: Key/data pair already exists",
1668 "MDB_NOTFOUND: No matching key/data pair found",
1669 "MDB_PAGE_NOTFOUND: Requested page not found",
1670 "MDB_CORRUPTED: Located page was wrong type",
1671 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1672 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1673 "MDB_INVALID: File is not an LMDB file",
1674 "MDB_MAP_FULL: Environment mapsize limit reached",
1675 "MDB_DBS_FULL: Environment maxdbs limit reached",
1676 "MDB_READERS_FULL: Environment maxreaders limit reached",
1677 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1678 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1679 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1680 "MDB_PAGE_FULL: Internal error - page has no more space",
1681 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1682 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1683 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1684 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1685 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1686 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1687 "MDB_PROBLEM: Unexpected problem - txn should abort",
1691 mdb_strerror(int err)
1694 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1695 * This works as long as no function between the call to mdb_strerror
1696 * and the actual use of the message uses more than 4K of stack.
1698 #define MSGSIZE 1024
1699 #define PADSIZE 4096
1700 char buf[MSGSIZE+PADSIZE], *ptr = buf;
1704 return ("Successful return: 0");
1706 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1707 i = err - MDB_KEYEXIST;
1708 return mdb_errstr[i];
1712 /* These are the C-runtime error codes we use. The comment indicates
1713 * their numeric value, and the Win32 error they would correspond to
1714 * if the error actually came from a Win32 API. A major mess, we should
1715 * have used LMDB-specific error codes for everything.
1718 case ENOENT: /* 2, FILE_NOT_FOUND */
1719 case EIO: /* 5, ACCESS_DENIED */
1720 case ENOMEM: /* 12, INVALID_ACCESS */
1721 case EACCES: /* 13, INVALID_DATA */
1722 case EBUSY: /* 16, CURRENT_DIRECTORY */
1723 case EINVAL: /* 22, BAD_COMMAND */
1724 case ENOSPC: /* 28, OUT_OF_PAPER */
1725 return strerror(err);
1730 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1731 FORMAT_MESSAGE_IGNORE_INSERTS,
1732 NULL, err, 0, ptr, MSGSIZE, (va_list *)buf+MSGSIZE);
1735 return strerror(err);
1739 /** assert(3) variant in cursor context */
1740 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1741 /** assert(3) variant in transaction context */
1742 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1743 /** assert(3) variant in environment context */
1744 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1747 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1748 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1751 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1752 const char *func, const char *file, int line)
1755 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1756 file, line, expr_txt, func);
1757 if (env->me_assert_func)
1758 env->me_assert_func(env, buf);
1759 fprintf(stderr, "%s\n", buf);
1763 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1767 /** Return the page number of \b mp which may be sub-page, for debug output */
1769 mdb_dbg_pgno(MDB_page *mp)
1772 COPY_PGNO(ret, mp->mp_pgno);
1776 /** Display a key in hexadecimal and return the address of the result.
1777 * @param[in] key the key to display
1778 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1779 * @return The key in hexadecimal form.
1782 mdb_dkey(MDB_val *key, char *buf)
1785 unsigned char *c = key->mv_data;
1791 if (key->mv_size > DKBUF_MAXKEYSIZE)
1792 return "MDB_MAXKEYSIZE";
1793 /* may want to make this a dynamic check: if the key is mostly
1794 * printable characters, print it as-is instead of converting to hex.
1798 for (i=0; i<key->mv_size; i++)
1799 ptr += sprintf(ptr, "%02x", *c++);
1801 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1807 mdb_leafnode_type(MDB_node *n)
1809 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1810 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1811 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1814 /** Display all the keys in the page. */
1816 mdb_page_list(MDB_page *mp)
1818 pgno_t pgno = mdb_dbg_pgno(mp);
1819 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1821 unsigned int i, nkeys, nsize, total = 0;
1825 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1826 case P_BRANCH: type = "Branch page"; break;
1827 case P_LEAF: type = "Leaf page"; break;
1828 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1829 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1830 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1832 fprintf(stderr, "Overflow page %"Yu" pages %u%s\n",
1833 pgno, mp->mp_pages, state);
1836 fprintf(stderr, "Meta-page %"Yu" txnid %"Yu"\n",
1837 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1840 fprintf(stderr, "Bad page %"Yu" flags 0x%X\n", pgno, mp->mp_flags);
1844 nkeys = NUMKEYS(mp);
1845 fprintf(stderr, "%s %"Yu" numkeys %d%s\n", type, pgno, nkeys, state);
1847 for (i=0; i<nkeys; i++) {
1848 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1849 key.mv_size = nsize = mp->mp_pad;
1850 key.mv_data = LEAF2KEY(mp, i, nsize);
1852 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1855 node = NODEPTR(mp, i);
1856 key.mv_size = node->mn_ksize;
1857 key.mv_data = node->mn_data;
1858 nsize = NODESIZE + key.mv_size;
1859 if (IS_BRANCH(mp)) {
1860 fprintf(stderr, "key %d: page %"Yu", %s\n", i, NODEPGNO(node),
1864 if (F_ISSET(node->mn_flags, F_BIGDATA))
1865 nsize += sizeof(pgno_t);
1867 nsize += NODEDSZ(node);
1869 nsize += sizeof(indx_t);
1870 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1871 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1873 total = EVEN(total);
1875 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1876 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1880 mdb_cursor_chk(MDB_cursor *mc)
1886 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1887 for (i=0; i<mc->mc_top; i++) {
1889 node = NODEPTR(mp, mc->mc_ki[i]);
1890 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1893 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1895 if (XCURSOR_INITED(mc)) {
1896 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1897 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1898 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1906 /** Count all the pages in each DB and in the freelist
1907 * and make sure it matches the actual number of pages
1909 * All named DBs must be open for a correct count.
1911 static void mdb_audit(MDB_txn *txn)
1915 MDB_ID freecount, count;
1920 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1921 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1922 freecount += *(MDB_ID *)data.mv_data;
1923 mdb_tassert(txn, rc == MDB_NOTFOUND);
1926 for (i = 0; i<txn->mt_numdbs; i++) {
1928 if (!(txn->mt_dbflags[i] & DB_VALID))
1930 mdb_cursor_init(&mc, txn, i, &mx);
1931 if (txn->mt_dbs[i].md_root == P_INVALID)
1933 count += txn->mt_dbs[i].md_branch_pages +
1934 txn->mt_dbs[i].md_leaf_pages +
1935 txn->mt_dbs[i].md_overflow_pages;
1936 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1937 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1938 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1941 mp = mc.mc_pg[mc.mc_top];
1942 for (j=0; j<NUMKEYS(mp); j++) {
1943 MDB_node *leaf = NODEPTR(mp, j);
1944 if (leaf->mn_flags & F_SUBDATA) {
1946 memcpy(&db, NODEDATA(leaf), sizeof(db));
1947 count += db.md_branch_pages + db.md_leaf_pages +
1948 db.md_overflow_pages;
1952 mdb_tassert(txn, rc == MDB_NOTFOUND);
1955 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1956 fprintf(stderr, "audit: %"Yu" freecount: %"Yu" count: %"Yu" total: %"Yu" next_pgno: %"Yu"\n",
1957 txn->mt_txnid, freecount, count+NUM_METAS,
1958 freecount+count+NUM_METAS, txn->mt_next_pgno);
1964 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1966 return txn->mt_dbxs[dbi].md_cmp(a, b);
1970 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1972 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1973 if (NEED_CMP_CLONG(dcmp, a->mv_size))
1974 dcmp = mdb_cmp_clong;
1978 /** Allocate memory for a page.
1979 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1980 * Set #MDB_TXN_ERROR on failure.
1983 mdb_page_malloc(MDB_txn *txn, unsigned num)
1985 MDB_env *env = txn->mt_env;
1986 MDB_page *ret = env->me_dpages;
1987 size_t psize = env->me_psize, sz = psize, off;
1988 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1989 * For a single page alloc, we init everything after the page header.
1990 * For multi-page, we init the final page; if the caller needed that
1991 * many pages they will be filling in at least up to the last page.
1995 VGMEMP_ALLOC(env, ret, sz);
1996 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1997 env->me_dpages = ret->mp_next;
2000 psize -= off = PAGEHDRSZ;
2005 if ((ret = malloc(sz)) != NULL) {
2006 VGMEMP_ALLOC(env, ret, sz);
2007 if (!(env->me_flags & MDB_NOMEMINIT)) {
2008 memset((char *)ret + off, 0, psize);
2012 txn->mt_flags |= MDB_TXN_ERROR;
2016 /** Free a single page.
2017 * Saves single pages to a list, for future reuse.
2018 * (This is not used for multi-page overflow pages.)
2021 mdb_page_free(MDB_env *env, MDB_page *mp)
2023 mp->mp_next = env->me_dpages;
2024 VGMEMP_FREE(env, mp);
2025 env->me_dpages = mp;
2028 /** Free a dirty page */
2030 mdb_dpage_free(MDB_env *env, MDB_page *dp)
2032 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
2033 mdb_page_free(env, dp);
2035 /* large pages just get freed directly */
2036 VGMEMP_FREE(env, dp);
2041 /** Return all dirty pages to dpage list */
2043 mdb_dlist_free(MDB_txn *txn)
2045 MDB_env *env = txn->mt_env;
2046 MDB_ID2L dl = txn->mt_u.dirty_list;
2047 unsigned i, n = dl[0].mid;
2049 for (i = 1; i <= n; i++) {
2050 mdb_dpage_free(env, dl[i].mptr);
2057 mdb_page_unref(MDB_txn *txn, MDB_page *mp)
2060 MDB_ID3L tl = txn->mt_rpages;
2062 if (mp->mp_flags & (P_SUBP|P_DIRTY))
2064 rem = mp->mp_pgno & (MDB_RPAGE_CHUNK-1);
2065 pgno = mp->mp_pgno ^ rem;
2066 x = mdb_mid3l_search(tl, pgno);
2067 if (x != tl[0].mid && tl[x+1].mid == mp->mp_pgno)
2072 #define MDB_PAGE_UNREF(txn, mp) mdb_page_unref(txn, mp)
2075 mdb_cursor_unref(MDB_cursor *mc)
2078 if (mc->mc_txn->mt_rpages[0].mid) {
2079 if (!mc->mc_snum || !mc->mc_pg[0] || IS_SUBP(mc->mc_pg[0]))
2081 for (i=0; i<mc->mc_snum; i++)
2082 mdb_page_unref(mc->mc_txn, mc->mc_pg[i]);
2084 mdb_page_unref(mc->mc_txn, mc->mc_ovpg);
2088 mc->mc_snum = mc->mc_top = 0;
2089 mc->mc_pg[0] = NULL;
2090 mc->mc_flags &= ~C_INITIALIZED;
2092 #define MDB_CURSOR_UNREF(mc, force) \
2093 (((force) || ((mc)->mc_flags & C_INITIALIZED)) \
2094 ? mdb_cursor_unref(mc) \
2098 #define MDB_PAGE_UNREF(txn, mp)
2099 #define MDB_CURSOR_UNREF(mc, force) ((void)0)
2100 #endif /* MDB_VL32 */
2102 /** Loosen or free a single page.
2103 * Saves single pages to a list for future reuse
2104 * in this same txn. It has been pulled from the freeDB
2105 * and already resides on the dirty list, but has been
2106 * deleted. Use these pages first before pulling again
2109 * If the page wasn't dirtied in this txn, just add it
2110 * to this txn's free list.
2113 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
2116 pgno_t pgno = mp->mp_pgno;
2117 MDB_txn *txn = mc->mc_txn;
2119 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
2120 if (txn->mt_parent) {
2121 MDB_ID2 *dl = txn->mt_u.dirty_list;
2122 /* If txn has a parent, make sure the page is in our
2126 unsigned x = mdb_mid2l_search(dl, pgno);
2127 if (x <= dl[0].mid && dl[x].mid == pgno) {
2128 if (mp != dl[x].mptr) { /* bad cursor? */
2129 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2130 txn->mt_flags |= MDB_TXN_ERROR;
2138 /* no parent txn, so it's just ours */
2143 DPRINTF(("loosen db %d page %"Yu, DDBI(mc), mp->mp_pgno));
2144 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
2145 txn->mt_loose_pgs = mp;
2146 txn->mt_loose_count++;
2147 mp->mp_flags |= P_LOOSE;
2149 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
2157 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
2158 * @param[in] mc A cursor handle for the current operation.
2159 * @param[in] pflags Flags of the pages to update:
2160 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
2161 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
2162 * @return 0 on success, non-zero on failure.
2165 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
2167 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
2168 MDB_txn *txn = mc->mc_txn;
2169 MDB_cursor *m3, *m0 = mc;
2174 int rc = MDB_SUCCESS, level;
2176 /* Mark pages seen by cursors: First m0, then tracked cursors */
2177 for (i = txn->mt_numdbs;; ) {
2178 if (mc->mc_flags & C_INITIALIZED) {
2179 for (m3 = mc;; m3 = &mx->mx_cursor) {
2181 for (j=0; j<m3->mc_snum; j++) {
2183 if ((mp->mp_flags & Mask) == pflags)
2184 mp->mp_flags ^= P_KEEP;
2186 mx = m3->mc_xcursor;
2187 /* Proceed to mx if it is at a sub-database */
2188 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
2190 if (! (mp && (mp->mp_flags & P_LEAF)))
2192 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
2193 if (!(leaf->mn_flags & F_SUBDATA))
2198 for (; !mc || mc == m0; mc = txn->mt_cursors[--i])
2205 /* Mark dirty root pages */
2206 for (i=0; i<txn->mt_numdbs; i++) {
2207 if (txn->mt_dbflags[i] & DB_DIRTY) {
2208 pgno_t pgno = txn->mt_dbs[i].md_root;
2209 if (pgno == P_INVALID)
2211 if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
2213 if ((dp->mp_flags & Mask) == pflags && level <= 1)
2214 dp->mp_flags ^= P_KEEP;
2222 static int mdb_page_flush(MDB_txn *txn, int keep);
2224 /** Spill pages from the dirty list back to disk.
2225 * This is intended to prevent running into #MDB_TXN_FULL situations,
2226 * but note that they may still occur in a few cases:
2227 * 1) our estimate of the txn size could be too small. Currently this
2228 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
2229 * 2) child txns may run out of space if their parents dirtied a
2230 * lot of pages and never spilled them. TODO: we probably should do
2231 * a preemptive spill during #mdb_txn_begin() of a child txn, if
2232 * the parent's dirty_room is below a given threshold.
2234 * Otherwise, if not using nested txns, it is expected that apps will
2235 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
2236 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
2237 * If the txn never references them again, they can be left alone.
2238 * If the txn only reads them, they can be used without any fuss.
2239 * If the txn writes them again, they can be dirtied immediately without
2240 * going thru all of the work of #mdb_page_touch(). Such references are
2241 * handled by #mdb_page_unspill().
2243 * Also note, we never spill DB root pages, nor pages of active cursors,
2244 * because we'll need these back again soon anyway. And in nested txns,
2245 * we can't spill a page in a child txn if it was already spilled in a
2246 * parent txn. That would alter the parent txns' data even though
2247 * the child hasn't committed yet, and we'd have no way to undo it if
2248 * the child aborted.
2250 * @param[in] m0 cursor A cursor handle identifying the transaction and
2251 * database for which we are checking space.
2252 * @param[in] key For a put operation, the key being stored.
2253 * @param[in] data For a put operation, the data being stored.
2254 * @return 0 on success, non-zero on failure.
2257 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
2259 MDB_txn *txn = m0->mc_txn;
2261 MDB_ID2L dl = txn->mt_u.dirty_list;
2262 unsigned int i, j, need;
2265 if (m0->mc_flags & C_SUB)
2268 /* Estimate how much space this op will take */
2269 i = m0->mc_db->md_depth;
2270 /* Named DBs also dirty the main DB */
2271 if (m0->mc_dbi >= CORE_DBS)
2272 i += txn->mt_dbs[MAIN_DBI].md_depth;
2273 /* For puts, roughly factor in the key+data size */
2275 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
2276 i += i; /* double it for good measure */
2279 if (txn->mt_dirty_room > i)
2282 if (!txn->mt_spill_pgs) {
2283 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
2284 if (!txn->mt_spill_pgs)
2287 /* purge deleted slots */
2288 MDB_IDL sl = txn->mt_spill_pgs;
2289 unsigned int num = sl[0];
2291 for (i=1; i<=num; i++) {
2298 /* Preserve pages which may soon be dirtied again */
2299 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2302 /* Less aggressive spill - we originally spilled the entire dirty list,
2303 * with a few exceptions for cursor pages and DB root pages. But this
2304 * turns out to be a lot of wasted effort because in a large txn many
2305 * of those pages will need to be used again. So now we spill only 1/8th
2306 * of the dirty pages. Testing revealed this to be a good tradeoff,
2307 * better than 1/2, 1/4, or 1/10.
2309 if (need < MDB_IDL_UM_MAX / 8)
2310 need = MDB_IDL_UM_MAX / 8;
2312 /* Save the page IDs of all the pages we're flushing */
2313 /* flush from the tail forward, this saves a lot of shifting later on. */
2314 for (i=dl[0].mid; i && need; i--) {
2315 MDB_ID pn = dl[i].mid << 1;
2317 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2319 /* Can't spill twice, make sure it's not already in a parent's
2322 if (txn->mt_parent) {
2324 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2325 if (tx2->mt_spill_pgs) {
2326 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2327 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2328 dp->mp_flags |= P_KEEP;
2336 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2340 mdb_midl_sort(txn->mt_spill_pgs);
2342 /* Flush the spilled part of dirty list */
2343 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2346 /* Reset any dirty pages we kept that page_flush didn't see */
2347 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2350 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2354 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2356 mdb_find_oldest(MDB_txn *txn)
2359 txnid_t mr, oldest = txn->mt_txnid - 1;
2360 if (txn->mt_env->me_txns) {
2361 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2362 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2373 /** Add a page to the txn's dirty list */
2375 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2378 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2380 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2381 insert = mdb_mid2l_append;
2383 insert = mdb_mid2l_insert;
2385 mid.mid = mp->mp_pgno;
2387 rc = insert(txn->mt_u.dirty_list, &mid);
2388 mdb_tassert(txn, rc == 0);
2389 txn->mt_dirty_room--;
2392 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2393 * me_pghead and mt_next_pgno. Set #MDB_TXN_ERROR on failure.
2395 * If there are free pages available from older transactions, they
2396 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2397 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2398 * and move me_pglast to say which records were consumed. Only this
2399 * function can create me_pghead and move me_pglast/mt_next_pgno.
2400 * When #MDB_DEVEL & 2, it is not affected by #mdb_freelist_save(): it
2401 * then uses the transaction's original snapshot of the freeDB.
2402 * @param[in] mc cursor A cursor handle identifying the transaction and
2403 * database for which we are allocating.
2404 * @param[in] num the number of pages to allocate.
2405 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2406 * will always be satisfied by a single contiguous chunk of memory.
2407 * @return 0 on success, non-zero on failure.
2410 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2412 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2413 /* Get at most <Max_retries> more freeDB records once me_pghead
2414 * has enough pages. If not enough, use new pages from the map.
2415 * If <Paranoid> and mc is updating the freeDB, only get new
2416 * records if me_pghead is empty. Then the freelist cannot play
2417 * catch-up with itself by growing while trying to save it.
2419 enum { Paranoid = 1, Max_retries = 500 };
2421 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2423 int rc, retry = num * 60;
2424 MDB_txn *txn = mc->mc_txn;
2425 MDB_env *env = txn->mt_env;
2426 pgno_t pgno, *mop = env->me_pghead;
2427 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2429 txnid_t oldest = 0, last;
2434 /* If there are any loose pages, just use them */
2435 if (num == 1 && txn->mt_loose_pgs) {
2436 np = txn->mt_loose_pgs;
2437 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2438 txn->mt_loose_count--;
2439 DPRINTF(("db %d use loose page %"Yu, DDBI(mc), np->mp_pgno));
2446 /* If our dirty list is already full, we can't do anything */
2447 if (txn->mt_dirty_room == 0) {
2452 for (op = MDB_FIRST;; op = MDB_NEXT) {
2457 /* Seek a big enough contiguous page range. Prefer
2458 * pages at the tail, just truncating the list.
2464 if (mop[i-n2] == pgno+n2)
2471 if (op == MDB_FIRST) { /* 1st iteration */
2472 /* Prepare to fetch more and coalesce */
2473 last = env->me_pglast;
2474 oldest = env->me_pgoldest;
2475 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2476 #if (MDB_DEVEL) & 2 /* "& 2" so MDB_DEVEL=1 won't hide bugs breaking freeDB */
2477 /* Use original snapshot. TODO: Should need less care in code
2478 * which modifies the database. Maybe we can delete some code?
2480 m2.mc_flags |= C_ORIG_RDONLY;
2481 m2.mc_db = &env->me_metas[(txn->mt_txnid-1) & 1]->mm_dbs[FREE_DBI];
2482 m2.mc_dbflag = (unsigned char *)""; /* probably unnecessary */
2486 key.mv_data = &last; /* will look up last+1 */
2487 key.mv_size = sizeof(last);
2489 if (Paranoid && mc->mc_dbi == FREE_DBI)
2492 if (Paranoid && retry < 0 && mop_len)
2496 /* Do not fetch more if the record will be too recent */
2497 if (oldest <= last) {
2499 oldest = mdb_find_oldest(txn);
2500 env->me_pgoldest = oldest;
2506 rc = mdb_cursor_get(&m2, &key, NULL, op);
2508 if (rc == MDB_NOTFOUND)
2512 last = *(txnid_t*)key.mv_data;
2513 if (oldest <= last) {
2515 oldest = mdb_find_oldest(txn);
2516 env->me_pgoldest = oldest;
2522 np = m2.mc_pg[m2.mc_top];
2523 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2524 if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
2527 idl = (MDB_ID *) data.mv_data;
2530 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2535 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2537 mop = env->me_pghead;
2539 env->me_pglast = last;
2541 DPRINTF(("IDL read txn %"Yu" root %"Yu" num %u",
2542 last, txn->mt_dbs[FREE_DBI].md_root, i));
2544 DPRINTF(("IDL %"Yu, idl[j]));
2546 /* Merge in descending sorted order */
2547 mdb_midl_xmerge(mop, idl);
2551 /* Use new pages from the map when nothing suitable in the freeDB */
2553 pgno = txn->mt_next_pgno;
2554 if (pgno + num >= env->me_maxpg) {
2555 DPUTS("DB size maxed out");
2559 #if defined(_WIN32) && !defined(MDB_VL32)
2560 if (!(env->me_flags & MDB_RDONLY)) {
2562 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
2563 p = VirtualAlloc(p, env->me_psize * num, MEM_COMMIT,
2564 (env->me_flags & MDB_WRITEMAP) ? PAGE_READWRITE:
2567 DPUTS("VirtualAlloc failed");
2575 if (env->me_flags & MDB_WRITEMAP) {
2576 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2578 if (!(np = mdb_page_malloc(txn, num))) {
2584 mop[0] = mop_len -= num;
2585 /* Move any stragglers down */
2586 for (j = i-num; j < mop_len; )
2587 mop[++j] = mop[++i];
2589 txn->mt_next_pgno = pgno + num;
2592 mdb_page_dirty(txn, np);
2598 txn->mt_flags |= MDB_TXN_ERROR;
2602 /** Copy the used portions of a non-overflow page.
2603 * @param[in] dst page to copy into
2604 * @param[in] src page to copy from
2605 * @param[in] psize size of a page
2608 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2610 enum { Align = sizeof(pgno_t) };
2611 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2613 /* If page isn't full, just copy the used portion. Adjust
2614 * alignment so memcpy may copy words instead of bytes.
2616 if ((unused &= -Align) && !IS_LEAF2(src)) {
2617 upper = (upper + PAGEBASE) & -Align;
2618 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2619 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2622 memcpy(dst, src, psize - unused);
2626 /** Pull a page off the txn's spill list, if present.
2627 * If a page being referenced was spilled to disk in this txn, bring
2628 * it back and make it dirty/writable again.
2629 * @param[in] txn the transaction handle.
2630 * @param[in] mp the page being referenced. It must not be dirty.
2631 * @param[out] ret the writable page, if any. ret is unchanged if
2632 * mp wasn't spilled.
2635 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2637 MDB_env *env = txn->mt_env;
2640 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2642 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2643 if (!tx2->mt_spill_pgs)
2645 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2646 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2649 if (txn->mt_dirty_room == 0)
2650 return MDB_TXN_FULL;
2651 if (IS_OVERFLOW(mp))
2655 if (env->me_flags & MDB_WRITEMAP) {
2658 np = mdb_page_malloc(txn, num);
2662 memcpy(np, mp, num * env->me_psize);
2664 mdb_page_copy(np, mp, env->me_psize);
2667 /* If in current txn, this page is no longer spilled.
2668 * If it happens to be the last page, truncate the spill list.
2669 * Otherwise mark it as deleted by setting the LSB.
2671 if (x == txn->mt_spill_pgs[0])
2672 txn->mt_spill_pgs[0]--;
2674 txn->mt_spill_pgs[x] |= 1;
2675 } /* otherwise, if belonging to a parent txn, the
2676 * page remains spilled until child commits
2679 mdb_page_dirty(txn, np);
2680 np->mp_flags |= P_DIRTY;
2688 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2689 * Set #MDB_TXN_ERROR on failure.
2690 * @param[in] mc cursor pointing to the page to be touched
2691 * @return 0 on success, non-zero on failure.
2694 mdb_page_touch(MDB_cursor *mc)
2696 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2697 MDB_txn *txn = mc->mc_txn;
2698 MDB_cursor *m2, *m3;
2702 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2703 if (txn->mt_flags & MDB_TXN_SPILLS) {
2705 rc = mdb_page_unspill(txn, mp, &np);
2711 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2712 (rc = mdb_page_alloc(mc, 1, &np)))
2715 DPRINTF(("touched db %d page %"Yu" -> %"Yu, DDBI(mc),
2716 mp->mp_pgno, pgno));
2717 mdb_cassert(mc, mp->mp_pgno != pgno);
2718 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2719 /* Update the parent page, if any, to point to the new page */
2721 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2722 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2723 SETPGNO(node, pgno);
2725 mc->mc_db->md_root = pgno;
2727 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2728 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2730 /* If txn has a parent, make sure the page is in our
2734 unsigned x = mdb_mid2l_search(dl, pgno);
2735 if (x <= dl[0].mid && dl[x].mid == pgno) {
2736 if (mp != dl[x].mptr) { /* bad cursor? */
2737 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2738 txn->mt_flags |= MDB_TXN_ERROR;
2744 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2746 np = mdb_page_malloc(txn, 1);
2751 rc = mdb_mid2l_insert(dl, &mid);
2752 mdb_cassert(mc, rc == 0);
2757 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2759 np->mp_flags |= P_DIRTY;
2762 /* Adjust cursors pointing to mp */
2763 mc->mc_pg[mc->mc_top] = np;
2764 m2 = txn->mt_cursors[mc->mc_dbi];
2765 if (mc->mc_flags & C_SUB) {
2766 for (; m2; m2=m2->mc_next) {
2767 m3 = &m2->mc_xcursor->mx_cursor;
2768 if (m3->mc_snum < mc->mc_snum) continue;
2769 if (m3->mc_pg[mc->mc_top] == mp)
2770 m3->mc_pg[mc->mc_top] = np;
2773 for (; m2; m2=m2->mc_next) {
2774 if (m2->mc_snum < mc->mc_snum) continue;
2775 if (m2 == mc) continue;
2776 if (m2->mc_pg[mc->mc_top] == mp) {
2777 m2->mc_pg[mc->mc_top] = np;
2779 XCURSOR_REFRESH(m2, mc->mc_top, np);
2783 MDB_PAGE_UNREF(mc->mc_txn, mp);
2787 txn->mt_flags |= MDB_TXN_ERROR;
2792 mdb_env_sync0(MDB_env *env, int force, pgno_t numpgs)
2795 if (env->me_flags & MDB_RDONLY)
2797 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2798 if (env->me_flags & MDB_WRITEMAP) {
2799 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2800 ? MS_ASYNC : MS_SYNC;
2801 if (MDB_MSYNC(env->me_map, env->me_psize * numpgs, flags))
2804 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2808 #ifdef BROKEN_FDATASYNC
2809 if (env->me_flags & MDB_FSYNCONLY) {
2810 if (fsync(env->me_fd))
2814 if (MDB_FDATASYNC(env->me_fd))
2822 mdb_env_sync(MDB_env *env, int force)
2824 MDB_meta *m = mdb_env_pick_meta(env);
2825 return mdb_env_sync0(env, force, m->mm_last_pg+1);
2828 /** Back up parent txn's cursors, then grab the originals for tracking */
2830 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2832 MDB_cursor *mc, *bk;
2837 for (i = src->mt_numdbs; --i >= 0; ) {
2838 if ((mc = src->mt_cursors[i]) != NULL) {
2839 size = sizeof(MDB_cursor);
2841 size += sizeof(MDB_xcursor);
2842 for (; mc; mc = bk->mc_next) {
2848 mc->mc_db = &dst->mt_dbs[i];
2849 /* Kill pointers into src to reduce abuse: The
2850 * user may not use mc until dst ends. But we need a valid
2851 * txn pointer here for cursor fixups to keep working.
2854 mc->mc_dbflag = &dst->mt_dbflags[i];
2855 if ((mx = mc->mc_xcursor) != NULL) {
2856 *(MDB_xcursor *)(bk+1) = *mx;
2857 mx->mx_cursor.mc_txn = dst;
2859 mc->mc_next = dst->mt_cursors[i];
2860 dst->mt_cursors[i] = mc;
2867 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2868 * @param[in] txn the transaction handle.
2869 * @param[in] merge true to keep changes to parent cursors, false to revert.
2870 * @return 0 on success, non-zero on failure.
2873 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2875 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2879 for (i = txn->mt_numdbs; --i >= 0; ) {
2880 for (mc = cursors[i]; mc; mc = next) {
2882 if ((bk = mc->mc_backup) != NULL) {
2884 /* Commit changes to parent txn */
2885 mc->mc_next = bk->mc_next;
2886 mc->mc_backup = bk->mc_backup;
2887 mc->mc_txn = bk->mc_txn;
2888 mc->mc_db = bk->mc_db;
2889 mc->mc_dbflag = bk->mc_dbflag;
2890 if ((mx = mc->mc_xcursor) != NULL)
2891 mx->mx_cursor.mc_txn = bk->mc_txn;
2893 /* Abort nested txn */
2895 if ((mx = mc->mc_xcursor) != NULL)
2896 *mx = *(MDB_xcursor *)(bk+1);
2900 /* Only malloced cursors are permanently tracked. */
2907 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2913 Pidset = F_SETLK, Pidcheck = F_GETLK
2917 /** Set or check a pid lock. Set returns 0 on success.
2918 * Check returns 0 if the process is certainly dead, nonzero if it may
2919 * be alive (the lock exists or an error happened so we do not know).
2921 * On Windows Pidset is a no-op, we merely check for the existence
2922 * of the process with the given pid. On POSIX we use a single byte
2923 * lock on the lockfile, set at an offset equal to the pid.
2926 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2928 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2931 if (op == Pidcheck) {
2932 h = OpenProcess(env->me_pidquery, FALSE, pid);
2933 /* No documented "no such process" code, but other program use this: */
2935 return ErrCode() != ERROR_INVALID_PARAMETER;
2936 /* A process exists until all handles to it close. Has it exited? */
2937 ret = WaitForSingleObject(h, 0) != 0;
2944 struct flock lock_info;
2945 memset(&lock_info, 0, sizeof(lock_info));
2946 lock_info.l_type = F_WRLCK;
2947 lock_info.l_whence = SEEK_SET;
2948 lock_info.l_start = pid;
2949 lock_info.l_len = 1;
2950 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2951 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2953 } else if ((rc = ErrCode()) == EINTR) {
2961 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2962 * @param[in] txn the transaction handle to initialize
2963 * @return 0 on success, non-zero on failure.
2966 mdb_txn_renew0(MDB_txn *txn)
2968 MDB_env *env = txn->mt_env;
2969 MDB_txninfo *ti = env->me_txns;
2971 unsigned int i, nr, flags = txn->mt_flags;
2973 int rc, new_notls = 0;
2975 if ((flags &= MDB_TXN_RDONLY) != 0) {
2977 meta = mdb_env_pick_meta(env);
2978 txn->mt_txnid = meta->mm_txnid;
2979 txn->mt_u.reader = NULL;
2981 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2982 pthread_getspecific(env->me_txkey);
2984 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2985 return MDB_BAD_RSLOT;
2987 MDB_PID_T pid = env->me_pid;
2988 MDB_THR_T tid = pthread_self();
2989 mdb_mutexref_t rmutex = env->me_rmutex;
2991 if (!env->me_live_reader) {
2992 rc = mdb_reader_pid(env, Pidset, pid);
2995 env->me_live_reader = 1;
2998 if (LOCK_MUTEX(rc, env, rmutex))
3000 nr = ti->mti_numreaders;
3001 for (i=0; i<nr; i++)
3002 if (ti->mti_readers[i].mr_pid == 0)
3004 if (i == env->me_maxreaders) {
3005 UNLOCK_MUTEX(rmutex);
3006 return MDB_READERS_FULL;
3008 r = &ti->mti_readers[i];
3009 /* Claim the reader slot, carefully since other code
3010 * uses the reader table un-mutexed: First reset the
3011 * slot, next publish it in mti_numreaders. After
3012 * that, it is safe for mdb_env_close() to touch it.
3013 * When it will be closed, we can finally claim it.
3016 r->mr_txnid = (txnid_t)-1;
3019 ti->mti_numreaders = ++nr;
3020 env->me_close_readers = nr;
3022 UNLOCK_MUTEX(rmutex);
3024 new_notls = (env->me_flags & MDB_NOTLS);
3025 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
3030 do /* LY: Retry on a race, ITS#7970. */
3031 r->mr_txnid = ti->mti_txnid;
3032 while(r->mr_txnid != ti->mti_txnid);
3033 txn->mt_txnid = r->mr_txnid;
3034 txn->mt_u.reader = r;
3035 meta = env->me_metas[txn->mt_txnid & 1];
3039 /* Not yet touching txn == env->me_txn0, it may be active */
3041 if (LOCK_MUTEX(rc, env, env->me_wmutex))
3043 txn->mt_txnid = ti->mti_txnid;
3044 meta = env->me_metas[txn->mt_txnid & 1];
3046 meta = mdb_env_pick_meta(env);
3047 txn->mt_txnid = meta->mm_txnid;
3051 if (txn->mt_txnid == mdb_debug_start)
3054 txn->mt_child = NULL;
3055 txn->mt_loose_pgs = NULL;
3056 txn->mt_loose_count = 0;
3057 txn->mt_dirty_room = MDB_IDL_UM_MAX;
3058 txn->mt_u.dirty_list = env->me_dirty_list;
3059 txn->mt_u.dirty_list[0].mid = 0;
3060 txn->mt_free_pgs = env->me_free_pgs;
3061 txn->mt_free_pgs[0] = 0;
3062 txn->mt_spill_pgs = NULL;
3064 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
3067 /* Copy the DB info and flags */
3068 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
3070 /* Moved to here to avoid a data race in read TXNs */
3071 txn->mt_next_pgno = meta->mm_last_pg+1;
3073 txn->mt_last_pgno = txn->mt_next_pgno - 1;
3076 txn->mt_flags = flags;
3079 txn->mt_numdbs = env->me_numdbs;
3080 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3081 x = env->me_dbflags[i];
3082 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
3083 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
3085 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
3086 txn->mt_dbflags[FREE_DBI] = DB_VALID;
3088 if (env->me_flags & MDB_FATAL_ERROR) {
3089 DPUTS("environment had fatal error, must shutdown!");
3091 } else if (env->me_maxpg < txn->mt_next_pgno) {
3092 rc = MDB_MAP_RESIZED;
3096 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
3101 mdb_txn_renew(MDB_txn *txn)
3105 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
3108 rc = mdb_txn_renew0(txn);
3109 if (rc == MDB_SUCCESS) {
3110 DPRINTF(("renew txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3111 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
3112 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
3118 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
3122 int rc, size, tsize;
3124 flags &= MDB_TXN_BEGIN_FLAGS;
3125 flags |= env->me_flags & MDB_WRITEMAP;
3127 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
3131 /* Nested transactions: Max 1 child, write txns only, no writemap */
3132 flags |= parent->mt_flags;
3133 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
3134 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
3136 /* Child txns save MDB_pgstate and use own copy of cursors */
3137 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
3138 size += tsize = sizeof(MDB_ntxn);
3139 } else if (flags & MDB_RDONLY) {
3140 size = env->me_maxdbs * (sizeof(MDB_db)+1);
3141 size += tsize = sizeof(MDB_txn);
3143 /* Reuse preallocated write txn. However, do not touch it until
3144 * mdb_txn_renew0() succeeds, since it currently may be active.
3149 if ((txn = calloc(1, size)) == NULL) {
3150 DPRINTF(("calloc: %s", strerror(errno)));
3155 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
3156 if (!txn->mt_rpages) {
3160 txn->mt_rpages[0].mid = 0;
3161 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
3164 txn->mt_dbxs = env->me_dbxs; /* static */
3165 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
3166 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
3167 txn->mt_flags = flags;
3172 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
3173 txn->mt_dbiseqs = parent->mt_dbiseqs;
3174 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
3175 if (!txn->mt_u.dirty_list ||
3176 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
3178 free(txn->mt_u.dirty_list);
3182 txn->mt_txnid = parent->mt_txnid;
3183 txn->mt_dirty_room = parent->mt_dirty_room;
3184 txn->mt_u.dirty_list[0].mid = 0;
3185 txn->mt_spill_pgs = NULL;
3186 txn->mt_next_pgno = parent->mt_next_pgno;
3187 parent->mt_flags |= MDB_TXN_HAS_CHILD;
3188 parent->mt_child = txn;
3189 txn->mt_parent = parent;
3190 txn->mt_numdbs = parent->mt_numdbs;
3192 txn->mt_rpages = parent->mt_rpages;
3194 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3195 /* Copy parent's mt_dbflags, but clear DB_NEW */
3196 for (i=0; i<txn->mt_numdbs; i++)
3197 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
3199 ntxn = (MDB_ntxn *)txn;
3200 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
3201 if (env->me_pghead) {
3202 size = MDB_IDL_SIZEOF(env->me_pghead);
3203 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
3205 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
3210 rc = mdb_cursor_shadow(parent, txn);
3212 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
3213 } else { /* MDB_RDONLY */
3214 txn->mt_dbiseqs = env->me_dbiseqs;
3216 rc = mdb_txn_renew0(txn);
3219 if (txn != env->me_txn0) {
3221 free(txn->mt_rpages);
3226 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
3228 DPRINTF(("begin txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3229 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
3230 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
3237 mdb_txn_env(MDB_txn *txn)
3239 if(!txn) return NULL;
3244 mdb_txn_id(MDB_txn *txn)
3247 return txn->mt_txnid;
3250 /** Export or close DBI handles opened in this txn. */
3252 mdb_dbis_update(MDB_txn *txn, int keep)
3255 MDB_dbi n = txn->mt_numdbs;
3256 MDB_env *env = txn->mt_env;
3257 unsigned char *tdbflags = txn->mt_dbflags;
3259 for (i = n; --i >= CORE_DBS;) {
3260 if (tdbflags[i] & DB_NEW) {
3262 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
3264 char *ptr = env->me_dbxs[i].md_name.mv_data;
3266 env->me_dbxs[i].md_name.mv_data = NULL;
3267 env->me_dbxs[i].md_name.mv_size = 0;
3268 env->me_dbflags[i] = 0;
3269 env->me_dbiseqs[i]++;
3275 if (keep && env->me_numdbs < n)
3279 /** End a transaction, except successful commit of a nested transaction.
3280 * May be called twice for readonly txns: First reset it, then abort.
3281 * @param[in] txn the transaction handle to end
3282 * @param[in] mode why and how to end the transaction
3285 mdb_txn_end(MDB_txn *txn, unsigned mode)
3287 MDB_env *env = txn->mt_env;
3289 static const char *const names[] = MDB_END_NAMES;
3292 /* Export or close DBI handles opened in this txn */
3293 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
3295 DPRINTF(("%s txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3296 names[mode & MDB_END_OPMASK],
3297 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
3298 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
3300 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3301 if (txn->mt_u.reader) {
3302 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
3303 if (!(env->me_flags & MDB_NOTLS)) {
3304 txn->mt_u.reader = NULL; /* txn does not own reader */
3305 } else if (mode & MDB_END_SLOT) {
3306 txn->mt_u.reader->mr_pid = 0;
3307 txn->mt_u.reader = NULL;
3308 } /* else txn owns the slot until it does MDB_END_SLOT */
3310 txn->mt_numdbs = 0; /* prevent further DBI activity */
3311 txn->mt_flags |= MDB_TXN_FINISHED;
3313 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
3314 pgno_t *pghead = env->me_pghead;
3316 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
3317 mdb_cursors_close(txn, 0);
3318 if (!(env->me_flags & MDB_WRITEMAP)) {
3319 mdb_dlist_free(txn);
3323 txn->mt_flags = MDB_TXN_FINISHED;
3325 if (!txn->mt_parent) {
3326 mdb_midl_shrink(&txn->mt_free_pgs);
3327 env->me_free_pgs = txn->mt_free_pgs;
3329 env->me_pghead = NULL;
3333 mode = 0; /* txn == env->me_txn0, do not free() it */
3335 /* The writer mutex was locked in mdb_txn_begin. */
3337 UNLOCK_MUTEX(env->me_wmutex);
3339 txn->mt_parent->mt_child = NULL;
3340 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
3341 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
3342 mdb_midl_free(txn->mt_free_pgs);
3343 mdb_midl_free(txn->mt_spill_pgs);
3344 free(txn->mt_u.dirty_list);
3347 mdb_midl_free(pghead);
3350 if (!txn->mt_parent) {
3351 MDB_ID3L el = env->me_rpages, tl = txn->mt_rpages;
3352 unsigned i, x, n = tl[0].mid;
3353 pthread_mutex_lock(&env->me_rpmutex);
3354 for (i = 1; i <= n; i++) {
3355 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
3356 /* tmp overflow pages that we didn't share in env */
3357 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3359 x = mdb_mid3l_search(el, tl[i].mid);
3360 if (tl[i].mptr == el[x].mptr) {
3363 /* another tmp overflow page */
3364 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3368 pthread_mutex_unlock(&env->me_rpmutex);
3370 if (mode & MDB_END_FREE)
3374 if (mode & MDB_END_FREE)
3379 mdb_txn_reset(MDB_txn *txn)
3384 /* This call is only valid for read-only txns */
3385 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3388 mdb_txn_end(txn, MDB_END_RESET);
3392 mdb_txn_abort(MDB_txn *txn)
3398 mdb_txn_abort(txn->mt_child);
3400 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3403 /** Save the freelist as of this transaction to the freeDB.
3404 * This changes the freelist. Keep trying until it stabilizes.
3406 * When (MDB_DEVEL) & 2, the changes do not affect #mdb_page_alloc(),
3407 * it then uses the transaction's original snapshot of the freeDB.
3410 mdb_freelist_save(MDB_txn *txn)
3412 /* env->me_pghead[] can grow and shrink during this call.
3413 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3414 * Page numbers cannot disappear from txn->mt_free_pgs[].
3417 MDB_env *env = txn->mt_env;
3418 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3419 txnid_t pglast = 0, head_id = 0;
3420 pgno_t freecnt = 0, *free_pgs, *mop;
3421 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3423 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3425 if (env->me_pghead) {
3426 /* Make sure first page of freeDB is touched and on freelist */
3427 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3428 if (rc && rc != MDB_NOTFOUND)
3432 if (!env->me_pghead && txn->mt_loose_pgs) {
3433 /* Put loose page numbers in mt_free_pgs, since
3434 * we may be unable to return them to me_pghead.
3436 MDB_page *mp = txn->mt_loose_pgs;
3437 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3439 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3440 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3441 txn->mt_loose_pgs = NULL;
3442 txn->mt_loose_count = 0;
3445 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3446 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3447 ? SSIZE_MAX : maxfree_1pg;
3450 /* Come back here after each Put() in case freelist changed */
3455 /* If using records from freeDB which we have not yet
3456 * deleted, delete them and any we reserved for me_pghead.
3458 while (pglast < env->me_pglast) {
3459 rc = mdb_cursor_first(&mc, &key, NULL);
3462 pglast = head_id = *(txnid_t *)key.mv_data;
3463 total_room = head_room = 0;
3464 mdb_tassert(txn, pglast <= env->me_pglast);
3465 rc = mdb_cursor_del(&mc, 0);
3470 /* Save the IDL of pages freed by this txn, to a single record */
3471 if (freecnt < txn->mt_free_pgs[0]) {
3473 /* Make sure last page of freeDB is touched and on freelist */
3474 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3475 if (rc && rc != MDB_NOTFOUND)
3478 free_pgs = txn->mt_free_pgs;
3479 /* Write to last page of freeDB */
3480 key.mv_size = sizeof(txn->mt_txnid);
3481 key.mv_data = &txn->mt_txnid;
3483 freecnt = free_pgs[0];
3484 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3485 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3488 /* Retry if mt_free_pgs[] grew during the Put() */
3489 free_pgs = txn->mt_free_pgs;
3490 } while (freecnt < free_pgs[0]);
3491 mdb_midl_sort(free_pgs);
3492 memcpy(data.mv_data, free_pgs, data.mv_size);
3495 unsigned int i = free_pgs[0];
3496 DPRINTF(("IDL write txn %"Yu" root %"Yu" num %u",
3497 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3499 DPRINTF(("IDL %"Yu, free_pgs[i]));
3505 mop = env->me_pghead;
3506 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3508 /* Reserve records for me_pghead[]. Split it if multi-page,
3509 * to avoid searching freeDB for a page range. Use keys in
3510 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3512 if (total_room >= mop_len) {
3513 if (total_room == mop_len || --more < 0)
3515 } else if (head_room >= maxfree_1pg && head_id > 1) {
3516 /* Keep current record (overflow page), add a new one */
3520 /* (Re)write {key = head_id, IDL length = head_room} */
3521 total_room -= head_room;
3522 head_room = mop_len - total_room;
3523 if (head_room > maxfree_1pg && head_id > 1) {
3524 /* Overflow multi-page for part of me_pghead */
3525 head_room /= head_id; /* amortize page sizes */
3526 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3527 } else if (head_room < 0) {
3528 /* Rare case, not bothering to delete this record */
3531 key.mv_size = sizeof(head_id);
3532 key.mv_data = &head_id;
3533 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3534 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3537 /* IDL is initially empty, zero out at least the length */
3538 pgs = (pgno_t *)data.mv_data;
3539 j = head_room > clean_limit ? head_room : 0;
3543 total_room += head_room;
3546 /* Return loose page numbers to me_pghead, though usually none are
3547 * left at this point. The pages themselves remain in dirty_list.
3549 if (txn->mt_loose_pgs) {
3550 MDB_page *mp = txn->mt_loose_pgs;
3551 unsigned count = txn->mt_loose_count;
3553 /* Room for loose pages + temp IDL with same */
3554 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3556 mop = env->me_pghead;
3557 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3558 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3559 loose[ ++count ] = mp->mp_pgno;
3561 mdb_midl_sort(loose);
3562 mdb_midl_xmerge(mop, loose);
3563 txn->mt_loose_pgs = NULL;
3564 txn->mt_loose_count = 0;
3568 /* Fill in the reserved me_pghead records */
3574 rc = mdb_cursor_first(&mc, &key, &data);
3575 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3576 txnid_t id = *(txnid_t *)key.mv_data;
3577 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3580 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3582 if (len > mop_len) {
3584 data.mv_size = (len + 1) * sizeof(MDB_ID);
3586 data.mv_data = mop -= len;
3589 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3591 if (rc || !(mop_len -= len))
3598 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3599 * @param[in] txn the transaction that's being committed
3600 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3601 * @return 0 on success, non-zero on failure.
3604 mdb_page_flush(MDB_txn *txn, int keep)
3606 MDB_env *env = txn->mt_env;
3607 MDB_ID2L dl = txn->mt_u.dirty_list;
3608 unsigned psize = env->me_psize, j;
3609 int i, pagecount = dl[0].mid, rc;
3613 MDB_page *dp = NULL;
3617 struct iovec iov[MDB_COMMIT_PAGES];
3618 ssize_t wsize = 0, wres;
3619 off_t wpos = 0, next_pos = 1; /* impossible pos, so pos != next_pos */
3625 if (env->me_flags & MDB_WRITEMAP) {
3626 /* Clear dirty flags */
3627 while (++i <= pagecount) {
3629 /* Don't flush this page yet */
3630 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3631 dp->mp_flags &= ~P_KEEP;
3635 dp->mp_flags &= ~P_DIRTY;
3640 /* Write the pages */
3642 if (++i <= pagecount) {
3644 /* Don't flush this page yet */
3645 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3646 dp->mp_flags &= ~P_KEEP;
3651 /* clear dirty flag */
3652 dp->mp_flags &= ~P_DIRTY;
3655 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3660 /* Windows actually supports scatter/gather I/O, but only on
3661 * unbuffered file handles. Since we're relying on the OS page
3662 * cache for all our data, that's self-defeating. So we just
3663 * write pages one at a time. We use the ov structure to set
3664 * the write offset, to at least save the overhead of a Seek
3667 DPRINTF(("committing page %"Yu, pgno));
3668 memset(&ov, 0, sizeof(ov));
3669 ov.Offset = pos & 0xffffffff;
3670 ov.OffsetHigh = pos >> 16 >> 16;
3671 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3673 DPRINTF(("WriteFile: %d", rc));
3677 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3678 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3681 /* Write previous page(s) */
3682 #ifdef MDB_USE_PWRITEV
3683 wres = pwritev(env->me_fd, iov, n, wpos);
3686 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3689 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3693 DPRINTF(("lseek: %s", strerror(rc)));
3696 wres = writev(env->me_fd, iov, n);
3699 if (wres != wsize) {
3704 DPRINTF(("Write error: %s", strerror(rc)));
3706 rc = EIO; /* TODO: Use which error code? */
3707 DPUTS("short write, filesystem full?");
3718 DPRINTF(("committing page %"Yu, pgno));
3719 next_pos = pos + size;
3720 iov[n].iov_len = size;
3721 iov[n].iov_base = (char *)dp;
3727 if (pgno > txn->mt_last_pgno)
3728 txn->mt_last_pgno = pgno;
3731 /* MIPS has cache coherency issues, this is a no-op everywhere else
3732 * Note: for any size >= on-chip cache size, entire on-chip cache is
3735 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3737 for (i = keep; ++i <= pagecount; ) {
3739 /* This is a page we skipped above */
3742 dl[j].mid = dp->mp_pgno;
3745 mdb_dpage_free(env, dp);
3750 txn->mt_dirty_room += i - j;
3756 mdb_txn_commit(MDB_txn *txn)
3759 unsigned int i, end_mode;
3765 /* mdb_txn_end() mode for a commit which writes nothing */
3766 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3768 if (txn->mt_child) {
3769 rc = mdb_txn_commit(txn->mt_child);
3776 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3780 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3781 DPUTS("txn has failed/finished, can't commit");
3783 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3788 if (txn->mt_parent) {
3789 MDB_txn *parent = txn->mt_parent;
3793 unsigned x, y, len, ps_len;
3795 /* Append our free list to parent's */
3796 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3799 mdb_midl_free(txn->mt_free_pgs);
3800 /* Failures after this must either undo the changes
3801 * to the parent or set MDB_TXN_ERROR in the parent.
3804 parent->mt_next_pgno = txn->mt_next_pgno;
3805 parent->mt_flags = txn->mt_flags;
3807 /* Merge our cursors into parent's and close them */
3808 mdb_cursors_close(txn, 1);
3810 /* Update parent's DB table. */
3811 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3812 parent->mt_numdbs = txn->mt_numdbs;
3813 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3814 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3815 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3816 /* preserve parent's DB_NEW status */
3817 x = parent->mt_dbflags[i] & DB_NEW;
3818 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3821 dst = parent->mt_u.dirty_list;
3822 src = txn->mt_u.dirty_list;
3823 /* Remove anything in our dirty list from parent's spill list */
3824 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3826 pspill[0] = (pgno_t)-1;
3827 /* Mark our dirty pages as deleted in parent spill list */
3828 for (i=0, len=src[0].mid; ++i <= len; ) {
3829 MDB_ID pn = src[i].mid << 1;
3830 while (pn > pspill[x])
3832 if (pn == pspill[x]) {
3837 /* Squash deleted pagenums if we deleted any */
3838 for (x=y; ++x <= ps_len; )
3839 if (!(pspill[x] & 1))
3840 pspill[++y] = pspill[x];
3844 /* Remove anything in our spill list from parent's dirty list */
3845 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3846 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3847 MDB_ID pn = txn->mt_spill_pgs[i];
3849 continue; /* deleted spillpg */
3851 y = mdb_mid2l_search(dst, pn);
3852 if (y <= dst[0].mid && dst[y].mid == pn) {
3854 while (y < dst[0].mid) {
3863 /* Find len = length of merging our dirty list with parent's */
3865 dst[0].mid = 0; /* simplify loops */
3866 if (parent->mt_parent) {
3867 len = x + src[0].mid;
3868 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3869 for (i = x; y && i; y--) {
3870 pgno_t yp = src[y].mid;
3871 while (yp < dst[i].mid)
3873 if (yp == dst[i].mid) {
3878 } else { /* Simplify the above for single-ancestor case */
3879 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3881 /* Merge our dirty list with parent's */
3883 for (i = len; y; dst[i--] = src[y--]) {
3884 pgno_t yp = src[y].mid;
3885 while (yp < dst[x].mid)
3886 dst[i--] = dst[x--];
3887 if (yp == dst[x].mid)
3888 free(dst[x--].mptr);
3890 mdb_tassert(txn, i == x);
3892 free(txn->mt_u.dirty_list);
3893 parent->mt_dirty_room = txn->mt_dirty_room;
3894 if (txn->mt_spill_pgs) {
3895 if (parent->mt_spill_pgs) {
3896 /* TODO: Prevent failure here, so parent does not fail */
3897 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3899 parent->mt_flags |= MDB_TXN_ERROR;
3900 mdb_midl_free(txn->mt_spill_pgs);
3901 mdb_midl_sort(parent->mt_spill_pgs);
3903 parent->mt_spill_pgs = txn->mt_spill_pgs;
3907 /* Append our loose page list to parent's */
3908 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3910 *lp = txn->mt_loose_pgs;
3911 parent->mt_loose_count += txn->mt_loose_count;
3913 parent->mt_child = NULL;
3914 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3919 if (txn != env->me_txn) {
3920 DPUTS("attempt to commit unknown transaction");
3925 mdb_cursors_close(txn, 0);
3927 if (!txn->mt_u.dirty_list[0].mid &&
3928 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3931 DPRINTF(("committing txn %"Yu" %p on mdbenv %p, root page %"Yu,
3932 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3934 /* Update DB root pointers */
3935 if (txn->mt_numdbs > CORE_DBS) {
3939 data.mv_size = sizeof(MDB_db);
3941 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3942 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3943 if (txn->mt_dbflags[i] & DB_DIRTY) {
3944 if (TXN_DBI_CHANGED(txn, i)) {
3948 data.mv_data = &txn->mt_dbs[i];
3949 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3957 rc = mdb_freelist_save(txn);
3961 mdb_midl_free(env->me_pghead);
3962 env->me_pghead = NULL;
3963 mdb_midl_shrink(&txn->mt_free_pgs);
3969 if ((rc = mdb_page_flush(txn, 0)))
3971 if (!F_ISSET(txn->mt_flags, MDB_TXN_NOSYNC) &&
3972 (rc = mdb_env_sync0(env, 0, txn->mt_next_pgno)))
3974 if ((rc = mdb_env_write_meta(txn)))
3976 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3979 mdb_txn_end(txn, end_mode);
3987 /** Read the environment parameters of a DB environment before
3988 * mapping it into memory.
3989 * @param[in] env the environment handle
3990 * @param[in] prev whether to read the backup meta page
3991 * @param[out] meta address of where to store the meta information
3992 * @return 0 on success, non-zero on failure.
3995 mdb_env_read_header(MDB_env *env, int prev, MDB_meta *meta)
4001 enum { Size = sizeof(pbuf) };
4003 /* We don't know the page size yet, so use a minimum value.
4004 * Read both meta pages so we can use the latest one.
4007 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
4011 memset(&ov, 0, sizeof(ov));
4013 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
4014 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
4017 rc = pread(env->me_fd, &pbuf, Size, off);
4020 if (rc == 0 && off == 0)
4022 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
4023 DPRINTF(("read: %s", mdb_strerror(rc)));
4027 p = (MDB_page *)&pbuf;
4029 if (!F_ISSET(p->mp_flags, P_META)) {
4030 DPRINTF(("page %"Yu" not a meta page", p->mp_pgno));
4035 if (m->mm_magic != MDB_MAGIC) {
4036 DPUTS("meta has invalid magic");
4040 if (m->mm_version != MDB_DATA_VERSION) {
4041 DPRINTF(("database is version %u, expected version %u",
4042 m->mm_version, MDB_DATA_VERSION));
4043 return MDB_VERSION_MISMATCH;
4046 if (off == 0 || (prev ? m->mm_txnid < meta->mm_txnid : m->mm_txnid > meta->mm_txnid))
4052 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
4054 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
4056 meta->mm_magic = MDB_MAGIC;
4057 meta->mm_version = MDB_DATA_VERSION;
4058 meta->mm_mapsize = env->me_mapsize;
4059 meta->mm_psize = env->me_psize;
4060 meta->mm_last_pg = NUM_METAS-1;
4061 meta->mm_flags = env->me_flags & 0xffff;
4062 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
4063 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
4064 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
4067 /** Write the environment parameters of a freshly created DB environment.
4068 * @param[in] env the environment handle
4069 * @param[in] meta the #MDB_meta to write
4070 * @return 0 on success, non-zero on failure.
4073 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
4081 memset(&ov, 0, sizeof(ov));
4082 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
4084 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
4087 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
4088 len = pwrite(fd, ptr, size, pos); \
4089 if (len == -1 && ErrCode() == EINTR) continue; \
4090 rc = (len >= 0); break; } while(1)
4093 DPUTS("writing new meta page");
4095 psize = env->me_psize;
4097 p = calloc(NUM_METAS, psize);
4101 p->mp_flags = P_META;
4102 *(MDB_meta *)METADATA(p) = *meta;
4104 q = (MDB_page *)((char *)p + psize);
4106 q->mp_flags = P_META;
4107 *(MDB_meta *)METADATA(q) = *meta;
4109 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
4112 else if ((unsigned) len == psize * NUM_METAS)
4120 /** Update the environment info to commit a transaction.
4121 * @param[in] txn the transaction that's being committed
4122 * @return 0 on success, non-zero on failure.
4125 mdb_env_write_meta(MDB_txn *txn)
4128 MDB_meta meta, metab, *mp;
4132 int rc, len, toggle;
4141 toggle = txn->mt_txnid & 1;
4142 DPRINTF(("writing meta page %d for root page %"Yu,
4143 toggle, txn->mt_dbs[MAIN_DBI].md_root));
4146 flags = txn->mt_flags | env->me_flags;
4147 mp = env->me_metas[toggle];
4148 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
4149 /* Persist any increases of mapsize config */
4150 if (mapsize < env->me_mapsize)
4151 mapsize = env->me_mapsize;
4153 if (flags & MDB_WRITEMAP) {
4154 mp->mm_mapsize = mapsize;
4155 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4156 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4157 mp->mm_last_pg = txn->mt_next_pgno - 1;
4158 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
4159 !(defined(__i386__) || defined(__x86_64__))
4160 /* LY: issue a memory barrier, if not x86. ITS#7969 */
4161 __sync_synchronize();
4163 mp->mm_txnid = txn->mt_txnid;
4164 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
4165 unsigned meta_size = env->me_psize;
4166 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
4167 ptr = (char *)mp - PAGEHDRSZ;
4168 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
4169 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
4173 if (MDB_MSYNC(ptr, meta_size, rc)) {
4180 metab.mm_txnid = mp->mm_txnid;
4181 metab.mm_last_pg = mp->mm_last_pg;
4183 meta.mm_mapsize = mapsize;
4184 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4185 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4186 meta.mm_last_pg = txn->mt_next_pgno - 1;
4187 meta.mm_txnid = txn->mt_txnid;
4189 off = offsetof(MDB_meta, mm_mapsize);
4190 ptr = (char *)&meta + off;
4191 len = sizeof(MDB_meta) - off;
4192 off += (char *)mp - env->me_map;
4194 /* Write to the SYNC fd unless MDB_NOSYNC/MDB_NOMETASYNC.
4195 * (me_mfd goes to the same file as me_fd, but writing to it
4196 * also syncs to disk. Avoids a separate fdatasync() call.)
4198 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
4201 memset(&ov, 0, sizeof(ov));
4203 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
4208 rc = pwrite(mfd, ptr, len, off);
4211 rc = rc < 0 ? ErrCode() : EIO;
4216 DPUTS("write failed, disk error?");
4217 /* On a failure, the pagecache still contains the new data.
4218 * Write some old data back, to prevent it from being used.
4219 * Use the non-SYNC fd; we know it will fail anyway.
4221 meta.mm_last_pg = metab.mm_last_pg;
4222 meta.mm_txnid = metab.mm_txnid;
4224 memset(&ov, 0, sizeof(ov));
4226 WriteFile(env->me_fd, ptr, len, NULL, &ov);
4228 r2 = pwrite(env->me_fd, ptr, len, off);
4229 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
4232 env->me_flags |= MDB_FATAL_ERROR;
4235 /* MIPS has cache coherency issues, this is a no-op everywhere else */
4236 CACHEFLUSH(env->me_map + off, len, DCACHE);
4238 /* Memory ordering issues are irrelevant; since the entire writer
4239 * is wrapped by wmutex, all of these changes will become visible
4240 * after the wmutex is unlocked. Since the DB is multi-version,
4241 * readers will get consistent data regardless of how fresh or
4242 * how stale their view of these values is.
4245 env->me_txns->mti_txnid = txn->mt_txnid;
4250 /** Check both meta pages to see which one is newer.
4251 * @param[in] env the environment handle
4252 * @return newest #MDB_meta.
4255 mdb_env_pick_meta(const MDB_env *env)
4257 MDB_meta *const *metas = env->me_metas;
4258 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
4262 mdb_env_create(MDB_env **env)
4266 e = calloc(1, sizeof(MDB_env));
4270 e->me_maxreaders = DEFAULT_READERS;
4271 e->me_maxdbs = e->me_numdbs = CORE_DBS;
4272 e->me_fd = INVALID_HANDLE_VALUE;
4273 e->me_lfd = INVALID_HANDLE_VALUE;
4274 e->me_mfd = INVALID_HANDLE_VALUE;
4275 #ifdef MDB_USE_POSIX_SEM
4276 e->me_rmutex = SEM_FAILED;
4277 e->me_wmutex = SEM_FAILED;
4278 #elif defined MDB_USE_SYSV_SEM
4279 e->me_rmutex->semid = -1;
4280 e->me_wmutex->semid = -1;
4282 e->me_pid = getpid();
4283 GET_PAGESIZE(e->me_os_psize);
4284 VGMEMP_CREATE(e,0,0);
4290 /** @brief Map a result from an NTAPI call to WIN32. */
4292 mdb_nt2win32(NTSTATUS st)
4297 GetOverlappedResult(NULL, &o, &br, FALSE);
4298 return GetLastError();
4303 mdb_env_map(MDB_env *env, void *addr)
4306 unsigned int flags = env->me_flags;
4309 int access = SECTION_MAP_READ;
4313 ULONG pageprot = PAGE_READONLY, secprot, alloctype;
4315 if (flags & MDB_WRITEMAP) {
4316 access |= SECTION_MAP_WRITE;
4317 pageprot = PAGE_READWRITE;
4319 if (flags & MDB_RDONLY) {
4320 secprot = PAGE_READONLY;
4324 secprot = PAGE_READWRITE;
4325 msize = env->me_mapsize;
4326 alloctype = MEM_RESERVE;
4329 rc = NtCreateSection(&mh, access, NULL, NULL, secprot, SEC_RESERVE, env->me_fd);
4331 return mdb_nt2win32(rc);
4334 msize = NUM_METAS * env->me_psize;
4336 rc = NtMapViewOfSection(mh, GetCurrentProcess(), &map, 0, 0, NULL, &msize, ViewUnmap, alloctype, pageprot);
4343 return mdb_nt2win32(rc);
4348 env->me_map = mmap(addr, NUM_METAS * env->me_psize, PROT_READ, MAP_SHARED,
4350 if (env->me_map == MAP_FAILED) {
4355 int prot = PROT_READ;
4356 if (flags & MDB_WRITEMAP) {
4358 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
4361 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
4363 if (env->me_map == MAP_FAILED) {
4368 if (flags & MDB_NORDAHEAD) {
4369 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
4371 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
4373 #ifdef POSIX_MADV_RANDOM
4374 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
4375 #endif /* POSIX_MADV_RANDOM */
4376 #endif /* MADV_RANDOM */
4380 /* Can happen because the address argument to mmap() is just a
4381 * hint. mmap() can pick another, e.g. if the range is in use.
4382 * The MAP_FIXED flag would prevent that, but then mmap could
4383 * instead unmap existing pages to make room for the new map.
4385 if (addr && env->me_map != addr)
4386 return EBUSY; /* TODO: Make a new MDB_* error code? */
4389 p = (MDB_page *)env->me_map;
4390 env->me_metas[0] = METADATA(p);
4391 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
4397 mdb_env_set_mapsize(MDB_env *env, mdb_size_t size)
4399 /* If env is already open, caller is responsible for making
4400 * sure there are no active txns.
4410 meta = mdb_env_pick_meta(env);
4412 size = meta->mm_mapsize;
4414 /* Silently round up to minimum if the size is too small */
4415 mdb_size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
4420 /* For MDB_VL32 this bit is a noop since we dynamically remap
4421 * chunks of the DB anyway.
4423 munmap(env->me_map, env->me_mapsize);
4424 env->me_mapsize = size;
4425 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4426 rc = mdb_env_map(env, old);
4429 #endif /* !MDB_VL32 */
4431 env->me_mapsize = size;
4433 env->me_maxpg = env->me_mapsize / env->me_psize;
4438 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4442 env->me_maxdbs = dbs + CORE_DBS;
4447 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4449 if (env->me_map || readers < 1)
4451 env->me_maxreaders = readers;
4456 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4458 if (!env || !readers)
4460 *readers = env->me_maxreaders;
4465 mdb_fsize(HANDLE fd, mdb_size_t *size)
4468 LARGE_INTEGER fsize;
4470 if (!GetFileSizeEx(fd, &fsize))
4473 *size = fsize.QuadPart;
4487 typedef wchar_t mdb_nchar_t;
4488 # define MDB_NAME(str) L##str
4489 # define mdb_name_cpy wcscpy
4491 /** Character type for file names: char on Unix, wchar_t on Windows */
4492 typedef char mdb_nchar_t;
4493 # define MDB_NAME(str) str /**< #mdb_nchar_t[] string literal */
4494 # define mdb_name_cpy strcpy /**< Copy name (#mdb_nchar_t string) */
4497 /** Filename - string of #mdb_nchar_t[] */
4498 typedef struct MDB_name {
4499 int mn_len; /**< Length */
4500 int mn_alloced; /**< True if #mn_val was malloced */
4501 mdb_nchar_t *mn_val; /**< Contents */
4504 /** Filename suffixes [datafile,lockfile][without,with MDB_NOSUBDIR] */
4505 static const mdb_nchar_t *const mdb_suffixes[2][2] = {
4506 { MDB_NAME("/data.mdb"), MDB_NAME("") },
4507 { MDB_NAME("/lock.mdb"), MDB_NAME("-lock") }
4510 #define MDB_SUFFLEN 9 /**< Max string length in #mdb_suffixes[] */
4512 /** Set up filename + scratch area for filename suffix, for opening files.
4513 * It should be freed with #mdb_fname_destroy().
4514 * On Windows, paths are converted from char *UTF-8 to wchar_t *UTF-16.
4516 * @param[in] path Pathname for #mdb_env_open().
4517 * @param[in] envflags Whether a subdir and/or lockfile will be used.
4518 * @param[out] fname Resulting filename, with room for a suffix if necessary.
4521 mdb_fname_init(const char *path, unsigned envflags, MDB_name *fname)
4523 int no_suffix = F_ISSET(envflags, MDB_NOSUBDIR|MDB_NOLOCK);
4524 fname->mn_alloced = 0;
4526 return utf8_to_utf16(path, fname, no_suffix ? 0 : MDB_SUFFLEN);
4528 fname->mn_len = strlen(path);
4530 fname->mn_val = (char *) path;
4531 else if ((fname->mn_val = malloc(fname->mn_len + MDB_SUFFLEN+1)) != NULL) {
4532 fname->mn_alloced = 1;
4533 strcpy(fname->mn_val, path);
4541 /** Destroy \b fname from #mdb_fname_init() */
4542 #define mdb_fname_destroy(fname) \
4543 do { if ((fname).mn_alloced) free((fname).mn_val); } while (0)
4545 #ifdef O_CLOEXEC /* POSIX.1-2008: Set FD_CLOEXEC atomically at open() */
4546 # define MDB_CLOEXEC O_CLOEXEC
4548 # define MDB_CLOEXEC 0
4551 /** File type, access mode etc. for #mdb_fopen() */
4552 enum mdb_fopen_type {
4554 MDB_O_RDONLY, MDB_O_RDWR, MDB_O_META, MDB_O_COPY, MDB_O_LOCKS
4556 /* A comment in mdb_fopen() explains some O_* flag choices. */
4557 MDB_O_RDONLY= O_RDONLY, /**< for RDONLY me_fd */
4558 MDB_O_RDWR = O_RDWR |O_CREAT, /**< for me_fd */
4559 MDB_O_META = O_WRONLY|MDB_DSYNC |MDB_CLOEXEC, /**< for me_mfd */
4560 MDB_O_COPY = O_WRONLY|O_CREAT|O_EXCL|MDB_CLOEXEC, /**< for #mdb_env_copy() */
4561 /** Bitmask for open() flags in enum #mdb_fopen_type. The other bits
4562 * distinguish otherwise-equal MDB_O_* constants from each other.
4564 MDB_O_MASK = MDB_O_RDWR|MDB_CLOEXEC | MDB_O_RDONLY|MDB_O_META|MDB_O_COPY,
4565 MDB_O_LOCKS = MDB_O_RDWR|MDB_CLOEXEC | ((MDB_O_MASK+1) & ~MDB_O_MASK) /**< for me_lfd */
4569 /** Open an LMDB file.
4570 * @param[in] env The LMDB environment.
4571 * @param[in,out] fname Path from from #mdb_fname_init(). A suffix is
4572 * appended if necessary to create the filename, without changing mn_len.
4573 * @param[in] which Determines file type, access mode, etc.
4574 * @param[in] mode The Unix permissions for the file, if we create it.
4575 * @param[out] res Resulting file handle.
4576 * @return 0 on success, non-zero on failure.
4579 mdb_fopen(const MDB_env *env, MDB_name *fname,
4580 enum mdb_fopen_type which, mdb_mode_t mode,
4583 int rc = MDB_SUCCESS;
4586 DWORD acc, share, disp, attrs;
4591 if (fname->mn_alloced) /* modifiable copy */
4592 mdb_name_cpy(fname->mn_val + fname->mn_len,
4593 mdb_suffixes[which==MDB_O_LOCKS][F_ISSET(env->me_flags, MDB_NOSUBDIR)]);
4595 /* The directory must already exist. Usually the file need not.
4596 * MDB_O_META requires the file because we already created it using
4597 * MDB_O_RDWR. MDB_O_COPY must not overwrite an existing file.
4599 * With MDB_O_COPY we do not want the OS to cache the writes, since
4600 * the source data is already in the OS cache.
4602 * The lockfile needs FD_CLOEXEC (close file descriptor on exec*())
4603 * to avoid the flock() issues noted under Caveats in lmdb.h.
4604 * Also set it for other filehandles which the user cannot get at
4605 * and close himself, which he may need after fork(). I.e. all but
4606 * me_fd, which programs do use via mdb_env_get_fd().
4610 acc = GENERIC_READ|GENERIC_WRITE;
4611 share = FILE_SHARE_READ|FILE_SHARE_WRITE;
4613 attrs = FILE_ATTRIBUTE_NORMAL;
4615 case MDB_O_RDONLY: /* read-only datafile */
4617 disp = OPEN_EXISTING;
4619 case MDB_O_META: /* for writing metapages */
4620 acc = GENERIC_WRITE;
4621 disp = OPEN_EXISTING;
4622 attrs = FILE_ATTRIBUTE_NORMAL|FILE_FLAG_WRITE_THROUGH;
4624 case MDB_O_COPY: /* mdb_env_copy() & co */
4625 acc = GENERIC_WRITE;
4628 attrs = FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH;
4630 default: break; /* silence gcc -Wswitch (not all enum values handled) */
4632 fd = CreateFileW(fname->mn_val, acc, share, NULL, disp, attrs, NULL);
4634 fd = open(fname->mn_val, which & MDB_O_MASK, mode);
4637 if (fd == INVALID_HANDLE_VALUE)
4641 if (which != MDB_O_RDONLY && which != MDB_O_RDWR) {
4642 /* Set CLOEXEC if we could not pass it to open() */
4643 if (!MDB_CLOEXEC && (flags = fcntl(fd, F_GETFD)) != -1)
4644 (void) fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
4646 if (which == MDB_O_COPY && env->me_psize >= env->me_os_psize) {
4647 /* This may require buffer alignment. There is no portable
4648 * way to ask how much, so we require OS pagesize alignment.
4650 # ifdef F_NOCACHE /* __APPLE__ */
4651 (void) fcntl(fd, F_NOCACHE, 1);
4652 # elif defined O_DIRECT
4653 /* open(...O_DIRECT...) would break on filesystems without
4654 * O_DIRECT support (ITS#7682). Try to set it here instead.
4656 if ((flags = fcntl(fd, F_GETFL)) != -1)
4657 (void) fcntl(fd, F_SETFL, flags | O_DIRECT);
4661 #endif /* !_WIN32 */
4668 #ifdef BROKEN_FDATASYNC
4669 #include <sys/utsname.h>
4670 #include <sys/vfs.h>
4673 /** Further setup required for opening an LMDB environment
4676 mdb_env_open2(MDB_env *env, int prev)
4678 unsigned int flags = env->me_flags;
4679 int i, newenv = 0, rc;
4683 /* See if we should use QueryLimited */
4685 if ((rc & 0xff) > 5)
4686 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4688 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4691 #ifdef BROKEN_FDATASYNC
4692 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4693 * https://lkml.org/lkml/2012/9/3/83
4694 * Kernels after 3.6-rc6 are known good.
4695 * https://lkml.org/lkml/2012/9/10/556
4696 * See if the DB is on ext3/ext4, then check for new enough kernel
4697 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4702 fstatfs(env->me_fd, &st);
4703 while (st.f_type == 0xEF53) {
4707 if (uts.release[0] < '3') {
4708 if (!strncmp(uts.release, "2.6.32.", 7)) {
4709 i = atoi(uts.release+7);
4711 break; /* 2.6.32.60 and newer is OK */
4712 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4713 i = atoi(uts.release+7);
4715 break; /* 2.6.34.15 and newer is OK */
4717 } else if (uts.release[0] == '3') {
4718 i = atoi(uts.release+2);
4720 break; /* 3.6 and newer is OK */
4722 i = atoi(uts.release+4);
4724 break; /* 3.5.4 and newer is OK */
4725 } else if (i == 2) {
4726 i = atoi(uts.release+4);
4728 break; /* 3.2.30 and newer is OK */
4730 } else { /* 4.x and newer is OK */
4733 env->me_flags |= MDB_FSYNCONLY;
4739 if ((i = mdb_env_read_header(env, prev, &meta)) != 0) {
4742 DPUTS("new mdbenv");
4744 env->me_psize = env->me_os_psize;
4745 if (env->me_psize > MAX_PAGESIZE)
4746 env->me_psize = MAX_PAGESIZE;
4747 memset(&meta, 0, sizeof(meta));
4748 mdb_env_init_meta0(env, &meta);
4749 meta.mm_mapsize = DEFAULT_MAPSIZE;
4751 env->me_psize = meta.mm_psize;
4754 /* Was a mapsize configured? */
4755 if (!env->me_mapsize) {
4756 env->me_mapsize = meta.mm_mapsize;
4759 /* Make sure mapsize >= committed data size. Even when using
4760 * mm_mapsize, which could be broken in old files (ITS#7789).
4762 mdb_size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4763 if (env->me_mapsize < minsize)
4764 env->me_mapsize = minsize;
4766 meta.mm_mapsize = env->me_mapsize;
4768 if (newenv && !(flags & MDB_FIXEDMAP)) {
4769 /* mdb_env_map() may grow the datafile. Write the metapages
4770 * first, so the file will be valid if initialization fails.
4771 * Except with FIXEDMAP, since we do not yet know mm_address.
4772 * We could fill in mm_address later, but then a different
4773 * program might end up doing that - one with a memory layout
4774 * and map address which does not suit the main program.
4776 rc = mdb_env_init_meta(env, &meta);
4782 /* For FIXEDMAP, make sure the file is non-empty before we attempt to map it */
4786 rc = WriteFile(env->me_fd, &dummy, 1, &len, NULL);
4794 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4799 if (flags & MDB_FIXEDMAP)
4800 meta.mm_address = env->me_map;
4801 i = mdb_env_init_meta(env, &meta);
4802 if (i != MDB_SUCCESS) {
4807 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4808 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4810 #if !(MDB_MAXKEYSIZE)
4811 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4813 env->me_maxpg = env->me_mapsize / env->me_psize;
4817 MDB_meta *meta = mdb_env_pick_meta(env);
4818 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4820 DPRINTF(("opened database version %u, pagesize %u",
4821 meta->mm_version, env->me_psize));
4822 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4823 DPRINTF(("depth: %u", db->md_depth));
4824 DPRINTF(("entries: %"Yu, db->md_entries));
4825 DPRINTF(("branch pages: %"Yu, db->md_branch_pages));
4826 DPRINTF(("leaf pages: %"Yu, db->md_leaf_pages));
4827 DPRINTF(("overflow pages: %"Yu, db->md_overflow_pages));
4828 DPRINTF(("root: %"Yu, db->md_root));
4836 /** Release a reader thread's slot in the reader lock table.
4837 * This function is called automatically when a thread exits.
4838 * @param[in] ptr This points to the slot in the reader lock table.
4841 mdb_env_reader_dest(void *ptr)
4843 MDB_reader *reader = ptr;
4846 if (reader->mr_pid == getpid()) /* catch pthread_exit() in child process */
4848 /* We omit the mutex, so do this atomically (i.e. skip mr_txnid) */
4853 /** Junk for arranging thread-specific callbacks on Windows. This is
4854 * necessarily platform and compiler-specific. Windows supports up
4855 * to 1088 keys. Let's assume nobody opens more than 64 environments
4856 * in a single process, for now. They can override this if needed.
4858 #ifndef MAX_TLS_KEYS
4859 #define MAX_TLS_KEYS 64
4861 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4862 static int mdb_tls_nkeys;
4864 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4868 case DLL_PROCESS_ATTACH: break;
4869 case DLL_THREAD_ATTACH: break;
4870 case DLL_THREAD_DETACH:
4871 for (i=0; i<mdb_tls_nkeys; i++) {
4872 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4874 mdb_env_reader_dest(r);
4878 case DLL_PROCESS_DETACH: break;
4883 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4885 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4889 /* Force some symbol references.
4890 * _tls_used forces the linker to create the TLS directory if not already done
4891 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4893 #pragma comment(linker, "/INCLUDE:_tls_used")
4894 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4895 #pragma const_seg(".CRT$XLB")
4896 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4897 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4900 #pragma comment(linker, "/INCLUDE:__tls_used")
4901 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4902 #pragma data_seg(".CRT$XLB")
4903 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4905 #endif /* WIN 32/64 */
4906 #endif /* !__GNUC__ */
4909 /** Downgrade the exclusive lock on the region back to shared */
4911 mdb_env_share_locks(MDB_env *env, int *excl)
4914 MDB_meta *meta = mdb_env_pick_meta(env);
4916 env->me_txns->mti_txnid = meta->mm_txnid;
4921 /* First acquire a shared lock. The Unlock will
4922 * then release the existing exclusive lock.
4924 memset(&ov, 0, sizeof(ov));
4925 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4928 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4934 struct flock lock_info;
4935 /* The shared lock replaces the existing lock */
4936 memset((void *)&lock_info, 0, sizeof(lock_info));
4937 lock_info.l_type = F_RDLCK;
4938 lock_info.l_whence = SEEK_SET;
4939 lock_info.l_start = 0;
4940 lock_info.l_len = 1;
4941 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4942 (rc = ErrCode()) == EINTR) ;
4943 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4950 /** Try to get exclusive lock, otherwise shared.
4951 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4954 mdb_env_excl_lock(MDB_env *env, int *excl)
4958 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4962 memset(&ov, 0, sizeof(ov));
4963 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4970 struct flock lock_info;
4971 memset((void *)&lock_info, 0, sizeof(lock_info));
4972 lock_info.l_type = F_WRLCK;
4973 lock_info.l_whence = SEEK_SET;
4974 lock_info.l_start = 0;
4975 lock_info.l_len = 1;
4976 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4977 (rc = ErrCode()) == EINTR) ;
4981 # ifndef MDB_USE_POSIX_MUTEX
4982 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4985 lock_info.l_type = F_RDLCK;
4986 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4987 (rc = ErrCode()) == EINTR) ;
4997 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4999 * @(#) $Revision: 5.1 $
5000 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
5001 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
5003 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
5007 * Please do not copyright this code. This code is in the public domain.
5009 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
5010 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
5011 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
5012 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
5013 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
5014 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
5015 * PERFORMANCE OF THIS SOFTWARE.
5018 * chongo <Landon Curt Noll> /\oo/\
5019 * http://www.isthe.com/chongo/
5021 * Share and Enjoy! :-)
5024 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
5025 * @param[in] val value to hash
5026 * @param[in] len length of value
5027 * @return 64 bit hash
5030 mdb_hash(const void *val, size_t len)
5032 const unsigned char *s = (const unsigned char *) val, *end = s + len;
5033 mdb_hash_t hval = 0xcbf29ce484222325ULL;
5035 * FNV-1a hash each octet of the buffer
5038 hval = (hval ^ *s++) * 0x100000001b3ULL;
5040 /* return our new hash value */
5044 /** Hash the string and output the encoded hash.
5045 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
5046 * very short name limits. We don't care about the encoding being reversible,
5047 * we just want to preserve as many bits of the input as possible in a
5048 * small printable string.
5049 * @param[in] str string to hash
5050 * @param[out] encbuf an array of 11 chars to hold the hash
5052 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
5055 mdb_pack85(unsigned long long l, char *out)
5059 for (i=0; i<10 && l; i++) {
5060 *out++ = mdb_a85[l % 85];
5066 /** Init #MDB_env.me_mutexname[] except the char which #MUTEXNAME() will set.
5067 * Changes to this code must be reflected in #MDB_LOCK_FORMAT.
5070 mdb_env_mname_init(MDB_env *env)
5072 char *nm = env->me_mutexname;
5073 strcpy(nm, MUTEXNAME_PREFIX);
5074 mdb_pack85(env->me_txns->mti_mutexid, nm + sizeof(MUTEXNAME_PREFIX));
5077 /** Return env->me_mutexname after filling in ch ('r'/'w') for convenience */
5078 #define MUTEXNAME(env, ch) ( \
5079 (void) ((env)->me_mutexname[sizeof(MUTEXNAME_PREFIX)-1] = (ch)), \
5080 (env)->me_mutexname)
5084 /** Open and/or initialize the lock region for the environment.
5085 * @param[in] env The LMDB environment.
5086 * @param[in] fname Filename + scratch area, from #mdb_fname_init().
5087 * @param[in] mode The Unix permissions for the file, if we create it.
5088 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
5089 * @return 0 on success, non-zero on failure.
5092 mdb_env_setup_locks(MDB_env *env, MDB_name *fname, int mode, int *excl)
5095 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
5097 # define MDB_ERRCODE_ROFS EROFS
5099 #ifdef MDB_USE_SYSV_SEM
5106 rc = mdb_fopen(env, fname, MDB_O_LOCKS, mode, &env->me_lfd);
5108 /* Omit lockfile if read-only env on read-only filesystem */
5109 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
5115 if (!(env->me_flags & MDB_NOTLS)) {
5116 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
5119 env->me_flags |= MDB_ENV_TXKEY;
5121 /* Windows TLS callbacks need help finding their TLS info. */
5122 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
5126 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
5130 /* Try to get exclusive lock. If we succeed, then
5131 * nobody is using the lock region and we should initialize it.
5133 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
5136 size = GetFileSize(env->me_lfd, NULL);
5138 size = lseek(env->me_lfd, 0, SEEK_END);
5139 if (size == -1) goto fail_errno;
5141 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
5142 if (size < rsize && *excl > 0) {
5144 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
5145 || !SetEndOfFile(env->me_lfd))
5148 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
5152 size = rsize - sizeof(MDB_txninfo);
5153 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
5158 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
5160 if (!mh) goto fail_errno;
5161 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
5163 if (!env->me_txns) goto fail_errno;
5165 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
5167 if (m == MAP_FAILED) goto fail_errno;
5173 BY_HANDLE_FILE_INFORMATION stbuf;
5180 if (!mdb_sec_inited) {
5181 InitializeSecurityDescriptor(&mdb_null_sd,
5182 SECURITY_DESCRIPTOR_REVISION);
5183 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
5184 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
5185 mdb_all_sa.bInheritHandle = FALSE;
5186 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
5189 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
5190 idbuf.volume = stbuf.dwVolumeSerialNumber;
5191 idbuf.nhigh = stbuf.nFileIndexHigh;
5192 idbuf.nlow = stbuf.nFileIndexLow;
5193 env->me_txns->mti_mutexid = mdb_hash(&idbuf, sizeof(idbuf));
5194 mdb_env_mname_init(env);
5195 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, MUTEXNAME(env, 'r'));
5196 if (!env->me_rmutex) goto fail_errno;
5197 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, MUTEXNAME(env, 'w'));
5198 if (!env->me_wmutex) goto fail_errno;
5199 #elif defined(MDB_USE_POSIX_SEM)
5206 #if defined(__NetBSD__)
5207 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
5209 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
5210 memset(&idbuf, 0, sizeof(idbuf));
5211 idbuf.dev = stbuf.st_dev;
5212 idbuf.ino = stbuf.st_ino;
5213 env->me_txns->mti_mutexid = mdb_hash(&idbuf, sizeof(idbuf))
5214 #ifdef MDB_SHORT_SEMNAMES
5215 /* Max 9 base85-digits. We truncate here instead of in
5216 * mdb_env_mname_init() to keep the latter portable.
5218 % ((mdb_hash_t)85*85*85*85*85*85*85*85*85)
5221 mdb_env_mname_init(env);
5222 /* Clean up after a previous run, if needed: Try to
5223 * remove both semaphores before doing anything else.
5225 sem_unlink(MUTEXNAME(env, 'r'));
5226 sem_unlink(MUTEXNAME(env, 'w'));
5227 env->me_rmutex = sem_open(MUTEXNAME(env, 'r'), O_CREAT|O_EXCL, mode, 1);
5228 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
5229 env->me_wmutex = sem_open(MUTEXNAME(env, 'w'), O_CREAT|O_EXCL, mode, 1);
5230 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
5231 #elif defined(MDB_USE_SYSV_SEM)
5232 unsigned short vals[2] = {1, 1};
5233 key_t key = ftok(fname->mn_val, 'M'); /* fname is lockfile path now */
5236 semid = semget(key, 2, (mode & 0777) | IPC_CREAT);
5240 if (semctl(semid, 0, SETALL, semu) < 0)
5242 env->me_txns->mti_semid = semid;
5243 env->me_txns->mti_rlocked = 0;
5244 env->me_txns->mti_wlocked = 0;
5245 #else /* MDB_USE_POSIX_MUTEX: */
5246 pthread_mutexattr_t mattr;
5248 /* Solaris needs this before initing a robust mutex. Otherwise
5249 * it may skip the init and return EBUSY "seems someone already
5250 * inited" or EINVAL "it was inited differently".
5252 memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
5253 memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
5255 if ((rc = pthread_mutexattr_init(&mattr)) != 0)
5257 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
5258 #ifdef MDB_ROBUST_SUPPORTED
5259 if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
5261 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
5262 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
5263 pthread_mutexattr_destroy(&mattr);
5266 #endif /* _WIN32 || ... */
5268 env->me_txns->mti_magic = MDB_MAGIC;
5269 env->me_txns->mti_format = MDB_LOCK_FORMAT;
5270 env->me_txns->mti_txnid = 0;
5271 env->me_txns->mti_numreaders = 0;
5274 #ifdef MDB_USE_SYSV_SEM
5275 struct semid_ds buf;
5277 if (env->me_txns->mti_magic != MDB_MAGIC) {
5278 DPUTS("lock region has invalid magic");
5282 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
5283 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
5284 env->me_txns->mti_format, MDB_LOCK_FORMAT));
5285 rc = MDB_VERSION_MISMATCH;
5289 if (rc && rc != EACCES && rc != EAGAIN) {
5293 mdb_env_mname_init(env);
5294 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, MUTEXNAME(env, 'r'));
5295 if (!env->me_rmutex) goto fail_errno;
5296 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, MUTEXNAME(env, 'w'));
5297 if (!env->me_wmutex) goto fail_errno;
5298 #elif defined(MDB_USE_POSIX_SEM)
5299 mdb_env_mname_init(env);
5300 env->me_rmutex = sem_open(MUTEXNAME(env, 'r'), 0);
5301 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
5302 env->me_wmutex = sem_open(MUTEXNAME(env, 'w'), 0);
5303 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
5304 #elif defined(MDB_USE_SYSV_SEM)
5305 semid = env->me_txns->mti_semid;
5307 /* check for read access */
5308 if (semctl(semid, 0, IPC_STAT, semu) < 0)
5310 /* check for write access */
5311 if (semctl(semid, 0, IPC_SET, semu) < 0)
5315 #ifdef MDB_USE_SYSV_SEM
5316 env->me_rmutex->semid = semid;
5317 env->me_wmutex->semid = semid;
5318 env->me_rmutex->semnum = 0;
5319 env->me_wmutex->semnum = 1;
5320 env->me_rmutex->locked = &env->me_txns->mti_rlocked;
5321 env->me_wmutex->locked = &env->me_txns->mti_wlocked;
5332 /** Only a subset of the @ref mdb_env flags can be changed
5333 * at runtime. Changing other flags requires closing the
5334 * environment and re-opening it with the new flags.
5336 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
5337 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
5338 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD|MDB_PREVMETA)
5340 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
5341 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
5345 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
5350 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
5354 if (flags & MDB_WRITEMAP) {
5355 /* silently ignore WRITEMAP in 32 bit mode */
5356 flags ^= MDB_WRITEMAP;
5358 if (flags & MDB_FIXEDMAP) {
5359 /* cannot support FIXEDMAP */
5363 flags |= env->me_flags;
5365 rc = mdb_fname_init(path, flags, &fname);
5371 env->me_rpmutex = CreateMutex(NULL, FALSE, NULL);
5372 if (!env->me_rpmutex) {
5377 rc = pthread_mutex_init(&env->me_rpmutex, NULL);
5382 flags |= MDB_ENV_ACTIVE; /* tell mdb_env_close0() to clean up */
5384 if (flags & MDB_RDONLY) {
5385 /* silently ignore WRITEMAP when we're only getting read access */
5386 flags &= ~MDB_WRITEMAP;
5388 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
5389 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
5393 env->me_flags = flags;
5399 env->me_rpages = malloc(MDB_ERPAGE_SIZE * sizeof(MDB_ID3));
5400 if (!env->me_rpages) {
5404 env->me_rpages[0].mid = 0;
5405 env->me_rpcheck = MDB_ERPAGE_SIZE/2;
5409 env->me_path = strdup(path);
5410 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
5411 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
5412 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
5413 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
5417 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
5419 /* For RDONLY, get lockfile after we know datafile exists */
5420 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
5421 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
5426 rc = mdb_fopen(env, &fname,
5427 (flags & MDB_RDONLY) ? MDB_O_RDONLY : MDB_O_RDWR,
5432 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
5433 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
5438 if ((rc = mdb_env_open2(env, flags & MDB_PREVMETA)) == MDB_SUCCESS) {
5439 if (!(flags & (MDB_RDONLY|MDB_WRITEMAP))) {
5440 /* Synchronous fd for meta writes. Needed even with
5441 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
5443 rc = mdb_fopen(env, &fname, MDB_O_META, mode, &env->me_mfd);
5447 DPRINTF(("opened dbenv %p", (void *) env));
5449 rc = mdb_env_share_locks(env, &excl);
5453 if (!(flags & MDB_RDONLY)) {
5455 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
5456 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
5457 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
5458 (txn = calloc(1, size)))
5460 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
5461 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
5462 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
5463 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
5466 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
5467 if (!txn->mt_rpages) {
5472 txn->mt_rpages[0].mid = 0;
5473 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
5475 txn->mt_dbxs = env->me_dbxs;
5476 txn->mt_flags = MDB_TXN_FINISHED;
5486 mdb_env_close0(env, excl);
5488 mdb_fname_destroy(fname);
5492 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
5494 mdb_env_close0(MDB_env *env, int excl)
5498 if (!(env->me_flags & MDB_ENV_ACTIVE))
5501 /* Doing this here since me_dbxs may not exist during mdb_env_close */
5503 for (i = env->me_maxdbs; --i >= CORE_DBS; )
5504 free(env->me_dbxs[i].md_name.mv_data);
5509 free(env->me_dbiseqs);
5510 free(env->me_dbflags);
5512 free(env->me_dirty_list);
5514 if (env->me_txn0 && env->me_txn0->mt_rpages)
5515 free(env->me_txn0->mt_rpages);
5516 if (env->me_rpages) {
5517 MDB_ID3L el = env->me_rpages;
5519 for (x=1; x<=el[0].mid; x++)
5520 munmap(el[x].mptr, el[x].mcnt * env->me_psize);
5525 mdb_midl_free(env->me_free_pgs);
5527 if (env->me_flags & MDB_ENV_TXKEY) {
5528 pthread_key_delete(env->me_txkey);
5530 /* Delete our key from the global list */
5531 for (i=0; i<mdb_tls_nkeys; i++)
5532 if (mdb_tls_keys[i] == env->me_txkey) {
5533 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
5542 munmap(env->me_map, NUM_METAS*env->me_psize);
5544 munmap(env->me_map, env->me_mapsize);
5547 if (env->me_mfd != INVALID_HANDLE_VALUE)
5548 (void) close(env->me_mfd);
5549 if (env->me_fd != INVALID_HANDLE_VALUE)
5550 (void) close(env->me_fd);
5552 MDB_PID_T pid = env->me_pid;
5553 /* Clearing readers is done in this function because
5554 * me_txkey with its destructor must be disabled first.
5556 * We skip the the reader mutex, so we touch only
5557 * data owned by this process (me_close_readers and
5558 * our readers), and clear each reader atomically.
5560 for (i = env->me_close_readers; --i >= 0; )
5561 if (env->me_txns->mti_readers[i].mr_pid == pid)
5562 env->me_txns->mti_readers[i].mr_pid = 0;
5564 if (env->me_rmutex) {
5565 CloseHandle(env->me_rmutex);
5566 if (env->me_wmutex) CloseHandle(env->me_wmutex);
5568 /* Windows automatically destroys the mutexes when
5569 * the last handle closes.
5571 #elif defined(MDB_USE_POSIX_SEM)
5572 if (env->me_rmutex != SEM_FAILED) {
5573 sem_close(env->me_rmutex);
5574 if (env->me_wmutex != SEM_FAILED)
5575 sem_close(env->me_wmutex);
5576 /* If we have the filelock: If we are the
5577 * only remaining user, clean up semaphores.
5580 mdb_env_excl_lock(env, &excl);
5582 sem_unlink(MUTEXNAME(env, 'r'));
5583 sem_unlink(MUTEXNAME(env, 'w'));
5586 #elif defined(MDB_USE_SYSV_SEM)
5587 if (env->me_rmutex->semid != -1) {
5588 /* If we have the filelock: If we are the
5589 * only remaining user, clean up semaphores.
5592 mdb_env_excl_lock(env, &excl);
5594 semctl(env->me_rmutex->semid, 0, IPC_RMID);
5597 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
5599 if (env->me_lfd != INVALID_HANDLE_VALUE) {
5602 /* Unlock the lockfile. Windows would have unlocked it
5603 * after closing anyway, but not necessarily at once.
5605 UnlockFile(env->me_lfd, 0, 0, 1, 0);
5608 (void) close(env->me_lfd);
5612 if (env->me_fmh) CloseHandle(env->me_fmh);
5613 if (env->me_rpmutex) CloseHandle(env->me_rpmutex);
5615 pthread_mutex_destroy(&env->me_rpmutex);
5619 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
5623 mdb_env_close(MDB_env *env)
5630 VGMEMP_DESTROY(env);
5631 while ((dp = env->me_dpages) != NULL) {
5632 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5633 env->me_dpages = dp->mp_next;
5637 mdb_env_close0(env, 0);
5641 /** Compare two items pointing at aligned #mdb_size_t's */
5643 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5645 return (*(mdb_size_t *)a->mv_data < *(mdb_size_t *)b->mv_data) ? -1 :
5646 *(mdb_size_t *)a->mv_data > *(mdb_size_t *)b->mv_data;
5649 /** Compare two items pointing at aligned unsigned int's.
5651 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5652 * but #mdb_cmp_clong() is called instead if the data type is #mdb_size_t.
5655 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5657 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5658 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5661 /** Compare two items pointing at unsigned ints of unknown alignment.
5662 * Nodes and keys are guaranteed to be 2-byte aligned.
5665 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5667 #if BYTE_ORDER == LITTLE_ENDIAN
5668 unsigned short *u, *c;
5671 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5672 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5675 } while(!x && u > (unsigned short *)a->mv_data);
5678 unsigned short *u, *c, *end;
5681 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5682 u = (unsigned short *)a->mv_data;
5683 c = (unsigned short *)b->mv_data;
5686 } while(!x && u < end);
5691 /** Compare two items lexically */
5693 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5700 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5706 diff = memcmp(a->mv_data, b->mv_data, len);
5707 return diff ? diff : len_diff<0 ? -1 : len_diff;
5710 /** Compare two items in reverse byte order */
5712 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5714 const unsigned char *p1, *p2, *p1_lim;
5718 p1_lim = (const unsigned char *)a->mv_data;
5719 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5720 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5722 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5728 while (p1 > p1_lim) {
5729 diff = *--p1 - *--p2;
5733 return len_diff<0 ? -1 : len_diff;
5736 /** Search for key within a page, using binary search.
5737 * Returns the smallest entry larger or equal to the key.
5738 * If exactp is non-null, stores whether the found entry was an exact match
5739 * in *exactp (1 or 0).
5740 * Updates the cursor index with the index of the found entry.
5741 * If no entry larger or equal to the key is found, returns NULL.
5744 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5746 unsigned int i = 0, nkeys;
5749 MDB_page *mp = mc->mc_pg[mc->mc_top];
5750 MDB_node *node = NULL;
5755 nkeys = NUMKEYS(mp);
5757 DPRINTF(("searching %u keys in %s %spage %"Yu,
5758 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5761 low = IS_LEAF(mp) ? 0 : 1;
5763 cmp = mc->mc_dbx->md_cmp;
5765 /* Branch pages have no data, so if using integer keys,
5766 * alignment is guaranteed. Use faster mdb_cmp_int.
5768 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5769 if (NODEPTR(mp, 1)->mn_ksize == sizeof(mdb_size_t))
5776 nodekey.mv_size = mc->mc_db->md_pad;
5777 node = NODEPTR(mp, 0); /* fake */
5778 while (low <= high) {
5779 i = (low + high) >> 1;
5780 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5781 rc = cmp(key, &nodekey);
5782 DPRINTF(("found leaf index %u [%s], rc = %i",
5783 i, DKEY(&nodekey), rc));
5792 while (low <= high) {
5793 i = (low + high) >> 1;
5795 node = NODEPTR(mp, i);
5796 nodekey.mv_size = NODEKSZ(node);
5797 nodekey.mv_data = NODEKEY(node);
5799 rc = cmp(key, &nodekey);
5802 DPRINTF(("found leaf index %u [%s], rc = %i",
5803 i, DKEY(&nodekey), rc));
5805 DPRINTF(("found branch index %u [%s -> %"Yu"], rc = %i",
5806 i, DKEY(&nodekey), NODEPGNO(node), rc));
5817 if (rc > 0) { /* Found entry is less than the key. */
5818 i++; /* Skip to get the smallest entry larger than key. */
5820 node = NODEPTR(mp, i);
5823 *exactp = (rc == 0 && nkeys > 0);
5824 /* store the key index */
5825 mc->mc_ki[mc->mc_top] = i;
5827 /* There is no entry larger or equal to the key. */
5830 /* nodeptr is fake for LEAF2 */
5836 mdb_cursor_adjust(MDB_cursor *mc, func)
5840 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5841 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5848 /** Pop a page off the top of the cursor's stack. */
5850 mdb_cursor_pop(MDB_cursor *mc)
5853 DPRINTF(("popping page %"Yu" off db %d cursor %p",
5854 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5860 mc->mc_flags &= ~C_INITIALIZED;
5865 /** Push a page onto the top of the cursor's stack.
5866 * Set #MDB_TXN_ERROR on failure.
5869 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5871 DPRINTF(("pushing page %"Yu" on db %d cursor %p", mp->mp_pgno,
5872 DDBI(mc), (void *) mc));
5874 if (mc->mc_snum >= CURSOR_STACK) {
5875 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5876 return MDB_CURSOR_FULL;
5879 mc->mc_top = mc->mc_snum++;
5880 mc->mc_pg[mc->mc_top] = mp;
5881 mc->mc_ki[mc->mc_top] = 0;
5887 /** Map a read-only page.
5888 * There are two levels of tracking in use, a per-txn list and a per-env list.
5889 * ref'ing and unref'ing the per-txn list is faster since it requires no
5890 * locking. Pages are cached in the per-env list for global reuse, and a lock
5891 * is required. Pages are not immediately unmapped when their refcnt goes to
5892 * zero; they hang around in case they will be reused again soon.
5894 * When the per-txn list gets full, all pages with refcnt=0 are purged from the
5895 * list and their refcnts in the per-env list are decremented.
5897 * When the per-env list gets full, all pages with refcnt=0 are purged from the
5898 * list and their pages are unmapped.
5900 * @note "full" means the list has reached its respective rpcheck threshold.
5901 * This threshold slowly raises if no pages could be purged on a given check,
5902 * and returns to its original value when enough pages were purged.
5904 * If purging doesn't free any slots, filling the per-txn list will return
5905 * MDB_TXN_FULL, and filling the per-env list returns MDB_MAP_FULL.
5907 * Reference tracking in a txn is imperfect, pages can linger with non-zero
5908 * refcnt even without active references. It was deemed to be too invasive
5909 * to add unrefs in every required location. However, all pages are unref'd
5910 * at the end of the transaction. This guarantees that no stale references
5911 * linger in the per-env list.
5913 * Usually we map chunks of 16 pages at a time, but if an overflow page begins
5914 * at the tail of the chunk we extend the chunk to include the entire overflow
5915 * page. Unfortunately, pages can be turned into overflow pages after their
5916 * chunk was already mapped. In that case we must remap the chunk if the
5917 * overflow page is referenced. If the chunk's refcnt is 0 we can just remap
5918 * it, otherwise we temporarily map a new chunk just for the overflow page.
5920 * @note this chunk handling means we cannot guarantee that a data item
5921 * returned from the DB will stay alive for the duration of the transaction:
5922 * We unref pages as soon as a cursor moves away from the page
5923 * A subsequent op may cause a purge, which may unmap any unref'd chunks
5924 * The caller must copy the data if it must be used later in the same txn.
5926 * Also - our reference counting revolves around cursors, but overflow pages
5927 * aren't pointed to by a cursor's page stack. We have to remember them
5928 * explicitly, in the added mc_ovpg field. A single cursor can only hold a
5929 * reference to one overflow page at a time.
5931 * @param[in] txn the transaction for this access.
5932 * @param[in] pgno the page number for the page to retrieve.
5933 * @param[out] ret address of a pointer where the page's address will be stored.
5934 * @return 0 on success, non-zero on failure.
5937 mdb_rpage_get(MDB_txn *txn, pgno_t pg0, MDB_page **ret)
5939 MDB_env *env = txn->mt_env;
5941 MDB_ID3L tl = txn->mt_rpages;
5942 MDB_ID3L el = env->me_rpages;
5946 int rc, retries = 1;
5950 #define SET_OFF(off,val) off.QuadPart = val
5951 #define MAP(rc,env,addr,len,off) \
5953 rc = NtMapViewOfSection(env->me_fmh, GetCurrentProcess(), &addr, 0, \
5954 len, &off, &len, ViewUnmap, (env->me_flags & MDB_RDONLY) ? 0 : MEM_RESERVE, PAGE_READONLY); \
5955 if (rc) rc = mdb_nt2win32(rc)
5959 #define SET_OFF(off,val) off = val
5960 #define MAP(rc,env,addr,len,off) \
5961 addr = mmap(NULL, len, PROT_READ, MAP_SHARED, env->me_fd, off); \
5962 rc = (addr == MAP_FAILED) ? errno : 0
5965 /* remember the offset of the actual page number, so we can
5966 * return the correct pointer at the end.
5968 rem = pg0 & (MDB_RPAGE_CHUNK-1);
5972 x = mdb_mid3l_search(tl, pgno);
5973 if (x <= tl[0].mid && tl[x].mid == pgno) {
5974 if (x != tl[0].mid && tl[x+1].mid == pg0)
5976 /* check for overflow size */
5977 p = (MDB_page *)((char *)tl[x].mptr + rem * env->me_psize);
5978 if (IS_OVERFLOW(p) && p->mp_pages + rem > tl[x].mcnt) {
5979 id3.mcnt = p->mp_pages + rem;
5980 len = id3.mcnt * env->me_psize;
5981 SET_OFF(off, pgno * env->me_psize);
5982 MAP(rc, env, id3.mptr, len, off);
5985 /* check for local-only page */
5987 mdb_tassert(txn, tl[x].mid != pg0);
5988 /* hope there's room to insert this locally.
5989 * setting mid here tells later code to just insert
5990 * this id3 instead of searching for a match.
5995 /* ignore the mapping we got from env, use new one */
5996 tl[x].mptr = id3.mptr;
5997 tl[x].mcnt = id3.mcnt;
5998 /* if no active ref, see if we can replace in env */
6001 pthread_mutex_lock(&env->me_rpmutex);
6002 i = mdb_mid3l_search(el, tl[x].mid);
6003 if (el[i].mref == 1) {
6004 /* just us, replace it */
6005 munmap(el[i].mptr, el[i].mcnt * env->me_psize);
6006 el[i].mptr = tl[x].mptr;
6007 el[i].mcnt = tl[x].mcnt;
6009 /* there are others, remove ourself */
6012 pthread_mutex_unlock(&env->me_rpmutex);
6016 id3.mptr = tl[x].mptr;
6017 id3.mcnt = tl[x].mcnt;
6023 if (tl[0].mid >= MDB_TRPAGE_MAX - txn->mt_rpcheck) {
6025 /* purge unref'd pages from our list and unref in env */
6026 pthread_mutex_lock(&env->me_rpmutex);
6029 for (i=1; i<=tl[0].mid; i++) {
6032 /* tmp overflow pages don't go to env */
6033 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
6034 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
6037 x = mdb_mid3l_search(el, tl[i].mid);
6041 pthread_mutex_unlock(&env->me_rpmutex);
6043 /* we didn't find any unref'd chunks.
6044 * if we're out of room, fail.
6046 if (tl[0].mid >= MDB_TRPAGE_MAX)
6047 return MDB_TXN_FULL;
6048 /* otherwise, raise threshold for next time around
6051 txn->mt_rpcheck /= 2;
6053 /* we found some unused; consolidate the list */
6054 for (i=y+1; i<= tl[0].mid; i++)
6058 /* decrease the check threshold toward its original value */
6059 if (!txn->mt_rpcheck)
6060 txn->mt_rpcheck = 1;
6061 while (txn->mt_rpcheck < tl[0].mid && txn->mt_rpcheck < MDB_TRPAGE_SIZE/2)
6062 txn->mt_rpcheck *= 2;
6065 if (tl[0].mid < MDB_TRPAGE_SIZE) {
6069 /* don't map past last written page in read-only envs */
6070 if ((env->me_flags & MDB_RDONLY) && pgno + MDB_RPAGE_CHUNK-1 > txn->mt_last_pgno)
6071 id3.mcnt = txn->mt_last_pgno + 1 - pgno;
6073 id3.mcnt = MDB_RPAGE_CHUNK;
6074 len = id3.mcnt * env->me_psize;
6077 /* search for page in env */
6078 pthread_mutex_lock(&env->me_rpmutex);
6079 x = mdb_mid3l_search(el, pgno);
6080 if (x <= el[0].mid && el[x].mid == pgno) {
6081 id3.mptr = el[x].mptr;
6082 id3.mcnt = el[x].mcnt;
6083 /* check for overflow size */
6084 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
6085 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
6086 id3.mcnt = p->mp_pages + rem;
6087 len = id3.mcnt * env->me_psize;
6088 SET_OFF(off, pgno * env->me_psize);
6089 MAP(rc, env, id3.mptr, len, off);
6093 munmap(el[x].mptr, env->me_psize * el[x].mcnt);
6094 el[x].mptr = id3.mptr;
6095 el[x].mcnt = id3.mcnt;
6098 pthread_mutex_unlock(&env->me_rpmutex);
6103 pthread_mutex_unlock(&env->me_rpmutex);
6106 if (el[0].mid >= MDB_ERPAGE_MAX - env->me_rpcheck) {
6107 /* purge unref'd pages */
6109 for (i=1; i<=el[0].mid; i++) {
6112 munmap(el[i].mptr, env->me_psize * el[i].mcnt);
6117 /* see if we can unref some local pages */
6122 if (el[0].mid >= MDB_ERPAGE_MAX) {
6123 pthread_mutex_unlock(&env->me_rpmutex);
6124 return MDB_MAP_FULL;
6126 env->me_rpcheck /= 2;
6128 for (i=y+1; i<= el[0].mid; i++)
6132 if (!env->me_rpcheck)
6133 env->me_rpcheck = 1;
6134 while (env->me_rpcheck < el[0].mid && env->me_rpcheck < MDB_ERPAGE_SIZE/2)
6135 env->me_rpcheck *= 2;
6138 SET_OFF(off, pgno * env->me_psize);
6139 MAP(rc, env, id3.mptr, len, off);
6142 pthread_mutex_unlock(&env->me_rpmutex);
6145 /* check for overflow size */
6146 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
6147 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
6148 id3.mcnt = p->mp_pages + rem;
6149 munmap(id3.mptr, len);
6150 len = id3.mcnt * env->me_psize;
6151 MAP(rc, env, id3.mptr, len, off);
6155 mdb_mid3l_insert(el, &id3);
6156 pthread_mutex_unlock(&env->me_rpmutex);
6158 mdb_mid3l_insert(tl, &id3);
6160 return MDB_TXN_FULL;
6163 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
6164 #if MDB_DEBUG /* we don't need this check any more */
6165 if (IS_OVERFLOW(p)) {
6166 mdb_tassert(txn, p->mp_pages + rem <= id3.mcnt);
6174 /** Find the address of the page corresponding to a given page number.
6175 * Set #MDB_TXN_ERROR on failure.
6176 * @param[in] mc the cursor accessing the page.
6177 * @param[in] pgno the page number for the page to retrieve.
6178 * @param[out] ret address of a pointer where the page's address will be stored.
6179 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
6180 * @return 0 on success, non-zero on failure.
6183 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
6185 MDB_txn *txn = mc->mc_txn;
6189 if (! (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP))) {
6193 MDB_ID2L dl = tx2->mt_u.dirty_list;
6195 /* Spilled pages were dirtied in this txn and flushed
6196 * because the dirty list got full. Bring this page
6197 * back in from the map (but don't unspill it here,
6198 * leave that unless page_touch happens again).
6200 if (tx2->mt_spill_pgs) {
6201 MDB_ID pn = pgno << 1;
6202 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
6203 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
6208 unsigned x = mdb_mid2l_search(dl, pgno);
6209 if (x <= dl[0].mid && dl[x].mid == pgno) {
6215 } while ((tx2 = tx2->mt_parent) != NULL);
6218 if (pgno >= txn->mt_next_pgno) {
6219 DPRINTF(("page %"Yu" not found", pgno));
6220 txn->mt_flags |= MDB_TXN_ERROR;
6221 return MDB_PAGE_NOTFOUND;
6229 int rc = mdb_rpage_get(txn, pgno, &p);
6231 txn->mt_flags |= MDB_TXN_ERROR;
6235 MDB_env *env = txn->mt_env;
6236 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
6247 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
6248 * The cursor is at the root page, set up the rest of it.
6251 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
6253 MDB_page *mp = mc->mc_pg[mc->mc_top];
6257 while (IS_BRANCH(mp)) {
6261 DPRINTF(("branch page %"Yu" has %u keys", mp->mp_pgno, NUMKEYS(mp)));
6262 /* Don't assert on branch pages in the FreeDB. We can get here
6263 * while in the process of rebalancing a FreeDB branch page; we must
6264 * let that proceed. ITS#8336
6266 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
6267 DPRINTF(("found index 0 to page %"Yu, NODEPGNO(NODEPTR(mp, 0))));
6269 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
6271 if (flags & MDB_PS_LAST) {
6272 i = NUMKEYS(mp) - 1;
6273 /* if already init'd, see if we're already in right place */
6274 if (mc->mc_flags & C_INITIALIZED) {
6275 if (mc->mc_ki[mc->mc_top] == i) {
6276 mc->mc_top = mc->mc_snum++;
6277 mp = mc->mc_pg[mc->mc_top];
6284 node = mdb_node_search(mc, key, &exact);
6286 i = NUMKEYS(mp) - 1;
6288 i = mc->mc_ki[mc->mc_top];
6290 mdb_cassert(mc, i > 0);
6294 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
6297 mdb_cassert(mc, i < NUMKEYS(mp));
6298 node = NODEPTR(mp, i);
6300 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6303 mc->mc_ki[mc->mc_top] = i;
6304 if ((rc = mdb_cursor_push(mc, mp)))
6308 if (flags & MDB_PS_MODIFY) {
6309 if ((rc = mdb_page_touch(mc)) != 0)
6311 mp = mc->mc_pg[mc->mc_top];
6316 DPRINTF(("internal error, index points to a %02X page!?",
6318 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6319 return MDB_CORRUPTED;
6322 DPRINTF(("found leaf page %"Yu" for key [%s]", mp->mp_pgno,
6323 key ? DKEY(key) : "null"));
6324 mc->mc_flags |= C_INITIALIZED;
6325 mc->mc_flags &= ~C_EOF;
6330 /** Search for the lowest key under the current branch page.
6331 * This just bypasses a NUMKEYS check in the current page
6332 * before calling mdb_page_search_root(), because the callers
6333 * are all in situations where the current page is known to
6337 mdb_page_search_lowest(MDB_cursor *mc)
6339 MDB_page *mp = mc->mc_pg[mc->mc_top];
6340 MDB_node *node = NODEPTR(mp, 0);
6343 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6346 mc->mc_ki[mc->mc_top] = 0;
6347 if ((rc = mdb_cursor_push(mc, mp)))
6349 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
6352 /** Search for the page a given key should be in.
6353 * Push it and its parent pages on the cursor stack.
6354 * @param[in,out] mc the cursor for this operation.
6355 * @param[in] key the key to search for, or NULL for first/last page.
6356 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
6357 * are touched (updated with new page numbers).
6358 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
6359 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
6360 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
6361 * @return 0 on success, non-zero on failure.
6364 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
6369 /* Make sure the txn is still viable, then find the root from
6370 * the txn's db table and set it as the root of the cursor's stack.
6372 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
6373 DPUTS("transaction may not be used now");
6376 /* Make sure we're using an up-to-date root */
6377 if (*mc->mc_dbflag & DB_STALE) {
6379 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6381 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
6382 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
6389 MDB_node *leaf = mdb_node_search(&mc2,
6390 &mc->mc_dbx->md_name, &exact);
6392 return MDB_NOTFOUND;
6393 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
6394 return MDB_INCOMPATIBLE; /* not a named DB */
6395 rc = mdb_node_read(&mc2, leaf, &data);
6398 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
6400 /* The txn may not know this DBI, or another process may
6401 * have dropped and recreated the DB with other flags.
6403 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
6404 return MDB_INCOMPATIBLE;
6405 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
6407 *mc->mc_dbflag &= ~DB_STALE;
6409 root = mc->mc_db->md_root;
6411 if (root == P_INVALID) { /* Tree is empty. */
6412 DPUTS("tree is empty");
6413 return MDB_NOTFOUND;
6417 mdb_cassert(mc, root > 1);
6418 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root) {
6421 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[0]);
6423 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
6430 for (i=1; i<mc->mc_snum; i++)
6431 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[i]);
6437 DPRINTF(("db %d root page %"Yu" has flags 0x%X",
6438 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
6440 if (flags & MDB_PS_MODIFY) {
6441 if ((rc = mdb_page_touch(mc)))
6445 if (flags & MDB_PS_ROOTONLY)
6448 return mdb_page_search_root(mc, key, flags);
6452 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
6454 MDB_txn *txn = mc->mc_txn;
6455 pgno_t pg = mp->mp_pgno;
6456 unsigned x = 0, ovpages = mp->mp_pages;
6457 MDB_env *env = txn->mt_env;
6458 MDB_IDL sl = txn->mt_spill_pgs;
6459 MDB_ID pn = pg << 1;
6462 DPRINTF(("free ov page %"Yu" (%d)", pg, ovpages));
6463 /* If the page is dirty or on the spill list we just acquired it,
6464 * so we should give it back to our current free list, if any.
6465 * Otherwise put it onto the list of pages we freed in this txn.
6467 * Won't create me_pghead: me_pglast must be inited along with it.
6468 * Unsupported in nested txns: They would need to hide the page
6469 * range in ancestor txns' dirty and spilled lists.
6471 if (env->me_pghead &&
6473 ((mp->mp_flags & P_DIRTY) ||
6474 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
6478 MDB_ID2 *dl, ix, iy;
6479 rc = mdb_midl_need(&env->me_pghead, ovpages);
6482 if (!(mp->mp_flags & P_DIRTY)) {
6483 /* This page is no longer spilled */
6490 /* Remove from dirty list */
6491 dl = txn->mt_u.dirty_list;
6493 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
6499 mdb_cassert(mc, x > 1);
6501 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
6502 txn->mt_flags |= MDB_TXN_ERROR;
6506 txn->mt_dirty_room++;
6507 if (!(env->me_flags & MDB_WRITEMAP))
6508 mdb_dpage_free(env, mp);
6510 /* Insert in me_pghead */
6511 mop = env->me_pghead;
6512 j = mop[0] + ovpages;
6513 for (i = mop[0]; i && mop[i] < pg; i--)
6519 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
6524 if (mc->mc_ovpg == mp)
6527 mc->mc_db->md_overflow_pages -= ovpages;
6531 /** Return the data associated with a given node.
6532 * @param[in] mc The cursor for this operation.
6533 * @param[in] leaf The node being read.
6534 * @param[out] data Updated to point to the node's data.
6535 * @return 0 on success, non-zero on failure.
6538 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
6540 MDB_page *omp; /* overflow page */
6545 MDB_PAGE_UNREF(mc->mc_txn, MC_OVPG(mc));
6546 MC_SET_OVPG(mc, NULL);
6548 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6549 data->mv_size = NODEDSZ(leaf);
6550 data->mv_data = NODEDATA(leaf);
6554 /* Read overflow data.
6556 data->mv_size = NODEDSZ(leaf);
6557 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
6558 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
6559 DPRINTF(("read overflow page %"Yu" failed", pgno));
6562 data->mv_data = METADATA(omp);
6563 MC_SET_OVPG(mc, omp);
6569 mdb_get(MDB_txn *txn, MDB_dbi dbi,
6570 MDB_val *key, MDB_val *data)
6577 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
6579 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
6582 if (txn->mt_flags & MDB_TXN_BLOCKED)
6585 mdb_cursor_init(&mc, txn, dbi, &mx);
6586 rc = mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
6587 /* unref all the pages when MDB_VL32 - caller must copy the data
6588 * before doing anything else
6590 MDB_CURSOR_UNREF(&mc, 1);
6594 /** Find a sibling for a page.
6595 * Replaces the page at the top of the cursor's stack with the
6596 * specified sibling, if one exists.
6597 * @param[in] mc The cursor for this operation.
6598 * @param[in] move_right Non-zero if the right sibling is requested,
6599 * otherwise the left sibling.
6600 * @return 0 on success, non-zero on failure.
6603 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
6612 if (mc->mc_snum < 2) {
6613 return MDB_NOTFOUND; /* root has no siblings */
6617 op = mc->mc_pg[mc->mc_top];
6620 DPRINTF(("parent page is page %"Yu", index %u",
6621 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
6623 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6624 : (mc->mc_ki[mc->mc_top] == 0)) {
6625 DPRINTF(("no more keys left, moving to %s sibling",
6626 move_right ? "right" : "left"));
6627 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
6628 /* undo cursor_pop before returning */
6635 mc->mc_ki[mc->mc_top]++;
6637 mc->mc_ki[mc->mc_top]--;
6638 DPRINTF(("just moving to %s index key %u",
6639 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
6641 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
6643 MDB_PAGE_UNREF(mc->mc_txn, op);
6645 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6646 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
6647 /* mc will be inconsistent if caller does mc_snum++ as above */
6648 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6652 mdb_cursor_push(mc, mp);
6654 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
6659 /** Move the cursor to the next data item. */
6661 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6667 if ((mc->mc_flags & C_DEL && op == MDB_NEXT_DUP))
6668 return MDB_NOTFOUND;
6670 if (!(mc->mc_flags & C_INITIALIZED))
6671 return mdb_cursor_first(mc, key, data);
6673 mp = mc->mc_pg[mc->mc_top];
6675 if (mc->mc_flags & C_EOF) {
6676 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mp)-1)
6677 return MDB_NOTFOUND;
6678 mc->mc_flags ^= C_EOF;
6681 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6682 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6683 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6684 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
6685 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
6686 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
6687 if (rc == MDB_SUCCESS)
6688 MDB_GET_KEY(leaf, key);
6693 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6696 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6697 if (op == MDB_NEXT_DUP)
6698 return MDB_NOTFOUND;
6702 DPRINTF(("cursor_next: top page is %"Yu" in cursor %p",
6703 mdb_dbg_pgno(mp), (void *) mc));
6704 if (mc->mc_flags & C_DEL) {
6705 mc->mc_flags ^= C_DEL;
6709 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
6710 DPUTS("=====> move to next sibling page");
6711 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6712 mc->mc_flags |= C_EOF;
6715 mp = mc->mc_pg[mc->mc_top];
6716 DPRINTF(("next page is %"Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6718 mc->mc_ki[mc->mc_top]++;
6721 DPRINTF(("==> cursor points to page %"Yu" with %u keys, key index %u",
6722 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6725 key->mv_size = mc->mc_db->md_pad;
6726 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6730 mdb_cassert(mc, IS_LEAF(mp));
6731 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6733 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6734 mdb_xcursor_init1(mc, leaf);
6737 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6740 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6741 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6742 if (rc != MDB_SUCCESS)
6747 MDB_GET_KEY(leaf, key);
6751 /** Move the cursor to the previous data item. */
6753 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6759 if (!(mc->mc_flags & C_INITIALIZED)) {
6760 rc = mdb_cursor_last(mc, key, data);
6763 mc->mc_ki[mc->mc_top]++;
6766 mp = mc->mc_pg[mc->mc_top];
6768 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6769 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6770 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6771 if (op == MDB_PREV || op == MDB_PREV_DUP) {
6772 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
6773 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
6774 if (rc == MDB_SUCCESS) {
6775 MDB_GET_KEY(leaf, key);
6776 mc->mc_flags &= ~C_EOF;
6782 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6785 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6786 if (op == MDB_PREV_DUP)
6787 return MDB_NOTFOUND;
6791 DPRINTF(("cursor_prev: top page is %"Yu" in cursor %p",
6792 mdb_dbg_pgno(mp), (void *) mc));
6794 mc->mc_flags &= ~(C_EOF|C_DEL);
6796 if (mc->mc_ki[mc->mc_top] == 0) {
6797 DPUTS("=====> move to prev sibling page");
6798 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
6801 mp = mc->mc_pg[mc->mc_top];
6802 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
6803 DPRINTF(("prev page is %"Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6805 mc->mc_ki[mc->mc_top]--;
6807 DPRINTF(("==> cursor points to page %"Yu" with %u keys, key index %u",
6808 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6811 key->mv_size = mc->mc_db->md_pad;
6812 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6816 mdb_cassert(mc, IS_LEAF(mp));
6817 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6819 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6820 mdb_xcursor_init1(mc, leaf);
6823 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6826 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6827 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6828 if (rc != MDB_SUCCESS)
6833 MDB_GET_KEY(leaf, key);
6837 /** Set the cursor on a specific data item. */
6839 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6840 MDB_cursor_op op, int *exactp)
6844 MDB_node *leaf = NULL;
6847 if (key->mv_size == 0)
6848 return MDB_BAD_VALSIZE;
6850 if (mc->mc_xcursor) {
6851 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6852 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6855 /* See if we're already on the right page */
6856 if (mc->mc_flags & C_INITIALIZED) {
6859 mp = mc->mc_pg[mc->mc_top];
6861 mc->mc_ki[mc->mc_top] = 0;
6862 return MDB_NOTFOUND;
6864 if (mp->mp_flags & P_LEAF2) {
6865 nodekey.mv_size = mc->mc_db->md_pad;
6866 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
6868 leaf = NODEPTR(mp, 0);
6869 MDB_GET_KEY2(leaf, nodekey);
6871 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6873 /* Probably happens rarely, but first node on the page
6874 * was the one we wanted.
6876 mc->mc_ki[mc->mc_top] = 0;
6883 unsigned int nkeys = NUMKEYS(mp);
6885 if (mp->mp_flags & P_LEAF2) {
6886 nodekey.mv_data = LEAF2KEY(mp,
6887 nkeys-1, nodekey.mv_size);
6889 leaf = NODEPTR(mp, nkeys-1);
6890 MDB_GET_KEY2(leaf, nodekey);
6892 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6894 /* last node was the one we wanted */
6895 mc->mc_ki[mc->mc_top] = nkeys-1;
6901 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
6902 /* This is definitely the right page, skip search_page */
6903 if (mp->mp_flags & P_LEAF2) {
6904 nodekey.mv_data = LEAF2KEY(mp,
6905 mc->mc_ki[mc->mc_top], nodekey.mv_size);
6907 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6908 MDB_GET_KEY2(leaf, nodekey);
6910 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6912 /* current node was the one we wanted */
6919 mc->mc_flags &= ~C_EOF;
6923 /* If any parents have right-sibs, search.
6924 * Otherwise, there's nothing further.
6926 for (i=0; i<mc->mc_top; i++)
6928 NUMKEYS(mc->mc_pg[i])-1)
6930 if (i == mc->mc_top) {
6931 /* There are no other pages */
6932 mc->mc_ki[mc->mc_top] = nkeys;
6933 return MDB_NOTFOUND;
6937 /* There are no other pages */
6938 mc->mc_ki[mc->mc_top] = 0;
6939 if (op == MDB_SET_RANGE && !exactp) {
6943 return MDB_NOTFOUND;
6949 rc = mdb_page_search(mc, key, 0);
6950 if (rc != MDB_SUCCESS)
6953 mp = mc->mc_pg[mc->mc_top];
6954 mdb_cassert(mc, IS_LEAF(mp));
6957 leaf = mdb_node_search(mc, key, exactp);
6958 if (exactp != NULL && !*exactp) {
6959 /* MDB_SET specified and not an exact match. */
6960 return MDB_NOTFOUND;
6964 DPUTS("===> inexact leaf not found, goto sibling");
6965 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6966 mc->mc_flags |= C_EOF;
6967 return rc; /* no entries matched */
6969 mp = mc->mc_pg[mc->mc_top];
6970 mdb_cassert(mc, IS_LEAF(mp));
6971 leaf = NODEPTR(mp, 0);
6975 mc->mc_flags |= C_INITIALIZED;
6976 mc->mc_flags &= ~C_EOF;
6979 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
6980 key->mv_size = mc->mc_db->md_pad;
6981 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6986 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6987 mdb_xcursor_init1(mc, leaf);
6990 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6991 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
6992 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6995 if (op == MDB_GET_BOTH) {
7001 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
7002 if (rc != MDB_SUCCESS)
7005 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
7008 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
7010 dcmp = mc->mc_dbx->md_dcmp;
7011 if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
7012 dcmp = mdb_cmp_clong;
7013 rc = dcmp(data, &olddata);
7015 if (op == MDB_GET_BOTH || rc > 0)
7016 return MDB_NOTFOUND;
7023 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
7024 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
7029 /* The key already matches in all other cases */
7030 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
7031 MDB_GET_KEY(leaf, key);
7032 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
7037 /** Move the cursor to the first item in the database. */
7039 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
7044 if (mc->mc_xcursor) {
7045 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
7046 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
7049 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
7050 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
7051 if (rc != MDB_SUCCESS)
7054 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
7056 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
7057 mc->mc_flags |= C_INITIALIZED;
7058 mc->mc_flags &= ~C_EOF;
7060 mc->mc_ki[mc->mc_top] = 0;
7062 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7063 key->mv_size = mc->mc_db->md_pad;
7064 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
7069 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7070 mdb_xcursor_init1(mc, leaf);
7071 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
7075 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
7079 MDB_GET_KEY(leaf, key);
7083 /** Move the cursor to the last item in the database. */
7085 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
7090 if (mc->mc_xcursor) {
7091 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
7092 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
7095 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
7096 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
7097 if (rc != MDB_SUCCESS)
7100 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
7102 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
7103 mc->mc_flags |= C_INITIALIZED|C_EOF;
7104 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7106 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7107 key->mv_size = mc->mc_db->md_pad;
7108 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
7113 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7114 mdb_xcursor_init1(mc, leaf);
7115 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
7119 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
7124 MDB_GET_KEY(leaf, key);
7129 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7134 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
7139 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
7143 case MDB_GET_CURRENT:
7144 if (!(mc->mc_flags & C_INITIALIZED)) {
7147 MDB_page *mp = mc->mc_pg[mc->mc_top];
7148 int nkeys = NUMKEYS(mp);
7149 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
7150 mc->mc_ki[mc->mc_top] = nkeys;
7156 key->mv_size = mc->mc_db->md_pad;
7157 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
7159 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7160 MDB_GET_KEY(leaf, key);
7162 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7163 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
7165 rc = mdb_node_read(mc, leaf, data);
7172 case MDB_GET_BOTH_RANGE:
7177 if (mc->mc_xcursor == NULL) {
7178 rc = MDB_INCOMPATIBLE;
7188 rc = mdb_cursor_set(mc, key, data, op,
7189 op == MDB_SET_RANGE ? NULL : &exact);
7192 case MDB_GET_MULTIPLE:
7193 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7197 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7198 rc = MDB_INCOMPATIBLE;
7202 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
7203 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
7206 case MDB_NEXT_MULTIPLE:
7211 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7212 rc = MDB_INCOMPATIBLE;
7215 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
7216 if (rc == MDB_SUCCESS) {
7217 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
7220 mx = &mc->mc_xcursor->mx_cursor;
7221 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
7223 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
7224 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
7230 case MDB_PREV_MULTIPLE:
7235 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7236 rc = MDB_INCOMPATIBLE;
7239 if (!(mc->mc_flags & C_INITIALIZED))
7240 rc = mdb_cursor_last(mc, key, data);
7243 if (rc == MDB_SUCCESS) {
7244 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
7245 if (mx->mc_flags & C_INITIALIZED) {
7246 rc = mdb_cursor_sibling(mx, 0);
7247 if (rc == MDB_SUCCESS)
7256 case MDB_NEXT_NODUP:
7257 rc = mdb_cursor_next(mc, key, data, op);
7261 case MDB_PREV_NODUP:
7262 rc = mdb_cursor_prev(mc, key, data, op);
7265 rc = mdb_cursor_first(mc, key, data);
7268 mfunc = mdb_cursor_first;
7270 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7274 if (mc->mc_xcursor == NULL) {
7275 rc = MDB_INCOMPATIBLE;
7278 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top])) {
7279 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7284 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7285 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7286 MDB_GET_KEY(leaf, key);
7287 rc = mdb_node_read(mc, leaf, data);
7291 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
7295 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
7298 rc = mdb_cursor_last(mc, key, data);
7301 mfunc = mdb_cursor_last;
7304 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
7309 if (mc->mc_flags & C_DEL)
7310 mc->mc_flags ^= C_DEL;
7315 /** Touch all the pages in the cursor stack. Set mc_top.
7316 * Makes sure all the pages are writable, before attempting a write operation.
7317 * @param[in] mc The cursor to operate on.
7320 mdb_cursor_touch(MDB_cursor *mc)
7322 int rc = MDB_SUCCESS;
7324 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & (DB_DIRTY|DB_DUPDATA))) {
7325 /* Touch DB record of named DB */
7328 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
7330 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
7331 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
7334 *mc->mc_dbflag |= DB_DIRTY;
7339 rc = mdb_page_touch(mc);
7340 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
7341 mc->mc_top = mc->mc_snum-1;
7346 /** Do not spill pages to disk if txn is getting full, may fail instead */
7347 #define MDB_NOSPILL 0x8000
7350 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7354 MDB_node *leaf = NULL;
7355 MDB_page *fp, *mp, *sub_root = NULL;
7357 MDB_val xdata, *rdata, dkey, olddata;
7359 int do_sub = 0, insert_key, insert_data;
7360 unsigned int mcount = 0, dcount = 0, nospill;
7363 unsigned int nflags;
7366 if (mc == NULL || key == NULL)
7369 env = mc->mc_txn->mt_env;
7371 /* Check this first so counter will always be zero on any
7374 if (flags & MDB_MULTIPLE) {
7375 dcount = data[1].mv_size;
7376 data[1].mv_size = 0;
7377 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
7378 return MDB_INCOMPATIBLE;
7381 nospill = flags & MDB_NOSPILL;
7382 flags &= ~MDB_NOSPILL;
7384 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7385 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7387 if (key->mv_size-1 >= ENV_MAXKEY(env))
7388 return MDB_BAD_VALSIZE;
7390 #if SIZE_MAX > MAXDATASIZE
7391 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
7392 return MDB_BAD_VALSIZE;
7394 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
7395 return MDB_BAD_VALSIZE;
7398 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
7399 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
7403 if (flags == MDB_CURRENT) {
7404 if (!(mc->mc_flags & C_INITIALIZED))
7407 } else if (mc->mc_db->md_root == P_INVALID) {
7408 /* new database, cursor has nothing to point to */
7411 mc->mc_flags &= ~C_INITIALIZED;
7416 if (flags & MDB_APPEND) {
7418 rc = mdb_cursor_last(mc, &k2, &d2);
7420 rc = mc->mc_dbx->md_cmp(key, &k2);
7423 mc->mc_ki[mc->mc_top]++;
7425 /* new key is <= last key */
7430 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
7432 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
7433 DPRINTF(("duplicate key [%s]", DKEY(key)));
7435 return MDB_KEYEXIST;
7437 if (rc && rc != MDB_NOTFOUND)
7441 if (mc->mc_flags & C_DEL)
7442 mc->mc_flags ^= C_DEL;
7444 /* Cursor is positioned, check for room in the dirty list */
7446 if (flags & MDB_MULTIPLE) {
7448 xdata.mv_size = data->mv_size * dcount;
7452 if ((rc2 = mdb_page_spill(mc, key, rdata)))
7456 if (rc == MDB_NO_ROOT) {
7458 /* new database, write a root leaf page */
7459 DPUTS("allocating new root leaf page");
7460 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
7463 mdb_cursor_push(mc, np);
7464 mc->mc_db->md_root = np->mp_pgno;
7465 mc->mc_db->md_depth++;
7466 *mc->mc_dbflag |= DB_DIRTY;
7467 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
7469 np->mp_flags |= P_LEAF2;
7470 mc->mc_flags |= C_INITIALIZED;
7472 /* make sure all cursor pages are writable */
7473 rc2 = mdb_cursor_touch(mc);
7478 insert_key = insert_data = rc;
7480 /* The key does not exist */
7481 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
7482 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
7483 LEAFSIZE(key, data) > env->me_nodemax)
7485 /* Too big for a node, insert in sub-DB. Set up an empty
7486 * "old sub-page" for prep_subDB to expand to a full page.
7488 fp_flags = P_LEAF|P_DIRTY;
7490 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
7491 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
7492 olddata.mv_size = PAGEHDRSZ;
7496 /* there's only a key anyway, so this is a no-op */
7497 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7499 unsigned int ksize = mc->mc_db->md_pad;
7500 if (key->mv_size != ksize)
7501 return MDB_BAD_VALSIZE;
7502 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
7503 memcpy(ptr, key->mv_data, ksize);
7505 /* if overwriting slot 0 of leaf, need to
7506 * update branch key if there is a parent page
7508 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7509 unsigned short dtop = 1;
7511 /* slot 0 is always an empty key, find real slot */
7512 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7516 if (mc->mc_ki[mc->mc_top])
7517 rc2 = mdb_update_key(mc, key);
7528 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7529 olddata.mv_size = NODEDSZ(leaf);
7530 olddata.mv_data = NODEDATA(leaf);
7533 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
7534 /* Prepare (sub-)page/sub-DB to accept the new item,
7535 * if needed. fp: old sub-page or a header faking
7536 * it. mp: new (sub-)page. offset: growth in page
7537 * size. xdata: node data with new page or DB.
7539 unsigned i, offset = 0;
7540 mp = fp = xdata.mv_data = env->me_pbuf;
7541 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
7543 /* Was a single item before, must convert now */
7544 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7546 /* Just overwrite the current item */
7547 if (flags == MDB_CURRENT)
7549 dcmp = mc->mc_dbx->md_dcmp;
7550 if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
7551 dcmp = mdb_cmp_clong;
7552 /* does data match? */
7553 if (!dcmp(data, &olddata)) {
7554 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
7555 return MDB_KEYEXIST;
7560 /* Back up original data item */
7561 dkey.mv_size = olddata.mv_size;
7562 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
7564 /* Make sub-page header for the dup items, with dummy body */
7565 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
7566 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
7567 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
7568 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7569 fp->mp_flags |= P_LEAF2;
7570 fp->mp_pad = data->mv_size;
7571 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
7573 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
7574 (dkey.mv_size & 1) + (data->mv_size & 1);
7576 fp->mp_upper = xdata.mv_size - PAGEBASE;
7577 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
7578 } else if (leaf->mn_flags & F_SUBDATA) {
7579 /* Data is on sub-DB, just store it */
7580 flags |= F_DUPDATA|F_SUBDATA;
7583 /* Data is on sub-page */
7584 fp = olddata.mv_data;
7587 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7588 offset = EVEN(NODESIZE + sizeof(indx_t) +
7592 offset = fp->mp_pad;
7593 if (SIZELEFT(fp) < offset) {
7594 offset *= 4; /* space for 4 more */
7597 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
7599 fp->mp_flags |= P_DIRTY;
7600 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
7601 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
7605 xdata.mv_size = olddata.mv_size + offset;
7608 fp_flags = fp->mp_flags;
7609 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
7610 /* Too big for a sub-page, convert to sub-DB */
7611 fp_flags &= ~P_SUBP;
7613 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7614 fp_flags |= P_LEAF2;
7615 dummy.md_pad = fp->mp_pad;
7616 dummy.md_flags = MDB_DUPFIXED;
7617 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7618 dummy.md_flags |= MDB_INTEGERKEY;
7624 dummy.md_branch_pages = 0;
7625 dummy.md_leaf_pages = 1;
7626 dummy.md_overflow_pages = 0;
7627 dummy.md_entries = NUMKEYS(fp);
7628 xdata.mv_size = sizeof(MDB_db);
7629 xdata.mv_data = &dummy;
7630 if ((rc = mdb_page_alloc(mc, 1, &mp)))
7632 offset = env->me_psize - olddata.mv_size;
7633 flags |= F_DUPDATA|F_SUBDATA;
7634 dummy.md_root = mp->mp_pgno;
7638 mp->mp_flags = fp_flags | P_DIRTY;
7639 mp->mp_pad = fp->mp_pad;
7640 mp->mp_lower = fp->mp_lower;
7641 mp->mp_upper = fp->mp_upper + offset;
7642 if (fp_flags & P_LEAF2) {
7643 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
7645 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
7646 olddata.mv_size - fp->mp_upper - PAGEBASE);
7647 for (i=0; i<NUMKEYS(fp); i++)
7648 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
7656 mdb_node_del(mc, 0);
7660 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
7661 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
7662 return MDB_INCOMPATIBLE;
7663 /* overflow page overwrites need special handling */
7664 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7667 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
7669 memcpy(&pg, olddata.mv_data, sizeof(pg));
7670 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
7672 ovpages = omp->mp_pages;
7674 /* Is the ov page large enough? */
7675 if (ovpages >= dpages) {
7676 if (!(omp->mp_flags & P_DIRTY) &&
7677 (level || (env->me_flags & MDB_WRITEMAP)))
7679 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
7682 level = 0; /* dirty in this txn or clean */
7685 if (omp->mp_flags & P_DIRTY) {
7686 /* yes, overwrite it. Note in this case we don't
7687 * bother to try shrinking the page if the new data
7688 * is smaller than the overflow threshold.
7691 /* It is writable only in a parent txn */
7692 size_t sz = (size_t) env->me_psize * ovpages, off;
7693 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
7699 /* Note - this page is already counted in parent's dirty_room */
7700 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
7701 mdb_cassert(mc, rc2 == 0);
7702 /* Currently we make the page look as with put() in the
7703 * parent txn, in case the user peeks at MDB_RESERVEd
7704 * or unused parts. Some users treat ovpages specially.
7706 if (!(flags & MDB_RESERVE)) {
7707 /* Skip the part where LMDB will put *data.
7708 * Copy end of page, adjusting alignment so
7709 * compiler may copy words instead of bytes.
7711 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
7712 memcpy((size_t *)((char *)np + off),
7713 (size_t *)((char *)omp + off), sz - off);
7716 memcpy(np, omp, sz); /* Copy beginning of page */
7719 SETDSZ(leaf, data->mv_size);
7720 if (F_ISSET(flags, MDB_RESERVE))
7721 data->mv_data = METADATA(omp);
7723 memcpy(METADATA(omp), data->mv_data, data->mv_size);
7727 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
7729 } else if (data->mv_size == olddata.mv_size) {
7730 /* same size, just replace it. Note that we could
7731 * also reuse this node if the new data is smaller,
7732 * but instead we opt to shrink the node in that case.
7734 if (F_ISSET(flags, MDB_RESERVE))
7735 data->mv_data = olddata.mv_data;
7736 else if (!(mc->mc_flags & C_SUB))
7737 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
7739 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
7744 mdb_node_del(mc, 0);
7750 nflags = flags & NODE_ADD_FLAGS;
7751 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
7752 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
7753 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
7754 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
7756 nflags |= MDB_SPLIT_REPLACE;
7757 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
7759 /* There is room already in this leaf page. */
7760 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
7762 /* Adjust other cursors pointing to mp */
7763 MDB_cursor *m2, *m3;
7764 MDB_dbi dbi = mc->mc_dbi;
7765 unsigned i = mc->mc_top;
7766 MDB_page *mp = mc->mc_pg[i];
7768 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7769 if (mc->mc_flags & C_SUB)
7770 m3 = &m2->mc_xcursor->mx_cursor;
7773 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
7774 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
7777 XCURSOR_REFRESH(m3, i, mp);
7782 if (rc == MDB_SUCCESS) {
7783 /* Now store the actual data in the child DB. Note that we're
7784 * storing the user data in the keys field, so there are strict
7785 * size limits on dupdata. The actual data fields of the child
7786 * DB are all zero size.
7789 int xflags, new_dupdata;
7794 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7795 if (flags & MDB_CURRENT) {
7796 xflags = MDB_CURRENT|MDB_NOSPILL;
7798 mdb_xcursor_init1(mc, leaf);
7799 xflags = (flags & MDB_NODUPDATA) ?
7800 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
7803 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
7804 new_dupdata = (int)dkey.mv_size;
7805 /* converted, write the original data first */
7807 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
7810 /* we've done our job */
7813 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
7814 /* Adjust other cursors pointing to mp */
7816 MDB_xcursor *mx = mc->mc_xcursor;
7817 unsigned i = mc->mc_top;
7818 MDB_page *mp = mc->mc_pg[i];
7820 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7821 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7822 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7823 if (m2->mc_pg[i] == mp) {
7824 if (m2->mc_ki[i] == mc->mc_ki[i]) {
7825 mdb_xcursor_init2(m2, mx, new_dupdata);
7826 } else if (!insert_key) {
7827 XCURSOR_REFRESH(m2, i, mp);
7832 ecount = mc->mc_xcursor->mx_db.md_entries;
7833 if (flags & MDB_APPENDDUP)
7834 xflags |= MDB_APPEND;
7835 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
7836 if (flags & F_SUBDATA) {
7837 void *db = NODEDATA(leaf);
7838 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7840 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
7842 /* Increment count unless we just replaced an existing item. */
7844 mc->mc_db->md_entries++;
7846 /* Invalidate txn if we created an empty sub-DB */
7849 /* If we succeeded and the key didn't exist before,
7850 * make sure the cursor is marked valid.
7852 mc->mc_flags |= C_INITIALIZED;
7854 if (flags & MDB_MULTIPLE) {
7857 /* let caller know how many succeeded, if any */
7858 data[1].mv_size = mcount;
7859 if (mcount < dcount) {
7860 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
7861 insert_key = insert_data = 0;
7868 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
7871 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7876 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
7882 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7883 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7885 if (!(mc->mc_flags & C_INITIALIZED))
7888 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
7889 return MDB_NOTFOUND;
7891 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
7894 rc = mdb_cursor_touch(mc);
7898 mp = mc->mc_pg[mc->mc_top];
7901 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7903 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7904 if (flags & MDB_NODUPDATA) {
7905 /* mdb_cursor_del0() will subtract the final entry */
7906 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
7907 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7909 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
7910 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7912 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
7915 /* If sub-DB still has entries, we're done */
7916 if (mc->mc_xcursor->mx_db.md_entries) {
7917 if (leaf->mn_flags & F_SUBDATA) {
7918 /* update subDB info */
7919 void *db = NODEDATA(leaf);
7920 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7923 /* shrink fake page */
7924 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
7925 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7926 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7927 /* fix other sub-DB cursors pointed at fake pages on this page */
7928 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7929 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7930 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7931 if (m2->mc_pg[mc->mc_top] == mp) {
7932 XCURSOR_REFRESH(m2, mc->mc_top, mp);
7936 mc->mc_db->md_entries--;
7939 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7941 /* otherwise fall thru and delete the sub-DB */
7944 if (leaf->mn_flags & F_SUBDATA) {
7945 /* add all the child DB's pages to the free list */
7946 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7951 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
7952 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
7953 rc = MDB_INCOMPATIBLE;
7957 /* add overflow pages to free list */
7958 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7962 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7963 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
7964 (rc = mdb_ovpage_free(mc, omp)))
7969 return mdb_cursor_del0(mc);
7972 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7976 /** Allocate and initialize new pages for a database.
7977 * Set #MDB_TXN_ERROR on failure.
7978 * @param[in] mc a cursor on the database being added to.
7979 * @param[in] flags flags defining what type of page is being allocated.
7980 * @param[in] num the number of pages to allocate. This is usually 1,
7981 * unless allocating overflow pages for a large record.
7982 * @param[out] mp Address of a page, or NULL on failure.
7983 * @return 0 on success, non-zero on failure.
7986 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
7991 if ((rc = mdb_page_alloc(mc, num, &np)))
7993 DPRINTF(("allocated new mpage %"Yu", page size %u",
7994 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
7995 np->mp_flags = flags | P_DIRTY;
7996 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
7997 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
8000 mc->mc_db->md_branch_pages++;
8001 else if (IS_LEAF(np))
8002 mc->mc_db->md_leaf_pages++;
8003 else if (IS_OVERFLOW(np)) {
8004 mc->mc_db->md_overflow_pages += num;
8012 /** Calculate the size of a leaf node.
8013 * The size depends on the environment's page size; if a data item
8014 * is too large it will be put onto an overflow page and the node
8015 * size will only include the key and not the data. Sizes are always
8016 * rounded up to an even number of bytes, to guarantee 2-byte alignment
8017 * of the #MDB_node headers.
8018 * @param[in] env The environment handle.
8019 * @param[in] key The key for the node.
8020 * @param[in] data The data for the node.
8021 * @return The number of bytes needed to store the node.
8024 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
8028 sz = LEAFSIZE(key, data);
8029 if (sz > env->me_nodemax) {
8030 /* put on overflow page */
8031 sz -= data->mv_size - sizeof(pgno_t);
8034 return EVEN(sz + sizeof(indx_t));
8037 /** Calculate the size of a branch node.
8038 * The size should depend on the environment's page size but since
8039 * we currently don't support spilling large keys onto overflow
8040 * pages, it's simply the size of the #MDB_node header plus the
8041 * size of the key. Sizes are always rounded up to an even number
8042 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
8043 * @param[in] env The environment handle.
8044 * @param[in] key The key for the node.
8045 * @return The number of bytes needed to store the node.
8048 mdb_branch_size(MDB_env *env, MDB_val *key)
8053 if (sz > env->me_nodemax) {
8054 /* put on overflow page */
8055 /* not implemented */
8056 /* sz -= key->size - sizeof(pgno_t); */
8059 return sz + sizeof(indx_t);
8062 /** Add a node to the page pointed to by the cursor.
8063 * Set #MDB_TXN_ERROR on failure.
8064 * @param[in] mc The cursor for this operation.
8065 * @param[in] indx The index on the page where the new node should be added.
8066 * @param[in] key The key for the new node.
8067 * @param[in] data The data for the new node, if any.
8068 * @param[in] pgno The page number, if adding a branch node.
8069 * @param[in] flags Flags for the node.
8070 * @return 0 on success, non-zero on failure. Possible errors are:
8072 * <li>ENOMEM - failed to allocate overflow pages for the node.
8073 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
8074 * should never happen since all callers already calculate the
8075 * page's free space before calling this function.
8079 mdb_node_add(MDB_cursor *mc, indx_t indx,
8080 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
8083 size_t node_size = NODESIZE;
8087 MDB_page *mp = mc->mc_pg[mc->mc_top];
8088 MDB_page *ofp = NULL; /* overflow page */
8092 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
8094 DPRINTF(("add to %s %spage %"Yu" index %i, data size %"Z"u key size %"Z"u [%s]",
8095 IS_LEAF(mp) ? "leaf" : "branch",
8096 IS_SUBP(mp) ? "sub-" : "",
8097 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
8098 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
8101 /* Move higher keys up one slot. */
8102 int ksize = mc->mc_db->md_pad, dif;
8103 char *ptr = LEAF2KEY(mp, indx, ksize);
8104 dif = NUMKEYS(mp) - indx;
8106 memmove(ptr+ksize, ptr, dif*ksize);
8107 /* insert new key */
8108 memcpy(ptr, key->mv_data, ksize);
8110 /* Just using these for counting */
8111 mp->mp_lower += sizeof(indx_t);
8112 mp->mp_upper -= ksize - sizeof(indx_t);
8116 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
8118 node_size += key->mv_size;
8120 mdb_cassert(mc, key && data);
8121 if (F_ISSET(flags, F_BIGDATA)) {
8122 /* Data already on overflow page. */
8123 node_size += sizeof(pgno_t);
8124 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
8125 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
8127 /* Put data on overflow page. */
8128 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
8129 data->mv_size, node_size+data->mv_size));
8130 node_size = EVEN(node_size + sizeof(pgno_t));
8131 if ((ssize_t)node_size > room)
8133 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
8135 DPRINTF(("allocated overflow page %"Yu, ofp->mp_pgno));
8139 node_size += data->mv_size;
8142 node_size = EVEN(node_size);
8143 if ((ssize_t)node_size > room)
8147 /* Move higher pointers up one slot. */
8148 for (i = NUMKEYS(mp); i > indx; i--)
8149 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
8151 /* Adjust free space offsets. */
8152 ofs = mp->mp_upper - node_size;
8153 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
8154 mp->mp_ptrs[indx] = ofs;
8156 mp->mp_lower += sizeof(indx_t);
8158 /* Write the node data. */
8159 node = NODEPTR(mp, indx);
8160 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
8161 node->mn_flags = flags;
8163 SETDSZ(node,data->mv_size);
8168 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8171 ndata = NODEDATA(node);
8173 if (F_ISSET(flags, F_BIGDATA))
8174 memcpy(ndata, data->mv_data, sizeof(pgno_t));
8175 else if (F_ISSET(flags, MDB_RESERVE))
8176 data->mv_data = ndata;
8178 memcpy(ndata, data->mv_data, data->mv_size);
8180 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
8181 ndata = METADATA(ofp);
8182 if (F_ISSET(flags, MDB_RESERVE))
8183 data->mv_data = ndata;
8185 memcpy(ndata, data->mv_data, data->mv_size);
8192 DPRINTF(("not enough room in page %"Yu", got %u ptrs",
8193 mdb_dbg_pgno(mp), NUMKEYS(mp)));
8194 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
8195 DPRINTF(("node size = %"Z"u", node_size));
8196 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8197 return MDB_PAGE_FULL;
8200 /** Delete the specified node from a page.
8201 * @param[in] mc Cursor pointing to the node to delete.
8202 * @param[in] ksize The size of a node. Only used if the page is
8203 * part of a #MDB_DUPFIXED database.
8206 mdb_node_del(MDB_cursor *mc, int ksize)
8208 MDB_page *mp = mc->mc_pg[mc->mc_top];
8209 indx_t indx = mc->mc_ki[mc->mc_top];
8211 indx_t i, j, numkeys, ptr;
8215 DPRINTF(("delete node %u on %s page %"Yu, indx,
8216 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
8217 numkeys = NUMKEYS(mp);
8218 mdb_cassert(mc, indx < numkeys);
8221 int x = numkeys - 1 - indx;
8222 base = LEAF2KEY(mp, indx, ksize);
8224 memmove(base, base + ksize, x * ksize);
8225 mp->mp_lower -= sizeof(indx_t);
8226 mp->mp_upper += ksize - sizeof(indx_t);
8230 node = NODEPTR(mp, indx);
8231 sz = NODESIZE + node->mn_ksize;
8233 if (F_ISSET(node->mn_flags, F_BIGDATA))
8234 sz += sizeof(pgno_t);
8236 sz += NODEDSZ(node);
8240 ptr = mp->mp_ptrs[indx];
8241 for (i = j = 0; i < numkeys; i++) {
8243 mp->mp_ptrs[j] = mp->mp_ptrs[i];
8244 if (mp->mp_ptrs[i] < ptr)
8245 mp->mp_ptrs[j] += sz;
8250 base = (char *)mp + mp->mp_upper + PAGEBASE;
8251 memmove(base + sz, base, ptr - mp->mp_upper);
8253 mp->mp_lower -= sizeof(indx_t);
8257 /** Compact the main page after deleting a node on a subpage.
8258 * @param[in] mp The main page to operate on.
8259 * @param[in] indx The index of the subpage on the main page.
8262 mdb_node_shrink(MDB_page *mp, indx_t indx)
8267 indx_t delta, nsize, len, ptr;
8270 node = NODEPTR(mp, indx);
8271 sp = (MDB_page *)NODEDATA(node);
8272 delta = SIZELEFT(sp);
8273 nsize = NODEDSZ(node) - delta;
8275 /* Prepare to shift upward, set len = length(subpage part to shift) */
8279 return; /* do not make the node uneven-sized */
8281 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
8282 for (i = NUMKEYS(sp); --i >= 0; )
8283 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
8286 sp->mp_upper = sp->mp_lower;
8287 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
8288 SETDSZ(node, nsize);
8290 /* Shift <lower nodes...initial part of subpage> upward */
8291 base = (char *)mp + mp->mp_upper + PAGEBASE;
8292 memmove(base + delta, base, (char *)sp + len - base);
8294 ptr = mp->mp_ptrs[indx];
8295 for (i = NUMKEYS(mp); --i >= 0; ) {
8296 if (mp->mp_ptrs[i] <= ptr)
8297 mp->mp_ptrs[i] += delta;
8299 mp->mp_upper += delta;
8302 /** Initial setup of a sorted-dups cursor.
8303 * Sorted duplicates are implemented as a sub-database for the given key.
8304 * The duplicate data items are actually keys of the sub-database.
8305 * Operations on the duplicate data items are performed using a sub-cursor
8306 * initialized when the sub-database is first accessed. This function does
8307 * the preliminary setup of the sub-cursor, filling in the fields that
8308 * depend only on the parent DB.
8309 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8312 mdb_xcursor_init0(MDB_cursor *mc)
8314 MDB_xcursor *mx = mc->mc_xcursor;
8316 mx->mx_cursor.mc_xcursor = NULL;
8317 mx->mx_cursor.mc_txn = mc->mc_txn;
8318 mx->mx_cursor.mc_db = &mx->mx_db;
8319 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
8320 mx->mx_cursor.mc_dbi = mc->mc_dbi;
8321 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
8322 mx->mx_cursor.mc_snum = 0;
8323 mx->mx_cursor.mc_top = 0;
8324 MC_SET_OVPG(&mx->mx_cursor, NULL);
8325 mx->mx_cursor.mc_flags = C_SUB | (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP));
8326 mx->mx_dbx.md_name.mv_size = 0;
8327 mx->mx_dbx.md_name.mv_data = NULL;
8328 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
8329 mx->mx_dbx.md_dcmp = NULL;
8330 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
8333 /** Final setup of a sorted-dups cursor.
8334 * Sets up the fields that depend on the data from the main cursor.
8335 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8336 * @param[in] node The data containing the #MDB_db record for the
8337 * sorted-dup database.
8340 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
8342 MDB_xcursor *mx = mc->mc_xcursor;
8344 mx->mx_cursor.mc_flags &= C_SUB|C_ORIG_RDONLY|C_WRITEMAP;
8345 if (node->mn_flags & F_SUBDATA) {
8346 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
8347 mx->mx_cursor.mc_pg[0] = 0;
8348 mx->mx_cursor.mc_snum = 0;
8349 mx->mx_cursor.mc_top = 0;
8351 MDB_page *fp = NODEDATA(node);
8352 mx->mx_db.md_pad = 0;
8353 mx->mx_db.md_flags = 0;
8354 mx->mx_db.md_depth = 1;
8355 mx->mx_db.md_branch_pages = 0;
8356 mx->mx_db.md_leaf_pages = 1;
8357 mx->mx_db.md_overflow_pages = 0;
8358 mx->mx_db.md_entries = NUMKEYS(fp);
8359 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
8360 mx->mx_cursor.mc_snum = 1;
8361 mx->mx_cursor.mc_top = 0;
8362 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8363 mx->mx_cursor.mc_pg[0] = fp;
8364 mx->mx_cursor.mc_ki[0] = 0;
8365 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
8366 mx->mx_db.md_flags = MDB_DUPFIXED;
8367 mx->mx_db.md_pad = fp->mp_pad;
8368 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
8369 mx->mx_db.md_flags |= MDB_INTEGERKEY;
8372 DPRINTF(("Sub-db -%u root page %"Yu, mx->mx_cursor.mc_dbi,
8373 mx->mx_db.md_root));
8374 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
8375 if (NEED_CMP_CLONG(mx->mx_dbx.md_cmp, mx->mx_db.md_pad))
8376 mx->mx_dbx.md_cmp = mdb_cmp_clong;
8380 /** Fixup a sorted-dups cursor due to underlying update.
8381 * Sets up some fields that depend on the data from the main cursor.
8382 * Almost the same as init1, but skips initialization steps if the
8383 * xcursor had already been used.
8384 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
8385 * @param[in] src_mx The xcursor of an up-to-date cursor.
8386 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
8389 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
8391 MDB_xcursor *mx = mc->mc_xcursor;
8394 mx->mx_cursor.mc_snum = 1;
8395 mx->mx_cursor.mc_top = 0;
8396 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8397 mx->mx_cursor.mc_ki[0] = 0;
8398 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
8399 #if UINT_MAX < MDB_SIZE_MAX /* matches mdb_xcursor_init1:NEED_CMP_CLONG() */
8400 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
8402 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
8405 mx->mx_db = src_mx->mx_db;
8406 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
8407 DPRINTF(("Sub-db -%u root page %"Yu, mx->mx_cursor.mc_dbi,
8408 mx->mx_db.md_root));
8411 /** Initialize a cursor for a given transaction and database. */
8413 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
8416 mc->mc_backup = NULL;
8419 mc->mc_db = &txn->mt_dbs[dbi];
8420 mc->mc_dbx = &txn->mt_dbxs[dbi];
8421 mc->mc_dbflag = &txn->mt_dbflags[dbi];
8426 MC_SET_OVPG(mc, NULL);
8427 mc->mc_flags = txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
8428 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
8429 mdb_tassert(txn, mx != NULL);
8430 mc->mc_xcursor = mx;
8431 mdb_xcursor_init0(mc);
8433 mc->mc_xcursor = NULL;
8435 if (*mc->mc_dbflag & DB_STALE) {
8436 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
8441 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
8444 size_t size = sizeof(MDB_cursor);
8446 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
8449 if (txn->mt_flags & MDB_TXN_BLOCKED)
8452 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8455 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
8456 size += sizeof(MDB_xcursor);
8458 if ((mc = malloc(size)) != NULL) {
8459 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
8460 if (txn->mt_cursors) {
8461 mc->mc_next = txn->mt_cursors[dbi];
8462 txn->mt_cursors[dbi] = mc;
8463 mc->mc_flags |= C_UNTRACK;
8475 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
8477 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
8480 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
8483 if (txn->mt_flags & MDB_TXN_BLOCKED)
8486 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
8490 /* Return the count of duplicate data items for the current key */
8492 mdb_cursor_count(MDB_cursor *mc, mdb_size_t *countp)
8496 if (mc == NULL || countp == NULL)
8499 if (mc->mc_xcursor == NULL)
8500 return MDB_INCOMPATIBLE;
8502 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
8505 if (!(mc->mc_flags & C_INITIALIZED))
8509 return MDB_NOTFOUND;
8511 if (mc->mc_flags & C_EOF) {
8512 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
8513 return MDB_NOTFOUND;
8514 mc->mc_flags ^= C_EOF;
8517 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8518 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
8521 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
8524 *countp = mc->mc_xcursor->mx_db.md_entries;
8530 mdb_cursor_close(MDB_cursor *mc)
8533 MDB_CURSOR_UNREF(mc, 0);
8535 if (mc && !mc->mc_backup) {
8536 /* Remove from txn, if tracked.
8537 * A read-only txn (!C_UNTRACK) may have been freed already,
8538 * so do not peek inside it. Only write txns track cursors.
8540 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
8541 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
8542 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
8544 *prev = mc->mc_next;
8551 mdb_cursor_txn(MDB_cursor *mc)
8553 if (!mc) return NULL;
8558 mdb_cursor_dbi(MDB_cursor *mc)
8563 /** Replace the key for a branch node with a new key.
8564 * Set #MDB_TXN_ERROR on failure.
8565 * @param[in] mc Cursor pointing to the node to operate on.
8566 * @param[in] key The new key to use.
8567 * @return 0 on success, non-zero on failure.
8570 mdb_update_key(MDB_cursor *mc, MDB_val *key)
8576 int delta, ksize, oksize;
8577 indx_t ptr, i, numkeys, indx;
8580 indx = mc->mc_ki[mc->mc_top];
8581 mp = mc->mc_pg[mc->mc_top];
8582 node = NODEPTR(mp, indx);
8583 ptr = mp->mp_ptrs[indx];
8587 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
8588 k2.mv_data = NODEKEY(node);
8589 k2.mv_size = node->mn_ksize;
8590 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Yu,
8592 mdb_dkey(&k2, kbuf2),
8598 /* Sizes must be 2-byte aligned. */
8599 ksize = EVEN(key->mv_size);
8600 oksize = EVEN(node->mn_ksize);
8601 delta = ksize - oksize;
8603 /* Shift node contents if EVEN(key length) changed. */
8605 if (delta > 0 && SIZELEFT(mp) < delta) {
8607 /* not enough space left, do a delete and split */
8608 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
8609 pgno = NODEPGNO(node);
8610 mdb_node_del(mc, 0);
8611 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
8614 numkeys = NUMKEYS(mp);
8615 for (i = 0; i < numkeys; i++) {
8616 if (mp->mp_ptrs[i] <= ptr)
8617 mp->mp_ptrs[i] -= delta;
8620 base = (char *)mp + mp->mp_upper + PAGEBASE;
8621 len = ptr - mp->mp_upper + NODESIZE;
8622 memmove(base - delta, base, len);
8623 mp->mp_upper -= delta;
8625 node = NODEPTR(mp, indx);
8628 /* But even if no shift was needed, update ksize */
8629 if (node->mn_ksize != key->mv_size)
8630 node->mn_ksize = key->mv_size;
8633 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8639 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
8641 /** Perform \b act while tracking temporary cursor \b mn */
8642 #define WITH_CURSOR_TRACKING(mn, act) do { \
8643 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
8644 if ((mn).mc_flags & C_SUB) { \
8645 dummy.mc_flags = C_INITIALIZED; \
8646 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
8651 tracked->mc_next = *tp; \
8654 *tp = tracked->mc_next; \
8657 /** Move a node from csrc to cdst.
8660 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
8667 unsigned short flags;
8671 /* Mark src and dst as dirty. */
8672 if ((rc = mdb_page_touch(csrc)) ||
8673 (rc = mdb_page_touch(cdst)))
8676 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8677 key.mv_size = csrc->mc_db->md_pad;
8678 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
8680 data.mv_data = NULL;
8684 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
8685 mdb_cassert(csrc, !((size_t)srcnode & 1));
8686 srcpg = NODEPGNO(srcnode);
8687 flags = srcnode->mn_flags;
8688 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8689 unsigned int snum = csrc->mc_snum;
8691 /* must find the lowest key below src */
8692 rc = mdb_page_search_lowest(csrc);
8695 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8696 key.mv_size = csrc->mc_db->md_pad;
8697 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8699 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8700 key.mv_size = NODEKSZ(s2);
8701 key.mv_data = NODEKEY(s2);
8703 csrc->mc_snum = snum--;
8704 csrc->mc_top = snum;
8706 key.mv_size = NODEKSZ(srcnode);
8707 key.mv_data = NODEKEY(srcnode);
8709 data.mv_size = NODEDSZ(srcnode);
8710 data.mv_data = NODEDATA(srcnode);
8712 mn.mc_xcursor = NULL;
8713 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
8714 unsigned int snum = cdst->mc_snum;
8717 /* must find the lowest key below dst */
8718 mdb_cursor_copy(cdst, &mn);
8719 rc = mdb_page_search_lowest(&mn);
8722 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8723 bkey.mv_size = mn.mc_db->md_pad;
8724 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
8726 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8727 bkey.mv_size = NODEKSZ(s2);
8728 bkey.mv_data = NODEKEY(s2);
8730 mn.mc_snum = snum--;
8733 rc = mdb_update_key(&mn, &bkey);
8738 DPRINTF(("moving %s node %u [%s] on page %"Yu" to node %u on page %"Yu,
8739 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
8740 csrc->mc_ki[csrc->mc_top],
8742 csrc->mc_pg[csrc->mc_top]->mp_pgno,
8743 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
8745 /* Add the node to the destination page.
8747 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
8748 if (rc != MDB_SUCCESS)
8751 /* Delete the node from the source page.
8753 mdb_node_del(csrc, key.mv_size);
8756 /* Adjust other cursors pointing to mp */
8757 MDB_cursor *m2, *m3;
8758 MDB_dbi dbi = csrc->mc_dbi;
8759 MDB_page *mpd, *mps;
8761 mps = csrc->mc_pg[csrc->mc_top];
8762 /* If we're adding on the left, bump others up */
8764 mpd = cdst->mc_pg[csrc->mc_top];
8765 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8766 if (csrc->mc_flags & C_SUB)
8767 m3 = &m2->mc_xcursor->mx_cursor;
8770 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8773 m3->mc_pg[csrc->mc_top] == mpd &&
8774 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
8775 m3->mc_ki[csrc->mc_top]++;
8778 m3->mc_pg[csrc->mc_top] == mps &&
8779 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
8780 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8781 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8782 m3->mc_ki[csrc->mc_top-1]++;
8785 XCURSOR_REFRESH(m3, csrc->mc_top, m3->mc_pg[csrc->mc_top]);
8788 /* Adding on the right, bump others down */
8790 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8791 if (csrc->mc_flags & C_SUB)
8792 m3 = &m2->mc_xcursor->mx_cursor;
8795 if (m3 == csrc) continue;
8796 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8798 if (m3->mc_pg[csrc->mc_top] == mps) {
8799 if (!m3->mc_ki[csrc->mc_top]) {
8800 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8801 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8802 m3->mc_ki[csrc->mc_top-1]--;
8804 m3->mc_ki[csrc->mc_top]--;
8807 XCURSOR_REFRESH(m3, csrc->mc_top, m3->mc_pg[csrc->mc_top]);
8813 /* Update the parent separators.
8815 if (csrc->mc_ki[csrc->mc_top] == 0) {
8816 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
8817 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8818 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8820 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8821 key.mv_size = NODEKSZ(srcnode);
8822 key.mv_data = NODEKEY(srcnode);
8824 DPRINTF(("update separator for source page %"Yu" to [%s]",
8825 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
8826 mdb_cursor_copy(csrc, &mn);
8829 /* We want mdb_rebalance to find mn when doing fixups */
8830 WITH_CURSOR_TRACKING(mn,
8831 rc = mdb_update_key(&mn, &key));
8835 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8837 indx_t ix = csrc->mc_ki[csrc->mc_top];
8838 nullkey.mv_size = 0;
8839 csrc->mc_ki[csrc->mc_top] = 0;
8840 rc = mdb_update_key(csrc, &nullkey);
8841 csrc->mc_ki[csrc->mc_top] = ix;
8842 mdb_cassert(csrc, rc == MDB_SUCCESS);
8846 if (cdst->mc_ki[cdst->mc_top] == 0) {
8847 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
8848 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8849 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
8851 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
8852 key.mv_size = NODEKSZ(srcnode);
8853 key.mv_data = NODEKEY(srcnode);
8855 DPRINTF(("update separator for destination page %"Yu" to [%s]",
8856 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
8857 mdb_cursor_copy(cdst, &mn);
8860 /* We want mdb_rebalance to find mn when doing fixups */
8861 WITH_CURSOR_TRACKING(mn,
8862 rc = mdb_update_key(&mn, &key));
8866 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
8868 indx_t ix = cdst->mc_ki[cdst->mc_top];
8869 nullkey.mv_size = 0;
8870 cdst->mc_ki[cdst->mc_top] = 0;
8871 rc = mdb_update_key(cdst, &nullkey);
8872 cdst->mc_ki[cdst->mc_top] = ix;
8873 mdb_cassert(cdst, rc == MDB_SUCCESS);
8880 /** Merge one page into another.
8881 * The nodes from the page pointed to by \b csrc will
8882 * be copied to the page pointed to by \b cdst and then
8883 * the \b csrc page will be freed.
8884 * @param[in] csrc Cursor pointing to the source page.
8885 * @param[in] cdst Cursor pointing to the destination page.
8886 * @return 0 on success, non-zero on failure.
8889 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
8891 MDB_page *psrc, *pdst;
8898 psrc = csrc->mc_pg[csrc->mc_top];
8899 pdst = cdst->mc_pg[cdst->mc_top];
8901 DPRINTF(("merging page %"Yu" into %"Yu, psrc->mp_pgno, pdst->mp_pgno));
8903 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
8904 mdb_cassert(csrc, cdst->mc_snum > 1);
8906 /* Mark dst as dirty. */
8907 if ((rc = mdb_page_touch(cdst)))
8910 /* get dst page again now that we've touched it. */
8911 pdst = cdst->mc_pg[cdst->mc_top];
8913 /* Move all nodes from src to dst.
8915 j = nkeys = NUMKEYS(pdst);
8916 if (IS_LEAF2(psrc)) {
8917 key.mv_size = csrc->mc_db->md_pad;
8918 key.mv_data = METADATA(psrc);
8919 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8920 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
8921 if (rc != MDB_SUCCESS)
8923 key.mv_data = (char *)key.mv_data + key.mv_size;
8926 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8927 srcnode = NODEPTR(psrc, i);
8928 if (i == 0 && IS_BRANCH(psrc)) {
8931 mdb_cursor_copy(csrc, &mn);
8932 mn.mc_xcursor = NULL;
8933 /* must find the lowest key below src */
8934 rc = mdb_page_search_lowest(&mn);
8937 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8938 key.mv_size = mn.mc_db->md_pad;
8939 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
8941 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8942 key.mv_size = NODEKSZ(s2);
8943 key.mv_data = NODEKEY(s2);
8946 key.mv_size = srcnode->mn_ksize;
8947 key.mv_data = NODEKEY(srcnode);
8950 data.mv_size = NODEDSZ(srcnode);
8951 data.mv_data = NODEDATA(srcnode);
8952 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
8953 if (rc != MDB_SUCCESS)
8958 DPRINTF(("dst page %"Yu" now has %u keys (%.1f%% filled)",
8959 pdst->mp_pgno, NUMKEYS(pdst),
8960 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
8962 /* Unlink the src page from parent and add to free list.
8965 mdb_node_del(csrc, 0);
8966 if (csrc->mc_ki[csrc->mc_top] == 0) {
8968 rc = mdb_update_key(csrc, &key);
8976 psrc = csrc->mc_pg[csrc->mc_top];
8977 /* If not operating on FreeDB, allow this page to be reused
8978 * in this txn. Otherwise just add to free list.
8980 rc = mdb_page_loose(csrc, psrc);
8984 csrc->mc_db->md_leaf_pages--;
8986 csrc->mc_db->md_branch_pages--;
8988 /* Adjust other cursors pointing to mp */
8989 MDB_cursor *m2, *m3;
8990 MDB_dbi dbi = csrc->mc_dbi;
8991 unsigned int top = csrc->mc_top;
8993 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8994 if (csrc->mc_flags & C_SUB)
8995 m3 = &m2->mc_xcursor->mx_cursor;
8998 if (m3 == csrc) continue;
8999 if (m3->mc_snum < csrc->mc_snum) continue;
9000 if (m3->mc_pg[top] == psrc) {
9001 m3->mc_pg[top] = pdst;
9002 m3->mc_ki[top] += nkeys;
9003 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
9004 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
9005 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
9009 XCURSOR_REFRESH(m3, top, m3->mc_pg[top]);
9013 unsigned int snum = cdst->mc_snum;
9014 uint16_t depth = cdst->mc_db->md_depth;
9015 mdb_cursor_pop(cdst);
9016 rc = mdb_rebalance(cdst);
9017 /* Did the tree height change? */
9018 if (depth != cdst->mc_db->md_depth)
9019 snum += cdst->mc_db->md_depth - depth;
9020 cdst->mc_snum = snum;
9021 cdst->mc_top = snum-1;
9026 /** Copy the contents of a cursor.
9027 * @param[in] csrc The cursor to copy from.
9028 * @param[out] cdst The cursor to copy to.
9031 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
9035 cdst->mc_txn = csrc->mc_txn;
9036 cdst->mc_dbi = csrc->mc_dbi;
9037 cdst->mc_db = csrc->mc_db;
9038 cdst->mc_dbx = csrc->mc_dbx;
9039 cdst->mc_snum = csrc->mc_snum;
9040 cdst->mc_top = csrc->mc_top;
9041 cdst->mc_flags = csrc->mc_flags;
9042 MC_SET_OVPG(cdst, MC_OVPG(csrc));
9044 for (i=0; i<csrc->mc_snum; i++) {
9045 cdst->mc_pg[i] = csrc->mc_pg[i];
9046 cdst->mc_ki[i] = csrc->mc_ki[i];
9050 /** Rebalance the tree after a delete operation.
9051 * @param[in] mc Cursor pointing to the page where rebalancing
9053 * @return 0 on success, non-zero on failure.
9056 mdb_rebalance(MDB_cursor *mc)
9060 unsigned int ptop, minkeys, thresh;
9064 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
9069 thresh = FILL_THRESHOLD;
9071 DPRINTF(("rebalancing %s page %"Yu" (has %u keys, %.1f%% full)",
9072 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
9073 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
9074 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
9076 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
9077 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
9078 DPRINTF(("no need to rebalance page %"Yu", above fill threshold",
9079 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
9083 if (mc->mc_snum < 2) {
9084 MDB_page *mp = mc->mc_pg[0];
9086 DPUTS("Can't rebalance a subpage, ignoring");
9089 if (NUMKEYS(mp) == 0) {
9090 DPUTS("tree is completely empty");
9091 mc->mc_db->md_root = P_INVALID;
9092 mc->mc_db->md_depth = 0;
9093 mc->mc_db->md_leaf_pages = 0;
9094 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
9097 /* Adjust cursors pointing to mp */
9100 mc->mc_flags &= ~C_INITIALIZED;
9102 MDB_cursor *m2, *m3;
9103 MDB_dbi dbi = mc->mc_dbi;
9105 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9106 if (mc->mc_flags & C_SUB)
9107 m3 = &m2->mc_xcursor->mx_cursor;
9110 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
9112 if (m3->mc_pg[0] == mp) {
9115 m3->mc_flags &= ~C_INITIALIZED;
9119 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
9121 DPUTS("collapsing root page!");
9122 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
9125 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
9126 rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
9129 mc->mc_db->md_depth--;
9130 mc->mc_db->md_branch_pages--;
9131 mc->mc_ki[0] = mc->mc_ki[1];
9132 for (i = 1; i<mc->mc_db->md_depth; i++) {
9133 mc->mc_pg[i] = mc->mc_pg[i+1];
9134 mc->mc_ki[i] = mc->mc_ki[i+1];
9137 /* Adjust other cursors pointing to mp */
9138 MDB_cursor *m2, *m3;
9139 MDB_dbi dbi = mc->mc_dbi;
9141 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9142 if (mc->mc_flags & C_SUB)
9143 m3 = &m2->mc_xcursor->mx_cursor;
9146 if (m3 == mc) continue;
9147 if (!(m3->mc_flags & C_INITIALIZED))
9149 if (m3->mc_pg[0] == mp) {
9150 for (i=0; i<mc->mc_db->md_depth; i++) {
9151 m3->mc_pg[i] = m3->mc_pg[i+1];
9152 m3->mc_ki[i] = m3->mc_ki[i+1];
9160 DPUTS("root page doesn't need rebalancing");
9164 /* The parent (branch page) must have at least 2 pointers,
9165 * otherwise the tree is invalid.
9167 ptop = mc->mc_top-1;
9168 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
9170 /* Leaf page fill factor is below the threshold.
9171 * Try to move keys from left or right neighbor, or
9172 * merge with a neighbor page.
9177 mdb_cursor_copy(mc, &mn);
9178 mn.mc_xcursor = NULL;
9180 oldki = mc->mc_ki[mc->mc_top];
9181 if (mc->mc_ki[ptop] == 0) {
9182 /* We're the leftmost leaf in our parent.
9184 DPUTS("reading right neighbor");
9186 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
9187 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
9190 mn.mc_ki[mn.mc_top] = 0;
9191 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
9194 /* There is at least one neighbor to the left.
9196 DPUTS("reading left neighbor");
9198 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
9199 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
9202 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
9203 mc->mc_ki[mc->mc_top] = 0;
9207 DPRINTF(("found neighbor page %"Yu" (%u keys, %.1f%% full)",
9208 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
9209 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
9211 /* If the neighbor page is above threshold and has enough keys,
9212 * move one key from it. Otherwise we should try to merge them.
9213 * (A branch page must never have less than 2 keys.)
9215 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
9216 rc = mdb_node_move(&mn, mc, fromleft);
9218 /* if we inserted on left, bump position up */
9223 rc = mdb_page_merge(&mn, mc);
9225 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
9226 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
9227 /* We want mdb_rebalance to find mn when doing fixups */
9228 WITH_CURSOR_TRACKING(mn,
9229 rc = mdb_page_merge(mc, &mn));
9230 mdb_cursor_copy(&mn, mc);
9232 mc->mc_flags &= ~C_EOF;
9234 mc->mc_ki[mc->mc_top] = oldki;
9238 /** Complete a delete operation started by #mdb_cursor_del(). */
9240 mdb_cursor_del0(MDB_cursor *mc)
9246 MDB_cursor *m2, *m3;
9247 MDB_dbi dbi = mc->mc_dbi;
9249 ki = mc->mc_ki[mc->mc_top];
9250 mp = mc->mc_pg[mc->mc_top];
9251 mdb_node_del(mc, mc->mc_db->md_pad);
9252 mc->mc_db->md_entries--;
9254 /* Adjust other cursors pointing to mp */
9255 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9256 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9257 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9259 if (m3 == mc || m3->mc_snum < mc->mc_snum)
9261 if (m3->mc_pg[mc->mc_top] == mp) {
9262 if (m3->mc_ki[mc->mc_top] == ki) {
9263 m3->mc_flags |= C_DEL;
9264 if (mc->mc_db->md_flags & MDB_DUPSORT) {
9265 /* Sub-cursor referred into dataset which is gone */
9266 m3->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
9269 } else if (m3->mc_ki[mc->mc_top] > ki) {
9270 m3->mc_ki[mc->mc_top]--;
9272 XCURSOR_REFRESH(m3, mc->mc_top, mp);
9276 rc = mdb_rebalance(mc);
9278 if (rc == MDB_SUCCESS) {
9279 /* DB is totally empty now, just bail out.
9280 * Other cursors adjustments were already done
9281 * by mdb_rebalance and aren't needed here.
9286 mp = mc->mc_pg[mc->mc_top];
9287 nkeys = NUMKEYS(mp);
9289 /* Adjust other cursors pointing to mp */
9290 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
9291 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9292 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9294 if (m3->mc_snum < mc->mc_snum)
9296 if (m3->mc_pg[mc->mc_top] == mp) {
9297 /* if m3 points past last node in page, find next sibling */
9298 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
9299 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9300 rc = mdb_cursor_sibling(m3, 1);
9301 if (rc == MDB_NOTFOUND) {
9302 m3->mc_flags |= C_EOF;
9307 if (mc->mc_db->md_flags & MDB_DUPSORT) {
9308 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
9309 /* If this node has dupdata, it may need to be reinited
9310 * because its data has moved.
9311 * If the xcursor was not initd it must be reinited.
9312 * Else if node points to a subDB, nothing is needed.
9313 * Else (xcursor was initd, not a subDB) needs mc_pg[0] reset.
9315 if (node->mn_flags & F_DUPDATA) {
9316 if (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
9317 if (!(node->mn_flags & F_SUBDATA))
9318 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
9320 mdb_xcursor_init1(m3, node);
9321 m3->mc_xcursor->mx_cursor.mc_flags |= C_DEL;
9328 mc->mc_flags |= C_DEL;
9332 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9337 mdb_del(MDB_txn *txn, MDB_dbi dbi,
9338 MDB_val *key, MDB_val *data)
9340 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9343 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9344 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9346 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
9347 /* must ignore any data */
9351 return mdb_del0(txn, dbi, key, data, 0);
9355 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
9356 MDB_val *key, MDB_val *data, unsigned flags)
9361 MDB_val rdata, *xdata;
9365 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
9367 mdb_cursor_init(&mc, txn, dbi, &mx);
9376 flags |= MDB_NODUPDATA;
9378 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
9380 /* let mdb_page_split know about this cursor if needed:
9381 * delete will trigger a rebalance; if it needs to move
9382 * a node from one page to another, it will have to
9383 * update the parent's separator key(s). If the new sepkey
9384 * is larger than the current one, the parent page may
9385 * run out of space, triggering a split. We need this
9386 * cursor to be consistent until the end of the rebalance.
9388 mc.mc_next = txn->mt_cursors[dbi];
9389 txn->mt_cursors[dbi] = &mc;
9390 rc = mdb_cursor_del(&mc, flags);
9391 txn->mt_cursors[dbi] = mc.mc_next;
9396 /** Split a page and insert a new node.
9397 * Set #MDB_TXN_ERROR on failure.
9398 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
9399 * The cursor will be updated to point to the actual page and index where
9400 * the node got inserted after the split.
9401 * @param[in] newkey The key for the newly inserted node.
9402 * @param[in] newdata The data for the newly inserted node.
9403 * @param[in] newpgno The page number, if the new node is a branch node.
9404 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
9405 * @return 0 on success, non-zero on failure.
9408 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
9409 unsigned int nflags)
9412 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
9415 int i, j, split_indx, nkeys, pmax;
9416 MDB_env *env = mc->mc_txn->mt_env;
9418 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
9419 MDB_page *copy = NULL;
9420 MDB_page *mp, *rp, *pp;
9425 mp = mc->mc_pg[mc->mc_top];
9426 newindx = mc->mc_ki[mc->mc_top];
9427 nkeys = NUMKEYS(mp);
9429 DPRINTF(("-----> splitting %s page %"Yu" and adding [%s] at index %i/%i",
9430 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
9431 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
9433 /* Create a right sibling. */
9434 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
9436 rp->mp_pad = mp->mp_pad;
9437 DPRINTF(("new right sibling: page %"Yu, rp->mp_pgno));
9439 /* Usually when splitting the root page, the cursor
9440 * height is 1. But when called from mdb_update_key,
9441 * the cursor height may be greater because it walks
9442 * up the stack while finding the branch slot to update.
9444 if (mc->mc_top < 1) {
9445 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
9447 /* shift current top to make room for new parent */
9448 for (i=mc->mc_snum; i>0; i--) {
9449 mc->mc_pg[i] = mc->mc_pg[i-1];
9450 mc->mc_ki[i] = mc->mc_ki[i-1];
9454 mc->mc_db->md_root = pp->mp_pgno;
9455 DPRINTF(("root split! new root = %"Yu, pp->mp_pgno));
9456 new_root = mc->mc_db->md_depth++;
9458 /* Add left (implicit) pointer. */
9459 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
9460 /* undo the pre-push */
9461 mc->mc_pg[0] = mc->mc_pg[1];
9462 mc->mc_ki[0] = mc->mc_ki[1];
9463 mc->mc_db->md_root = mp->mp_pgno;
9464 mc->mc_db->md_depth--;
9471 ptop = mc->mc_top-1;
9472 DPRINTF(("parent branch page is %"Yu, mc->mc_pg[ptop]->mp_pgno));
9475 mdb_cursor_copy(mc, &mn);
9476 mn.mc_xcursor = NULL;
9477 mn.mc_pg[mn.mc_top] = rp;
9478 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
9480 if (nflags & MDB_APPEND) {
9481 mn.mc_ki[mn.mc_top] = 0;
9483 split_indx = newindx;
9487 split_indx = (nkeys+1) / 2;
9492 unsigned int lsize, rsize, ksize;
9493 /* Move half of the keys to the right sibling */
9494 x = mc->mc_ki[mc->mc_top] - split_indx;
9495 ksize = mc->mc_db->md_pad;
9496 split = LEAF2KEY(mp, split_indx, ksize);
9497 rsize = (nkeys - split_indx) * ksize;
9498 lsize = (nkeys - split_indx) * sizeof(indx_t);
9499 mp->mp_lower -= lsize;
9500 rp->mp_lower += lsize;
9501 mp->mp_upper += rsize - lsize;
9502 rp->mp_upper -= rsize - lsize;
9503 sepkey.mv_size = ksize;
9504 if (newindx == split_indx) {
9505 sepkey.mv_data = newkey->mv_data;
9507 sepkey.mv_data = split;
9510 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
9511 memcpy(rp->mp_ptrs, split, rsize);
9512 sepkey.mv_data = rp->mp_ptrs;
9513 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
9514 memcpy(ins, newkey->mv_data, ksize);
9515 mp->mp_lower += sizeof(indx_t);
9516 mp->mp_upper -= ksize - sizeof(indx_t);
9519 memcpy(rp->mp_ptrs, split, x * ksize);
9520 ins = LEAF2KEY(rp, x, ksize);
9521 memcpy(ins, newkey->mv_data, ksize);
9522 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
9523 rp->mp_lower += sizeof(indx_t);
9524 rp->mp_upper -= ksize - sizeof(indx_t);
9525 mc->mc_ki[mc->mc_top] = x;
9528 int psize, nsize, k;
9529 /* Maximum free space in an empty page */
9530 pmax = env->me_psize - PAGEHDRSZ;
9532 nsize = mdb_leaf_size(env, newkey, newdata);
9534 nsize = mdb_branch_size(env, newkey);
9535 nsize = EVEN(nsize);
9537 /* grab a page to hold a temporary copy */
9538 copy = mdb_page_malloc(mc->mc_txn, 1);
9543 copy->mp_pgno = mp->mp_pgno;
9544 copy->mp_flags = mp->mp_flags;
9545 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
9546 copy->mp_upper = env->me_psize - PAGEBASE;
9548 /* prepare to insert */
9549 for (i=0, j=0; i<nkeys; i++) {
9551 copy->mp_ptrs[j++] = 0;
9553 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
9556 /* When items are relatively large the split point needs
9557 * to be checked, because being off-by-one will make the
9558 * difference between success or failure in mdb_node_add.
9560 * It's also relevant if a page happens to be laid out
9561 * such that one half of its nodes are all "small" and
9562 * the other half of its nodes are "large." If the new
9563 * item is also "large" and falls on the half with
9564 * "large" nodes, it also may not fit.
9566 * As a final tweak, if the new item goes on the last
9567 * spot on the page (and thus, onto the new page), bias
9568 * the split so the new page is emptier than the old page.
9569 * This yields better packing during sequential inserts.
9571 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
9572 /* Find split point */
9574 if (newindx <= split_indx || newindx >= nkeys) {
9576 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
9581 for (; i!=k; i+=j) {
9586 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9587 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
9589 if (F_ISSET(node->mn_flags, F_BIGDATA))
9590 psize += sizeof(pgno_t);
9592 psize += NODEDSZ(node);
9594 psize = EVEN(psize);
9596 if (psize > pmax || i == k-j) {
9597 split_indx = i + (j<0);
9602 if (split_indx == newindx) {
9603 sepkey.mv_size = newkey->mv_size;
9604 sepkey.mv_data = newkey->mv_data;
9606 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
9607 sepkey.mv_size = node->mn_ksize;
9608 sepkey.mv_data = NODEKEY(node);
9613 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
9615 /* Copy separator key to the parent.
9617 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
9618 int snum = mc->mc_snum;
9622 /* We want other splits to find mn when doing fixups */
9623 WITH_CURSOR_TRACKING(mn,
9624 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
9629 if (mc->mc_snum > snum) {
9632 /* Right page might now have changed parent.
9633 * Check if left page also changed parent.
9635 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9636 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9637 for (i=0; i<ptop; i++) {
9638 mc->mc_pg[i] = mn.mc_pg[i];
9639 mc->mc_ki[i] = mn.mc_ki[i];
9641 mc->mc_pg[ptop] = mn.mc_pg[ptop];
9642 if (mn.mc_ki[ptop]) {
9643 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
9645 /* find right page's left sibling */
9646 mc->mc_ki[ptop] = mn.mc_ki[ptop];
9647 rc = mdb_cursor_sibling(mc, 0);
9652 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
9655 if (rc != MDB_SUCCESS) {
9656 if (rc == MDB_NOTFOUND) /* improper mdb_cursor_sibling() result */
9660 if (nflags & MDB_APPEND) {
9661 mc->mc_pg[mc->mc_top] = rp;
9662 mc->mc_ki[mc->mc_top] = 0;
9663 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
9666 for (i=0; i<mc->mc_top; i++)
9667 mc->mc_ki[i] = mn.mc_ki[i];
9668 } else if (!IS_LEAF2(mp)) {
9670 mc->mc_pg[mc->mc_top] = rp;
9675 rkey.mv_data = newkey->mv_data;
9676 rkey.mv_size = newkey->mv_size;
9682 /* Update index for the new key. */
9683 mc->mc_ki[mc->mc_top] = j;
9685 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9686 rkey.mv_data = NODEKEY(node);
9687 rkey.mv_size = node->mn_ksize;
9689 xdata.mv_data = NODEDATA(node);
9690 xdata.mv_size = NODEDSZ(node);
9693 pgno = NODEPGNO(node);
9694 flags = node->mn_flags;
9697 if (!IS_LEAF(mp) && j == 0) {
9698 /* First branch index doesn't need key data. */
9702 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
9708 mc->mc_pg[mc->mc_top] = copy;
9713 } while (i != split_indx);
9715 nkeys = NUMKEYS(copy);
9716 for (i=0; i<nkeys; i++)
9717 mp->mp_ptrs[i] = copy->mp_ptrs[i];
9718 mp->mp_lower = copy->mp_lower;
9719 mp->mp_upper = copy->mp_upper;
9720 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
9721 env->me_psize - copy->mp_upper - PAGEBASE);
9723 /* reset back to original page */
9724 if (newindx < split_indx) {
9725 mc->mc_pg[mc->mc_top] = mp;
9727 mc->mc_pg[mc->mc_top] = rp;
9729 /* Make sure mc_ki is still valid.
9731 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9732 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9733 for (i=0; i<=ptop; i++) {
9734 mc->mc_pg[i] = mn.mc_pg[i];
9735 mc->mc_ki[i] = mn.mc_ki[i];
9739 if (nflags & MDB_RESERVE) {
9740 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
9741 if (!(node->mn_flags & F_BIGDATA))
9742 newdata->mv_data = NODEDATA(node);
9745 if (newindx >= split_indx) {
9746 mc->mc_pg[mc->mc_top] = rp;
9748 /* Make sure mc_ki is still valid.
9750 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9751 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9752 for (i=0; i<=ptop; i++) {
9753 mc->mc_pg[i] = mn.mc_pg[i];
9754 mc->mc_ki[i] = mn.mc_ki[i];
9761 /* Adjust other cursors pointing to mp */
9762 MDB_cursor *m2, *m3;
9763 MDB_dbi dbi = mc->mc_dbi;
9764 nkeys = NUMKEYS(mp);
9766 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9767 if (mc->mc_flags & C_SUB)
9768 m3 = &m2->mc_xcursor->mx_cursor;
9773 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9777 /* sub cursors may be on different DB */
9778 if (m3->mc_pg[0] != mp)
9781 for (k=new_root; k>=0; k--) {
9782 m3->mc_ki[k+1] = m3->mc_ki[k];
9783 m3->mc_pg[k+1] = m3->mc_pg[k];
9785 if (m3->mc_ki[0] >= nkeys) {
9790 m3->mc_pg[0] = mc->mc_pg[0];
9794 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
9795 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
9796 m3->mc_ki[mc->mc_top]++;
9797 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9798 m3->mc_pg[mc->mc_top] = rp;
9799 m3->mc_ki[mc->mc_top] -= nkeys;
9800 for (i=0; i<mc->mc_top; i++) {
9801 m3->mc_ki[i] = mn.mc_ki[i];
9802 m3->mc_pg[i] = mn.mc_pg[i];
9805 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
9806 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
9810 XCURSOR_REFRESH(m3, mc->mc_top, m3->mc_pg[mc->mc_top]);
9813 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
9816 if (copy) /* tmp page */
9817 mdb_page_free(env, copy);
9819 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9824 mdb_put(MDB_txn *txn, MDB_dbi dbi,
9825 MDB_val *key, MDB_val *data, unsigned int flags)
9831 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9834 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
9837 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9838 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9840 mdb_cursor_init(&mc, txn, dbi, &mx);
9841 mc.mc_next = txn->mt_cursors[dbi];
9842 txn->mt_cursors[dbi] = &mc;
9843 rc = mdb_cursor_put(&mc, key, data, flags);
9844 txn->mt_cursors[dbi] = mc.mc_next;
9849 #define MDB_WBUF (1024*1024)
9851 #define MDB_EOF 0x10 /**< #mdb_env_copyfd1() is done reading */
9853 /** State needed for a double-buffering compacting copy. */
9854 typedef struct mdb_copy {
9857 pthread_mutex_t mc_mutex;
9858 pthread_cond_t mc_cond; /**< Condition variable for #mc_new */
9863 pgno_t mc_next_pgno;
9865 int mc_toggle; /**< Buffer number in provider */
9866 int mc_new; /**< (0-2 buffers to write) | (#MDB_EOF at end) */
9867 /** Error code. Never cleared if set. Both threads can set nonzero
9868 * to fail the copy. Not mutex-protected, LMDB expects atomic int.
9870 volatile int mc_error;
9873 /** Dedicated writer thread for compacting copy. */
9874 static THREAD_RET ESECT CALL_CONV
9875 mdb_env_copythr(void *arg)
9879 int toggle = 0, wsize, rc;
9882 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9885 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9889 sigaddset(&set, SIGPIPE);
9890 if ((rc = pthread_sigmask(SIG_BLOCK, &set, NULL)) != 0)
9895 pthread_mutex_lock(&my->mc_mutex);
9898 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9899 if (my->mc_new == 0 + MDB_EOF) /* 0 buffers, just EOF */
9901 wsize = my->mc_wlen[toggle];
9902 ptr = my->mc_wbuf[toggle];
9905 while (wsize > 0 && !my->mc_error) {
9906 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
9909 #if defined(SIGPIPE) && !defined(_WIN32)
9911 /* Collect the pending SIGPIPE, otherwise at least OS X
9912 * gives it to the process on thread-exit (ITS#8504).
9915 sigwait(&set, &tmp);
9919 } else if (len > 0) {
9932 /* If there's an overflow page tail, write it too */
9933 if (my->mc_olen[toggle]) {
9934 wsize = my->mc_olen[toggle];
9935 ptr = my->mc_over[toggle];
9936 my->mc_olen[toggle] = 0;
9939 my->mc_wlen[toggle] = 0;
9941 /* Return the empty buffer to provider */
9943 pthread_cond_signal(&my->mc_cond);
9945 pthread_mutex_unlock(&my->mc_mutex);
9946 return (THREAD_RET)0;
9950 /** Give buffer and/or #MDB_EOF to writer thread, await unused buffer.
9952 * @param[in] my control structure.
9953 * @param[in] adjust (1 to hand off 1 buffer) | (MDB_EOF when ending).
9956 mdb_env_cthr_toggle(mdb_copy *my, int adjust)
9958 pthread_mutex_lock(&my->mc_mutex);
9959 my->mc_new += adjust;
9960 pthread_cond_signal(&my->mc_cond);
9961 while (my->mc_new & 2) /* both buffers in use */
9962 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9963 pthread_mutex_unlock(&my->mc_mutex);
9965 my->mc_toggle ^= (adjust & 1);
9966 /* Both threads reset mc_wlen, to be safe from threading errors */
9967 my->mc_wlen[my->mc_toggle] = 0;
9968 return my->mc_error;
9971 /** Depth-first tree traversal for compacting copy.
9972 * @param[in] my control structure.
9973 * @param[in,out] pg database root.
9974 * @param[in] flags includes #F_DUPDATA if it is a sorted-duplicate sub-DB.
9977 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
9979 MDB_cursor mc = {0};
9981 MDB_page *mo, *mp, *leaf;
9986 /* Empty DB, nothing to do */
9987 if (*pg == P_INVALID)
9991 mc.mc_txn = my->mc_txn;
9992 mc.mc_flags = my->mc_txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
9994 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
9997 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
10001 /* Make cursor pages writable */
10002 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
10006 for (i=0; i<mc.mc_top; i++) {
10007 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
10008 mc.mc_pg[i] = (MDB_page *)ptr;
10009 ptr += my->mc_env->me_psize;
10012 /* This is writable space for a leaf page. Usually not needed. */
10013 leaf = (MDB_page *)ptr;
10015 toggle = my->mc_toggle;
10016 while (mc.mc_snum > 0) {
10018 mp = mc.mc_pg[mc.mc_top];
10022 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
10023 for (i=0; i<n; i++) {
10024 ni = NODEPTR(mp, i);
10025 if (ni->mn_flags & F_BIGDATA) {
10029 /* Need writable leaf */
10031 mc.mc_pg[mc.mc_top] = leaf;
10032 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
10034 ni = NODEPTR(mp, i);
10037 memcpy(&pg, NODEDATA(ni), sizeof(pg));
10038 memcpy(NODEDATA(ni), &my->mc_next_pgno, sizeof(pgno_t));
10039 rc = mdb_page_get(&mc, pg, &omp, NULL);
10042 if (my->mc_wlen[toggle] >= MDB_WBUF) {
10043 rc = mdb_env_cthr_toggle(my, 1);
10046 toggle = my->mc_toggle;
10048 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
10049 memcpy(mo, omp, my->mc_env->me_psize);
10050 mo->mp_pgno = my->mc_next_pgno;
10051 my->mc_next_pgno += omp->mp_pages;
10052 my->mc_wlen[toggle] += my->mc_env->me_psize;
10053 if (omp->mp_pages > 1) {
10054 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
10055 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
10056 rc = mdb_env_cthr_toggle(my, 1);
10059 toggle = my->mc_toggle;
10061 } else if (ni->mn_flags & F_SUBDATA) {
10064 /* Need writable leaf */
10066 mc.mc_pg[mc.mc_top] = leaf;
10067 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
10069 ni = NODEPTR(mp, i);
10072 memcpy(&db, NODEDATA(ni), sizeof(db));
10073 my->mc_toggle = toggle;
10074 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
10077 toggle = my->mc_toggle;
10078 memcpy(NODEDATA(ni), &db, sizeof(db));
10083 mc.mc_ki[mc.mc_top]++;
10084 if (mc.mc_ki[mc.mc_top] < n) {
10087 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
10089 rc = mdb_page_get(&mc, pg, &mp, NULL);
10094 mc.mc_ki[mc.mc_top] = 0;
10095 if (IS_BRANCH(mp)) {
10096 /* Whenever we advance to a sibling branch page,
10097 * we must proceed all the way down to its first leaf.
10099 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
10102 mc.mc_pg[mc.mc_top] = mp;
10106 if (my->mc_wlen[toggle] >= MDB_WBUF) {
10107 rc = mdb_env_cthr_toggle(my, 1);
10110 toggle = my->mc_toggle;
10112 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
10113 mdb_page_copy(mo, mp, my->mc_env->me_psize);
10114 mo->mp_pgno = my->mc_next_pgno++;
10115 my->mc_wlen[toggle] += my->mc_env->me_psize;
10117 /* Update parent if there is one */
10118 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
10119 SETPGNO(ni, mo->mp_pgno);
10120 mdb_cursor_pop(&mc);
10122 /* Otherwise we're done */
10132 /** Copy environment with compaction. */
10134 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
10139 MDB_txn *txn = NULL;
10141 pgno_t root, new_root;
10142 int rc = MDB_SUCCESS;
10145 if (!(my.mc_mutex = CreateMutex(NULL, FALSE, NULL)) ||
10146 !(my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL))) {
10150 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
10151 if (my.mc_wbuf[0] == NULL) {
10152 /* _aligned_malloc() sets errno, but we use Windows error codes */
10153 rc = ERROR_NOT_ENOUGH_MEMORY;
10157 if ((rc = pthread_mutex_init(&my.mc_mutex, NULL)) != 0)
10159 if ((rc = pthread_cond_init(&my.mc_cond, NULL)) != 0)
10161 #ifdef HAVE_MEMALIGN
10162 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
10163 if (my.mc_wbuf[0] == NULL) {
10170 if ((rc = posix_memalign(&p, env->me_os_psize, MDB_WBUF*2)) != 0)
10176 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
10177 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
10178 my.mc_next_pgno = NUM_METAS;
10181 rc = THREAD_CREATE(thr, mdb_env_copythr, &my);
10185 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10189 mp = (MDB_page *)my.mc_wbuf[0];
10190 memset(mp, 0, NUM_METAS * env->me_psize);
10192 mp->mp_flags = P_META;
10193 mm = (MDB_meta *)METADATA(mp);
10194 mdb_env_init_meta0(env, mm);
10195 mm->mm_address = env->me_metas[0]->mm_address;
10197 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
10199 mp->mp_flags = P_META;
10200 *(MDB_meta *)METADATA(mp) = *mm;
10201 mm = (MDB_meta *)METADATA(mp);
10203 /* Set metapage 1 with current main DB */
10204 root = new_root = txn->mt_dbs[MAIN_DBI].md_root;
10205 if (root != P_INVALID) {
10206 /* Count free pages + freeDB pages. Subtract from last_pg
10207 * to find the new last_pg, which also becomes the new root.
10209 MDB_ID freecount = 0;
10212 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
10213 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
10214 freecount += *(MDB_ID *)data.mv_data;
10215 if (rc != MDB_NOTFOUND)
10217 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
10218 txn->mt_dbs[FREE_DBI].md_leaf_pages +
10219 txn->mt_dbs[FREE_DBI].md_overflow_pages;
10221 new_root = txn->mt_next_pgno - 1 - freecount;
10222 mm->mm_last_pg = new_root;
10223 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
10224 mm->mm_dbs[MAIN_DBI].md_root = new_root;
10226 /* When the DB is empty, handle it specially to
10227 * fix any breakage like page leaks from ITS#8174.
10229 mm->mm_dbs[MAIN_DBI].md_flags = txn->mt_dbs[MAIN_DBI].md_flags;
10231 if (root != P_INVALID || mm->mm_dbs[MAIN_DBI].md_flags) {
10232 mm->mm_txnid = 1; /* use metapage 1 */
10235 my.mc_wlen[0] = env->me_psize * NUM_METAS;
10237 rc = mdb_env_cwalk(&my, &root, 0);
10238 if (rc == MDB_SUCCESS && root != new_root) {
10239 rc = MDB_INCOMPATIBLE; /* page leak or corrupt DB */
10245 mdb_env_cthr_toggle(&my, 1 | MDB_EOF);
10246 rc = THREAD_FINISH(thr);
10247 mdb_txn_abort(txn);
10251 if (my.mc_wbuf[0]) _aligned_free(my.mc_wbuf[0]);
10252 if (my.mc_cond) CloseHandle(my.mc_cond);
10253 if (my.mc_mutex) CloseHandle(my.mc_mutex);
10255 free(my.mc_wbuf[0]);
10256 pthread_cond_destroy(&my.mc_cond);
10258 pthread_mutex_destroy(&my.mc_mutex);
10260 return rc ? rc : my.mc_error;
10263 /** Copy environment as-is. */
10265 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
10267 MDB_txn *txn = NULL;
10268 mdb_mutexref_t wmutex = NULL;
10270 mdb_size_t wsize, w3;
10274 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
10278 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
10281 /* Do the lock/unlock of the reader mutex before starting the
10282 * write txn. Otherwise other read txns could block writers.
10284 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10288 if (env->me_txns) {
10289 /* We must start the actual read txn after blocking writers */
10290 mdb_txn_end(txn, MDB_END_RESET_TMP);
10292 /* Temporarily block writers until we snapshot the meta pages */
10293 wmutex = env->me_wmutex;
10294 if (LOCK_MUTEX(rc, env, wmutex))
10297 rc = mdb_txn_renew0(txn);
10299 UNLOCK_MUTEX(wmutex);
10304 wsize = env->me_psize * NUM_METAS;
10308 DO_WRITE(rc, fd, ptr, w2, len);
10312 } else if (len > 0) {
10318 /* Non-blocking or async handles are not supported */
10324 UNLOCK_MUTEX(wmutex);
10329 w3 = txn->mt_next_pgno * env->me_psize;
10331 mdb_size_t fsize = 0;
10332 if ((rc = mdb_fsize(env->me_fd, &fsize)))
10337 wsize = w3 - wsize;
10338 while (wsize > 0) {
10339 if (wsize > MAX_WRITE)
10343 DO_WRITE(rc, fd, ptr, w2, len);
10347 } else if (len > 0) {
10359 mdb_txn_abort(txn);
10364 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
10366 if (flags & MDB_CP_COMPACT)
10367 return mdb_env_copyfd1(env, fd);
10369 return mdb_env_copyfd0(env, fd);
10373 mdb_env_copyfd(MDB_env *env, HANDLE fd)
10375 return mdb_env_copyfd2(env, fd, 0);
10379 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
10383 HANDLE newfd = INVALID_HANDLE_VALUE;
10385 rc = mdb_fname_init(path, env->me_flags | MDB_NOLOCK, &fname);
10386 if (rc == MDB_SUCCESS) {
10387 rc = mdb_fopen(env, &fname, MDB_O_COPY, 0666, &newfd);
10388 mdb_fname_destroy(fname);
10390 if (rc == MDB_SUCCESS) {
10391 rc = mdb_env_copyfd2(env, newfd, flags);
10392 if (close(newfd) < 0 && rc == MDB_SUCCESS)
10399 mdb_env_copy(MDB_env *env, const char *path)
10401 return mdb_env_copy2(env, path, 0);
10405 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
10407 if (flag & ~CHANGEABLE)
10410 env->me_flags |= flag;
10412 env->me_flags &= ~flag;
10413 return MDB_SUCCESS;
10417 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
10422 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
10423 return MDB_SUCCESS;
10427 mdb_env_set_userctx(MDB_env *env, void *ctx)
10431 env->me_userctx = ctx;
10432 return MDB_SUCCESS;
10436 mdb_env_get_userctx(MDB_env *env)
10438 return env ? env->me_userctx : NULL;
10442 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
10447 env->me_assert_func = func;
10449 return MDB_SUCCESS;
10453 mdb_env_get_path(MDB_env *env, const char **arg)
10458 *arg = env->me_path;
10459 return MDB_SUCCESS;
10463 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
10469 return MDB_SUCCESS;
10472 /** Common code for #mdb_stat() and #mdb_env_stat().
10473 * @param[in] env the environment to operate in.
10474 * @param[in] db the #MDB_db record containing the stats to return.
10475 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
10476 * @return 0, this function always succeeds.
10479 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
10481 arg->ms_psize = env->me_psize;
10482 arg->ms_depth = db->md_depth;
10483 arg->ms_branch_pages = db->md_branch_pages;
10484 arg->ms_leaf_pages = db->md_leaf_pages;
10485 arg->ms_overflow_pages = db->md_overflow_pages;
10486 arg->ms_entries = db->md_entries;
10488 return MDB_SUCCESS;
10492 mdb_env_stat(MDB_env *env, MDB_stat *arg)
10496 if (env == NULL || arg == NULL)
10499 meta = mdb_env_pick_meta(env);
10501 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
10505 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
10509 if (env == NULL || arg == NULL)
10512 meta = mdb_env_pick_meta(env);
10513 arg->me_mapaddr = meta->mm_address;
10514 arg->me_last_pgno = meta->mm_last_pg;
10515 arg->me_last_txnid = meta->mm_txnid;
10517 arg->me_mapsize = env->me_mapsize;
10518 arg->me_maxreaders = env->me_maxreaders;
10519 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
10520 return MDB_SUCCESS;
10523 /** Set the default comparison functions for a database.
10524 * Called immediately after a database is opened to set the defaults.
10525 * The user can then override them with #mdb_set_compare() or
10526 * #mdb_set_dupsort().
10527 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
10528 * @param[in] dbi A database handle returned by #mdb_dbi_open()
10531 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
10533 uint16_t f = txn->mt_dbs[dbi].md_flags;
10535 txn->mt_dbxs[dbi].md_cmp =
10536 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
10537 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
10539 txn->mt_dbxs[dbi].md_dcmp =
10540 !(f & MDB_DUPSORT) ? 0 :
10541 ((f & MDB_INTEGERDUP)
10542 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
10543 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
10546 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
10552 int rc, dbflag, exact;
10553 unsigned int unused = 0, seq;
10557 if (flags & ~VALID_FLAGS)
10559 if (txn->mt_flags & MDB_TXN_BLOCKED)
10560 return MDB_BAD_TXN;
10565 if (flags & PERSISTENT_FLAGS) {
10566 uint16_t f2 = flags & PERSISTENT_FLAGS;
10567 /* make sure flag changes get committed */
10568 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
10569 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
10570 txn->mt_flags |= MDB_TXN_DIRTY;
10573 mdb_default_cmp(txn, MAIN_DBI);
10574 return MDB_SUCCESS;
10577 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
10578 mdb_default_cmp(txn, MAIN_DBI);
10581 /* Is the DB already open? */
10582 len = strlen(name);
10583 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
10584 if (!txn->mt_dbxs[i].md_name.mv_size) {
10585 /* Remember this free slot */
10586 if (!unused) unused = i;
10589 if (len == txn->mt_dbxs[i].md_name.mv_size &&
10590 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
10592 return MDB_SUCCESS;
10596 /* If no free slot and max hit, fail */
10597 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
10598 return MDB_DBS_FULL;
10600 /* Cannot mix named databases with some mainDB flags */
10601 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
10602 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
10604 /* Find the DB info */
10605 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
10608 key.mv_data = (void *)name;
10609 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
10610 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
10611 if (rc == MDB_SUCCESS) {
10612 /* make sure this is actually a DB */
10613 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
10614 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
10615 return MDB_INCOMPATIBLE;
10616 } else if (! (rc == MDB_NOTFOUND && (flags & MDB_CREATE))) {
10620 /* Done here so we cannot fail after creating a new DB */
10621 if ((namedup = strdup(name)) == NULL)
10625 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
10626 data.mv_size = sizeof(MDB_db);
10627 data.mv_data = &dummy;
10628 memset(&dummy, 0, sizeof(dummy));
10629 dummy.md_root = P_INVALID;
10630 dummy.md_flags = flags & PERSISTENT_FLAGS;
10631 WITH_CURSOR_TRACKING(mc,
10632 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA));
10633 dbflag |= DB_DIRTY;
10639 /* Got info, register DBI in this txn */
10640 unsigned int slot = unused ? unused : txn->mt_numdbs;
10641 txn->mt_dbxs[slot].md_name.mv_data = namedup;
10642 txn->mt_dbxs[slot].md_name.mv_size = len;
10643 txn->mt_dbxs[slot].md_rel = NULL;
10644 txn->mt_dbflags[slot] = dbflag;
10645 /* txn-> and env-> are the same in read txns, use
10646 * tmp variable to avoid undefined assignment
10648 seq = ++txn->mt_env->me_dbiseqs[slot];
10649 txn->mt_dbiseqs[slot] = seq;
10651 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
10653 mdb_default_cmp(txn, slot);
10663 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
10665 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
10668 if (txn->mt_flags & MDB_TXN_BLOCKED)
10669 return MDB_BAD_TXN;
10671 if (txn->mt_dbflags[dbi] & DB_STALE) {
10674 /* Stale, must read the DB's root. cursor_init does it for us. */
10675 mdb_cursor_init(&mc, txn, dbi, &mx);
10677 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
10680 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
10683 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
10685 ptr = env->me_dbxs[dbi].md_name.mv_data;
10686 /* If there was no name, this was already closed */
10688 env->me_dbxs[dbi].md_name.mv_data = NULL;
10689 env->me_dbxs[dbi].md_name.mv_size = 0;
10690 env->me_dbflags[dbi] = 0;
10691 env->me_dbiseqs[dbi]++;
10696 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
10698 /* We could return the flags for the FREE_DBI too but what's the point? */
10699 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10701 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
10702 return MDB_SUCCESS;
10705 /** Add all the DB's pages to the free list.
10706 * @param[in] mc Cursor on the DB to free.
10707 * @param[in] subs non-Zero to check for sub-DBs in this DB.
10708 * @return 0 on success, non-zero on failure.
10711 mdb_drop0(MDB_cursor *mc, int subs)
10715 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
10716 if (rc == MDB_SUCCESS) {
10717 MDB_txn *txn = mc->mc_txn;
10722 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
10723 * This also avoids any P_LEAF2 pages, which have no nodes.
10724 * Also if the DB doesn't have sub-DBs and has no overflow
10725 * pages, omit scanning leaves.
10727 if ((mc->mc_flags & C_SUB) ||
10728 (!subs && !mc->mc_db->md_overflow_pages))
10729 mdb_cursor_pop(mc);
10731 mdb_cursor_copy(mc, &mx);
10733 /* bump refcount for mx's pages */
10734 for (i=0; i<mc->mc_snum; i++)
10735 mdb_page_get(&mx, mc->mc_pg[i]->mp_pgno, &mx.mc_pg[i], NULL);
10737 while (mc->mc_snum > 0) {
10738 MDB_page *mp = mc->mc_pg[mc->mc_top];
10739 unsigned n = NUMKEYS(mp);
10741 for (i=0; i<n; i++) {
10742 ni = NODEPTR(mp, i);
10743 if (ni->mn_flags & F_BIGDATA) {
10746 memcpy(&pg, NODEDATA(ni), sizeof(pg));
10747 rc = mdb_page_get(mc, pg, &omp, NULL);
10750 mdb_cassert(mc, IS_OVERFLOW(omp));
10751 rc = mdb_midl_append_range(&txn->mt_free_pgs,
10752 pg, omp->mp_pages);
10755 mc->mc_db->md_overflow_pages -= omp->mp_pages;
10756 if (!mc->mc_db->md_overflow_pages && !subs)
10758 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
10759 mdb_xcursor_init1(mc, ni);
10760 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
10765 if (!subs && !mc->mc_db->md_overflow_pages)
10768 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
10770 for (i=0; i<n; i++) {
10772 ni = NODEPTR(mp, i);
10775 mdb_midl_xappend(txn->mt_free_pgs, pg);
10780 mc->mc_ki[mc->mc_top] = i;
10781 rc = mdb_cursor_sibling(mc, 1);
10783 if (rc != MDB_NOTFOUND)
10785 /* no more siblings, go back to beginning
10786 * of previous level.
10789 mdb_cursor_pop(mc);
10791 for (i=1; i<mc->mc_snum; i++) {
10793 mc->mc_pg[i] = mx.mc_pg[i];
10798 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
10801 txn->mt_flags |= MDB_TXN_ERROR;
10802 /* drop refcount for mx's pages */
10803 MDB_CURSOR_UNREF(&mx, 0);
10804 } else if (rc == MDB_NOTFOUND) {
10807 mc->mc_flags &= ~C_INITIALIZED;
10811 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
10813 MDB_cursor *mc, *m2;
10816 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10819 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
10822 if (TXN_DBI_CHANGED(txn, dbi))
10823 return MDB_BAD_DBI;
10825 rc = mdb_cursor_open(txn, dbi, &mc);
10829 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
10830 /* Invalidate the dropped DB's cursors */
10831 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
10832 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
10836 /* Can't delete the main DB */
10837 if (del && dbi >= CORE_DBS) {
10838 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
10840 txn->mt_dbflags[dbi] = DB_STALE;
10841 mdb_dbi_close(txn->mt_env, dbi);
10843 txn->mt_flags |= MDB_TXN_ERROR;
10846 /* reset the DB record, mark it dirty */
10847 txn->mt_dbflags[dbi] |= DB_DIRTY;
10848 txn->mt_dbs[dbi].md_depth = 0;
10849 txn->mt_dbs[dbi].md_branch_pages = 0;
10850 txn->mt_dbs[dbi].md_leaf_pages = 0;
10851 txn->mt_dbs[dbi].md_overflow_pages = 0;
10852 txn->mt_dbs[dbi].md_entries = 0;
10853 txn->mt_dbs[dbi].md_root = P_INVALID;
10855 txn->mt_flags |= MDB_TXN_DIRTY;
10858 mdb_cursor_close(mc);
10862 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10864 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10867 txn->mt_dbxs[dbi].md_cmp = cmp;
10868 return MDB_SUCCESS;
10871 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10873 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10876 txn->mt_dbxs[dbi].md_dcmp = cmp;
10877 return MDB_SUCCESS;
10880 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
10882 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10885 txn->mt_dbxs[dbi].md_rel = rel;
10886 return MDB_SUCCESS;
10889 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
10891 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10894 txn->mt_dbxs[dbi].md_relctx = ctx;
10895 return MDB_SUCCESS;
10899 mdb_env_get_maxkeysize(MDB_env *env)
10901 return ENV_MAXKEY(env);
10905 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
10907 unsigned int i, rdrs;
10910 int rc = 0, first = 1;
10914 if (!env->me_txns) {
10915 return func("(no reader locks)\n", ctx);
10917 rdrs = env->me_txns->mti_numreaders;
10918 mr = env->me_txns->mti_readers;
10919 for (i=0; i<rdrs; i++) {
10920 if (mr[i].mr_pid) {
10921 txnid_t txnid = mr[i].mr_txnid;
10922 sprintf(buf, txnid == (txnid_t)-1 ?
10923 "%10d %"Z"x -\n" : "%10d %"Z"x %"Yu"\n",
10924 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
10927 rc = func(" pid thread txnid\n", ctx);
10931 rc = func(buf, ctx);
10937 rc = func("(no active readers)\n", ctx);
10942 /** Insert pid into list if not already present.
10943 * return -1 if already present.
10946 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
10948 /* binary search of pid in list */
10950 unsigned cursor = 1;
10952 unsigned n = ids[0];
10955 unsigned pivot = n >> 1;
10956 cursor = base + pivot + 1;
10957 val = pid - ids[cursor];
10962 } else if ( val > 0 ) {
10967 /* found, so it's a duplicate */
10976 for (n = ids[0]; n > cursor; n--)
10983 mdb_reader_check(MDB_env *env, int *dead)
10989 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
10992 /** As #mdb_reader_check(). \b rlocked is set if caller locked #me_rmutex. */
10994 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
10996 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
10997 unsigned int i, j, rdrs;
10999 MDB_PID_T *pids, pid;
11000 int rc = MDB_SUCCESS, count = 0;
11002 rdrs = env->me_txns->mti_numreaders;
11003 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
11007 mr = env->me_txns->mti_readers;
11008 for (i=0; i<rdrs; i++) {
11009 pid = mr[i].mr_pid;
11010 if (pid && pid != env->me_pid) {
11011 if (mdb_pid_insert(pids, pid) == 0) {
11012 if (!mdb_reader_pid(env, Pidcheck, pid)) {
11013 /* Stale reader found */
11016 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
11017 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
11019 rdrs = 0; /* the above checked all readers */
11021 /* Recheck, a new process may have reused pid */
11022 if (mdb_reader_pid(env, Pidcheck, pid))
11026 for (; j<rdrs; j++)
11027 if (mr[j].mr_pid == pid) {
11028 DPRINTF(("clear stale reader pid %u txn %"Yd,
11029 (unsigned) pid, mr[j].mr_txnid));
11034 UNLOCK_MUTEX(rmutex);
11045 #ifdef MDB_ROBUST_SUPPORTED
11046 /** Handle #LOCK_MUTEX0() failure.
11047 * Try to repair the lock file if the mutex owner died.
11048 * @param[in] env the environment handle
11049 * @param[in] mutex LOCK_MUTEX0() mutex
11050 * @param[in] rc LOCK_MUTEX0() error (nonzero)
11051 * @return 0 on success with the mutex locked, or an error code on failure.
11054 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
11059 if (rc == MDB_OWNERDEAD) {
11060 /* We own the mutex. Clean up after dead previous owner. */
11062 rlocked = (mutex == env->me_rmutex);
11064 /* Keep mti_txnid updated, otherwise next writer can
11065 * overwrite data which latest meta page refers to.
11067 meta = mdb_env_pick_meta(env);
11068 env->me_txns->mti_txnid = meta->mm_txnid;
11069 /* env is hosed if the dead thread was ours */
11071 env->me_flags |= MDB_FATAL_ERROR;
11072 env->me_txn = NULL;
11076 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
11077 (rc ? "this process' env is hosed" : "recovering")));
11078 rc2 = mdb_reader_check0(env, rlocked, NULL);
11080 rc2 = mdb_mutex_consistent(mutex);
11081 if (rc || (rc = rc2)) {
11082 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
11083 UNLOCK_MUTEX(mutex);
11089 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
11094 #endif /* MDB_ROBUST_SUPPORTED */
11096 #if defined(_WIN32)
11097 /** Convert \b src to new wchar_t[] string with room for \b xtra extra chars */
11099 utf8_to_utf16(const char *src, MDB_name *dst, int xtra)
11102 wchar_t *result = NULL;
11103 for (;;) { /* malloc result, then fill it in */
11104 need = MultiByteToWideChar(CP_UTF8, 0, src, -1, result, need);
11111 result = malloc(sizeof(wchar_t) * (need + xtra));
11116 dst->mn_alloced = 1;
11117 dst->mn_len = need - 1;
11118 dst->mn_val = result;
11119 return MDB_SUCCESS;
11122 #endif /* defined(_WIN32) */