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
145 /* On Solaris, we need the POSIX sigwait function */
147 # define _POSIX_PTHREAD_SEMANTICS 1
151 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
152 #include <netinet/in.h>
153 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
156 #if defined(__APPLE__) || defined (BSD) || defined(__FreeBSD_kernel__)
157 # if !(defined(MDB_USE_POSIX_MUTEX) || defined(MDB_USE_POSIX_SEM))
158 # define MDB_USE_SYSV_SEM 1
160 # define MDB_FDATASYNC fsync
161 #elif defined(ANDROID)
162 # define MDB_FDATASYNC fsync
168 #ifdef MDB_USE_POSIX_SEM
169 # define MDB_USE_HASH 1
170 #include <semaphore.h>
171 #elif defined(MDB_USE_SYSV_SEM)
174 #ifdef _SEM_SEMUN_UNDEFINED
177 struct semid_ds *buf;
178 unsigned short *array;
180 #endif /* _SEM_SEMUN_UNDEFINED */
182 #define MDB_USE_POSIX_MUTEX 1
183 #endif /* MDB_USE_POSIX_SEM */
186 #if defined(_WIN32) + defined(MDB_USE_POSIX_SEM) + defined(MDB_USE_SYSV_SEM) \
187 + defined(MDB_USE_POSIX_MUTEX) != 1
188 # error "Ambiguous shared-lock implementation"
192 #include <valgrind/memcheck.h>
193 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
194 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
195 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
196 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
197 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
199 #define VGMEMP_CREATE(h,r,z)
200 #define VGMEMP_ALLOC(h,a,s)
201 #define VGMEMP_FREE(h,a)
202 #define VGMEMP_DESTROY(h)
203 #define VGMEMP_DEFINED(a,s)
207 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
208 /* Solaris just defines one or the other */
209 # define LITTLE_ENDIAN 1234
210 # define BIG_ENDIAN 4321
211 # ifdef _LITTLE_ENDIAN
212 # define BYTE_ORDER LITTLE_ENDIAN
214 # define BYTE_ORDER BIG_ENDIAN
217 # define BYTE_ORDER __BYTE_ORDER
221 #ifndef LITTLE_ENDIAN
222 #define LITTLE_ENDIAN __LITTLE_ENDIAN
225 #define BIG_ENDIAN __BIG_ENDIAN
228 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
229 #define MISALIGNED_OK 1
235 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
236 # error "Unknown or unsupported endianness (BYTE_ORDER)"
237 #elif (-6 & 5) || CHAR_BIT!=8 || UINT_MAX!=0xffffffff || MDB_SIZE_MAX%UINT_MAX
238 # error "Two's complement, reasonably sized integer types, please"
242 /** Put infrequently used env functions in separate section */
244 # define ESECT __attribute__ ((section("__TEXT,text_env")))
246 # define ESECT __attribute__ ((section("text_env")))
253 #define CALL_CONV WINAPI
258 /** @defgroup internal LMDB Internals
261 /** @defgroup compat Compatibility Macros
262 * A bunch of macros to minimize the amount of platform-specific ifdefs
263 * needed throughout the rest of the code. When the features this library
264 * needs are similar enough to POSIX to be hidden in a one-or-two line
265 * replacement, this macro approach is used.
269 /** Features under development */
274 /** Wrapper around __func__, which is a C99 feature */
275 #if __STDC_VERSION__ >= 199901L
276 # define mdb_func_ __func__
277 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
278 # define mdb_func_ __FUNCTION__
280 /* If a debug message says <mdb_unknown>(), update the #if statements above */
281 # define mdb_func_ "<mdb_unknown>"
284 /* Internal error codes, not exposed outside liblmdb */
285 #define MDB_NO_ROOT (MDB_LAST_ERRCODE + 10)
287 #define MDB_OWNERDEAD ((int) WAIT_ABANDONED)
288 #elif defined MDB_USE_SYSV_SEM
289 #define MDB_OWNERDEAD (MDB_LAST_ERRCODE + 11)
290 #elif defined(MDB_USE_POSIX_MUTEX) && defined(EOWNERDEAD)
291 #define MDB_OWNERDEAD EOWNERDEAD /**< #LOCK_MUTEX0() result if dead owner */
295 #define GLIBC_VER ((__GLIBC__ << 16 )| __GLIBC_MINOR__)
297 /** Some platforms define the EOWNERDEAD error code
298 * even though they don't support Robust Mutexes.
299 * Compile with -DMDB_USE_ROBUST=0, or use some other
300 * mechanism like -DMDB_USE_SYSV_SEM instead of
301 * -DMDB_USE_POSIX_MUTEX. (SysV semaphores are
302 * also Robust, but some systems don't support them
305 #ifndef MDB_USE_ROBUST
306 /* Android currently lacks Robust Mutex support. So does glibc < 2.4. */
307 # if defined(MDB_USE_POSIX_MUTEX) && (defined(ANDROID) || \
308 (defined(__GLIBC__) && GLIBC_VER < 0x020004))
309 # define MDB_USE_ROBUST 0
311 # define MDB_USE_ROBUST 1
313 #endif /* !MDB_USE_ROBUST */
315 #if defined(MDB_USE_POSIX_MUTEX) && (MDB_USE_ROBUST)
316 /* glibc < 2.12 only provided _np API */
317 # if (defined(__GLIBC__) && GLIBC_VER < 0x02000c) || \
318 (defined(PTHREAD_MUTEX_ROBUST_NP) && !defined(PTHREAD_MUTEX_ROBUST))
319 # define PTHREAD_MUTEX_ROBUST PTHREAD_MUTEX_ROBUST_NP
320 # define pthread_mutexattr_setrobust(attr, flag) pthread_mutexattr_setrobust_np(attr, flag)
321 # define pthread_mutex_consistent(mutex) pthread_mutex_consistent_np(mutex)
323 #endif /* MDB_USE_POSIX_MUTEX && MDB_USE_ROBUST */
325 #if defined(MDB_OWNERDEAD) && (MDB_USE_ROBUST)
326 #define MDB_ROBUST_SUPPORTED 1
330 #define MDB_USE_HASH 1
331 #define MDB_PIDLOCK 0
332 #define THREAD_RET DWORD
333 #define pthread_t HANDLE
334 #define pthread_mutex_t HANDLE
335 #define pthread_cond_t HANDLE
336 typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
337 #define pthread_key_t DWORD
338 #define pthread_self() GetCurrentThreadId()
339 #define pthread_key_create(x,y) \
340 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
341 #define pthread_key_delete(x) TlsFree(x)
342 #define pthread_getspecific(x) TlsGetValue(x)
343 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
344 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
345 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
346 #define pthread_cond_signal(x) SetEvent(*x)
347 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
348 #define THREAD_CREATE(thr,start,arg) \
349 (((thr) = CreateThread(NULL, 0, start, arg, 0, NULL)) ? 0 : ErrCode())
350 #define THREAD_FINISH(thr) \
351 (WaitForSingleObject(thr, INFINITE) ? ErrCode() : 0)
352 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
353 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
354 #define mdb_mutex_consistent(mutex) 0
355 #define getpid() GetCurrentProcessId()
356 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
357 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
358 #define ErrCode() GetLastError()
359 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
360 #define close(fd) (CloseHandle(fd) ? 0 : -1)
361 #define munmap(ptr,len) UnmapViewOfFile(ptr)
362 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
363 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
365 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
368 #define THREAD_RET void *
369 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
370 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
372 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
373 #define MDB_PIDLOCK 1
375 #ifdef MDB_USE_POSIX_SEM
377 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
378 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
379 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
382 mdb_sem_wait(sem_t *sem)
385 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
389 #elif defined MDB_USE_SYSV_SEM
391 typedef struct mdb_mutex {
395 } mdb_mutex_t[1], *mdb_mutexref_t;
397 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
398 #define UNLOCK_MUTEX(mutex) do { \
399 struct sembuf sb = { 0, 1, SEM_UNDO }; \
400 sb.sem_num = (mutex)->semnum; \
401 *(mutex)->locked = 0; \
402 semop((mutex)->semid, &sb, 1); \
406 mdb_sem_wait(mdb_mutexref_t sem)
408 int rc, *locked = sem->locked;
409 struct sembuf sb = { 0, -1, SEM_UNDO };
410 sb.sem_num = sem->semnum;
412 if (!semop(sem->semid, &sb, 1)) {
413 rc = *locked ? MDB_OWNERDEAD : MDB_SUCCESS;
417 } while ((rc = errno) == EINTR);
421 #define mdb_mutex_consistent(mutex) 0
423 #else /* MDB_USE_POSIX_MUTEX: */
424 /** Shared mutex/semaphore as the original is stored.
426 * Not for copies. Instead it can be assigned to an #mdb_mutexref_t.
427 * When mdb_mutexref_t is a pointer and mdb_mutex_t is not, then it
428 * is array[size 1] so it can be assigned to the pointer.
430 typedef pthread_mutex_t mdb_mutex_t[1];
431 /** Reference to an #mdb_mutex_t */
432 typedef pthread_mutex_t *mdb_mutexref_t;
433 /** Lock the reader or writer mutex.
434 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
436 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
437 /** Unlock the reader or writer mutex.
439 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
440 /** Mark mutex-protected data as repaired, after death of previous owner.
442 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
443 #endif /* MDB_USE_POSIX_SEM || MDB_USE_SYSV_SEM */
445 /** Get the error code for the last failed system function.
447 #define ErrCode() errno
449 /** An abstraction for a file handle.
450 * On POSIX systems file handles are small integers. On Windows
451 * they're opaque pointers.
455 /** A value for an invalid file handle.
456 * Mainly used to initialize file variables and signify that they are
459 #define INVALID_HANDLE_VALUE (-1)
461 /** Get the size of a memory page for the system.
462 * This is the basic size that the platform's memory manager uses, and is
463 * fundamental to the use of memory-mapped files.
465 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
468 #define Z MDB_FMT_Z /**< printf/scanf format modifier for size_t */
469 #define Yu MDB_PRIy(u) /**< printf format for #mdb_size_t */
470 #define Yd MDB_PRIy(d) /**< printf format for 'signed #mdb_size_t' */
472 #ifdef MDB_USE_SYSV_SEM
473 #define MNAME_LEN (sizeof(int))
475 #define MNAME_LEN (sizeof(pthread_mutex_t))
478 /** Initial part of #MDB_env.me_mutexname[].
479 * Changes to this code must be reflected in #MDB_LOCK_FORMAT.
482 #define MUTEXNAME_PREFIX "Global\\MDB"
483 #elif defined MDB_USE_POSIX_SEM
484 #define MUTEXNAME_PREFIX "/MDB"
489 #ifdef MDB_ROBUST_SUPPORTED
490 /** Lock mutex, handle any error, set rc = result.
491 * Return 0 on success, nonzero (not rc) on error.
493 #define LOCK_MUTEX(rc, env, mutex) \
494 (((rc) = LOCK_MUTEX0(mutex)) && \
495 ((rc) = mdb_mutex_failed(env, mutex, rc)))
496 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
498 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
499 #define mdb_mutex_failed(env, mutex, rc) (rc)
503 /** A flag for opening a file and requesting synchronous data writes.
504 * This is only used when writing a meta page. It's not strictly needed;
505 * we could just do a normal write and then immediately perform a flush.
506 * But if this flag is available it saves us an extra system call.
508 * @note If O_DSYNC is undefined but exists in /usr/include,
509 * preferably set some compiler flag to get the definition.
513 # define MDB_DSYNC O_DSYNC
515 # define MDB_DSYNC O_SYNC
520 /** Function for flushing the data of a file. Define this to fsync
521 * if fdatasync() is not supported.
523 #ifndef MDB_FDATASYNC
524 # define MDB_FDATASYNC fdatasync
528 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
539 /** A page number in the database.
540 * Note that 64 bit page numbers are overkill, since pages themselves
541 * already represent 12-13 bits of addressable memory, and the OS will
542 * always limit applications to a maximum of 63 bits of address space.
544 * @note In the #MDB_node structure, we only store 48 bits of this value,
545 * which thus limits us to only 60 bits of addressable data.
547 typedef MDB_ID pgno_t;
549 /** A transaction ID.
550 * See struct MDB_txn.mt_txnid for details.
552 typedef MDB_ID txnid_t;
554 /** @defgroup debug Debug Macros
558 /** Enable debug output. Needs variable argument macros (a C99 feature).
559 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
560 * read from and written to the database (used for free space management).
566 static int mdb_debug;
567 static txnid_t mdb_debug_start;
569 /** Print a debug message with printf formatting.
570 * Requires double parenthesis around 2 or more args.
572 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
573 # define DPRINTF0(fmt, ...) \
574 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
576 # define DPRINTF(args) ((void) 0)
578 /** Print a debug string.
579 * The string is printed literally, with no format processing.
581 #define DPUTS(arg) DPRINTF(("%s", arg))
582 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
584 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
587 /** @brief The maximum size of a database page.
589 * It is 32k or 64k, since value-PAGEBASE must fit in
590 * #MDB_page.%mp_upper.
592 * LMDB will use database pages < OS pages if needed.
593 * That causes more I/O in write transactions: The OS must
594 * know (read) the whole page before writing a partial page.
596 * Note that we don't currently support Huge pages. On Linux,
597 * regular data files cannot use Huge pages, and in general
598 * Huge pages aren't actually pageable. We rely on the OS
599 * demand-pager to read our data and page it out when memory
600 * pressure from other processes is high. So until OSs have
601 * actual paging support for Huge pages, they're not viable.
603 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
605 /** The minimum number of keys required in a database page.
606 * Setting this to a larger value will place a smaller bound on the
607 * maximum size of a data item. Data items larger than this size will
608 * be pushed into overflow pages instead of being stored directly in
609 * the B-tree node. This value used to default to 4. With a page size
610 * of 4096 bytes that meant that any item larger than 1024 bytes would
611 * go into an overflow page. That also meant that on average 2-3KB of
612 * each overflow page was wasted space. The value cannot be lower than
613 * 2 because then there would no longer be a tree structure. With this
614 * value, items larger than 2KB will go into overflow pages, and on
615 * average only 1KB will be wasted.
617 #define MDB_MINKEYS 2
619 /** A stamp that identifies a file as an LMDB file.
620 * There's nothing special about this value other than that it is easily
621 * recognizable, and it will reflect any byte order mismatches.
623 #define MDB_MAGIC 0xBEEFC0DE
625 /** The version number for a database's datafile format. */
626 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
627 /** The version number for a database's lockfile format. */
628 #define MDB_LOCK_VERSION ((MDB_DEVEL) ? 999 : 2)
629 /** Number of bits representing #MDB_LOCK_VERSION in #MDB_LOCK_FORMAT.
630 * The remaining bits must leave room for #MDB_lock_desc.
632 #define MDB_LOCK_VERSION_BITS 12
634 /** @brief The max size of a key we can write, or 0 for computed max.
636 * This macro should normally be left alone or set to 0.
637 * Note that a database with big keys or dupsort data cannot be
638 * reliably modified by a liblmdb which uses a smaller max.
639 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
641 * Other values are allowed, for backwards compat. However:
642 * A value bigger than the computed max can break if you do not
643 * know what you are doing, and liblmdb <= 0.9.10 can break when
644 * modifying a DB with keys/dupsort data bigger than its max.
646 * Data items in an #MDB_DUPSORT database are also limited to
647 * this size, since they're actually keys of a sub-DB. Keys and
648 * #MDB_DUPSORT data items must fit on a node in a regular page.
650 #ifndef MDB_MAXKEYSIZE
651 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
654 /** The maximum size of a key we can write to the environment. */
656 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
658 #define ENV_MAXKEY(env) ((env)->me_maxkey)
661 /** @brief The maximum size of a data item.
663 * We only store a 32 bit value for node sizes.
665 #define MAXDATASIZE 0xffffffffUL
668 /** Key size which fits in a #DKBUF.
671 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
674 * This is used for printing a hex dump of a key's contents.
676 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
677 /** Display a key in hex.
679 * Invoke a function to display a key in hex.
681 #define DKEY(x) mdb_dkey(x, kbuf)
687 /** An invalid page number.
688 * Mainly used to denote an empty tree.
690 #define P_INVALID (~(pgno_t)0)
692 /** Test if the flags \b f are set in a flag word \b w. */
693 #define F_ISSET(w, f) (((w) & (f)) == (f))
695 /** Round \b n up to an even number. */
696 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
698 /** Least significant 1-bit of \b n. n must be of an unsigned type. */
699 #define LOW_BIT(n) ((n) & (-(n)))
701 /** (log2(\b p2) % \b n), for p2 = power of 2 and 0 < n < 8. */
702 #define LOG2_MOD(p2, n) (7 - 86 / ((p2) % ((1U<<(n))-1) + 11))
703 /* Explanation: Let p2 = 2**(n*y + x), x<n and M = (1U<<n)-1. Now p2 =
704 * (M+1)**y * 2**x = 2**x (mod M). Finally "/" "happens" to return 7-x.
707 /** Should be alignment of \b type. Ensure it is a power of 2. */
708 #define ALIGNOF2(type) \
709 LOW_BIT(offsetof(struct { char ch_; type align_; }, align_))
711 /** Used for offsets within a single page.
712 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
715 typedef uint16_t indx_t;
717 typedef unsigned long long mdb_hash_t;
719 /** Default size of memory map.
720 * This is certainly too small for any actual applications. Apps should always set
721 * the size explicitly using #mdb_env_set_mapsize().
723 #define DEFAULT_MAPSIZE 1048576
725 /** @defgroup readers Reader Lock Table
726 * Readers don't acquire any locks for their data access. Instead, they
727 * simply record their transaction ID in the reader table. The reader
728 * mutex is needed just to find an empty slot in the reader table. The
729 * slot's address is saved in thread-specific data so that subsequent read
730 * transactions started by the same thread need no further locking to proceed.
732 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
734 * No reader table is used if the database is on a read-only filesystem, or
735 * if #MDB_NOLOCK is set.
737 * Since the database uses multi-version concurrency control, readers don't
738 * actually need any locking. This table is used to keep track of which
739 * readers are using data from which old transactions, so that we'll know
740 * when a particular old transaction is no longer in use. Old transactions
741 * that have discarded any data pages can then have those pages reclaimed
742 * for use by a later write transaction.
744 * The lock table is constructed such that reader slots are aligned with the
745 * processor's cache line size. Any slot is only ever used by one thread.
746 * This alignment guarantees that there will be no contention or cache
747 * thrashing as threads update their own slot info, and also eliminates
748 * any need for locking when accessing a slot.
750 * A writer thread will scan every slot in the table to determine the oldest
751 * outstanding reader transaction. Any freed pages older than this will be
752 * reclaimed by the writer. The writer doesn't use any locks when scanning
753 * this table. This means that there's no guarantee that the writer will
754 * see the most up-to-date reader info, but that's not required for correct
755 * operation - all we need is to know the upper bound on the oldest reader,
756 * we don't care at all about the newest reader. So the only consequence of
757 * reading stale information here is that old pages might hang around a
758 * while longer before being reclaimed. That's actually good anyway, because
759 * the longer we delay reclaiming old pages, the more likely it is that a
760 * string of contiguous pages can be found after coalescing old pages from
761 * many old transactions together.
764 /** Number of slots in the reader table.
765 * This value was chosen somewhat arbitrarily. 126 readers plus a
766 * couple mutexes fit exactly into 8KB on my development machine.
767 * Applications should set the table size using #mdb_env_set_maxreaders().
769 #define DEFAULT_READERS 126
771 /** The size of a CPU cache line in bytes. We want our lock structures
772 * aligned to this size to avoid false cache line sharing in the
774 * This value works for most CPUs. For Itanium this should be 128.
780 /** The information we store in a single slot of the reader table.
781 * In addition to a transaction ID, we also record the process and
782 * thread ID that owns a slot, so that we can detect stale information,
783 * e.g. threads or processes that went away without cleaning up.
784 * @note We currently don't check for stale records. We simply re-init
785 * the table when we know that we're the only process opening the
788 typedef struct MDB_rxbody {
789 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
790 * Multiple readers that start at the same time will probably have the
791 * same ID here. Again, it's not important to exclude them from
792 * anything; all we need to know is which version of the DB they
793 * started from so we can avoid overwriting any data used in that
794 * particular version.
796 volatile txnid_t mrb_txnid;
797 /** The process ID of the process owning this reader txn. */
798 volatile MDB_PID_T mrb_pid;
799 /** The thread ID of the thread owning this txn. */
800 volatile MDB_THR_T mrb_tid;
803 /** The actual reader record, with cacheline padding. */
804 typedef struct MDB_reader {
807 /** shorthand for mrb_txnid */
808 #define mr_txnid mru.mrx.mrb_txnid
809 #define mr_pid mru.mrx.mrb_pid
810 #define mr_tid mru.mrx.mrb_tid
811 /** cache line alignment */
812 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
816 /** The header for the reader table.
817 * The table resides in a memory-mapped file. (This is a different file
818 * than is used for the main database.)
820 * For POSIX the actual mutexes reside in the shared memory of this
821 * mapped file. On Windows, mutexes are named objects allocated by the
822 * kernel; we store the mutex names in this mapped file so that other
823 * processes can grab them. This same approach is also used on
824 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
825 * process-shared POSIX mutexes. For these cases where a named object
826 * is used, the object name is derived from a 64 bit FNV hash of the
827 * environment pathname. As such, naming collisions are extremely
828 * unlikely. If a collision occurs, the results are unpredictable.
830 typedef struct MDB_txbody {
831 /** Stamp identifying this as an LMDB file. It must be set
834 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
836 /** The ID of the last transaction committed to the database.
837 * This is recorded here only for convenience; the value can always
838 * be determined by reading the main database meta pages.
840 volatile txnid_t mtb_txnid;
841 /** The number of slots that have been used in the reader table.
842 * This always records the maximum count, it is not decremented
843 * when readers release their slots.
845 volatile unsigned mtb_numreaders;
846 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
847 /** Binary form of names of the reader/writer locks */
848 mdb_hash_t mtb_mutexid;
849 #elif defined(MDB_USE_SYSV_SEM)
853 /** Mutex protecting access to this table.
854 * This is the reader table lock used with LOCK_MUTEX().
856 mdb_mutex_t mtb_rmutex;
860 /** The actual reader table definition. */
861 typedef struct MDB_txninfo {
864 #define mti_magic mt1.mtb.mtb_magic
865 #define mti_format mt1.mtb.mtb_format
866 #define mti_rmutex mt1.mtb.mtb_rmutex
867 #define mti_txnid mt1.mtb.mtb_txnid
868 #define mti_numreaders mt1.mtb.mtb_numreaders
869 #define mti_mutexid mt1.mtb.mtb_mutexid
870 #ifdef MDB_USE_SYSV_SEM
871 #define mti_semid mt1.mtb.mtb_semid
872 #define mti_rlocked mt1.mtb.mtb_rlocked
874 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
876 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM))
878 #ifdef MDB_USE_SYSV_SEM
880 #define mti_wlocked mt2.mt2_wlocked
882 mdb_mutex_t mt2_wmutex;
883 #define mti_wmutex mt2.mt2_wmutex
885 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
888 MDB_reader mti_readers[1];
891 /** Lockfile format signature: version, features and field layout */
892 #define MDB_LOCK_FORMAT \
894 (((MDB_LOCK_VERSION) % (1U << MDB_LOCK_VERSION_BITS)) \
895 + MDB_lock_desc * (1U << MDB_LOCK_VERSION_BITS)))
897 /** Lock type and layout. Values 0-119. _WIN32 implies #MDB_PIDLOCK.
898 * Some low values are reserved for future tweaks.
901 # define MDB_LOCK_TYPE (0 + ALIGNOF2(mdb_hash_t)/8 % 2)
902 #elif defined MDB_USE_POSIX_SEM
903 # define MDB_LOCK_TYPE (4 + ALIGNOF2(mdb_hash_t)/8 % 2)
904 #elif defined MDB_USE_SYSV_SEM
905 # define MDB_LOCK_TYPE (8)
906 #elif defined MDB_USE_POSIX_MUTEX
907 /* We do not know the inside of a POSIX mutex and how to check if mutexes
908 * used by two executables are compatible. Just check alignment and size.
910 # define MDB_LOCK_TYPE (10 + \
911 LOG2_MOD(ALIGNOF2(pthread_mutex_t), 5) + \
912 sizeof(pthread_mutex_t) / 4U % 22 * 5)
916 /** Magic number for lockfile layout and features.
918 * This *attempts* to stop liblmdb variants compiled with conflicting
919 * options from using the lockfile at the same time and thus breaking
920 * it. It describes locking types, and sizes and sometimes alignment
921 * of the various lockfile items.
923 * The detected ranges are mostly guesswork, or based simply on how
924 * big they could be without using more bits. So we can tweak them
925 * in good conscience when updating #MDB_LOCK_VERSION.
928 /* Default CACHELINE=64 vs. other values (have seen mention of 32-256) */
929 (CACHELINE==64 ? 0 : 1 + LOG2_MOD(CACHELINE >> (CACHELINE>64), 5))
930 + 6 * (sizeof(MDB_PID_T)/4 % 3) /* legacy(2) to word(4/8)? */
931 + 18 * (sizeof(pthread_t)/4 % 5) /* can be struct{id, active data} */
932 + 90 * (sizeof(MDB_txbody) / CACHELINE % 3)
933 + 270 * (MDB_LOCK_TYPE % 120)
934 /* The above is < 270*120 < 2**15 */
935 + ((sizeof(txnid_t) == 8) << 15) /* 32bit/64bit */
936 + ((sizeof(MDB_reader) > CACHELINE) << 16)
937 /* Not really needed - implied by MDB_LOCK_TYPE != (_WIN32 locking) */
938 + (((MDB_PIDLOCK) != 0) << 17)
939 /* 18 bits total: Must be <= (32 - MDB_LOCK_VERSION_BITS). */
943 /** Common header for all page types. The page type depends on #mp_flags.
945 * #P_BRANCH and #P_LEAF pages have unsorted '#MDB_node's at the end, with
946 * sorted #mp_ptrs[] entries referring to them. Exception: #P_LEAF2 pages
947 * omit mp_ptrs and pack sorted #MDB_DUPFIXED values after the page header.
949 * #P_OVERFLOW records occupy one or more contiguous pages where only the
950 * first has a page header. They hold the real data of #F_BIGDATA nodes.
952 * #P_SUBP sub-pages are small leaf "pages" with duplicate data.
953 * A node with flag #F_DUPDATA but not #F_SUBDATA contains a sub-page.
954 * (Duplicate data can also go in sub-databases, which use normal pages.)
956 * #P_META pages contain #MDB_meta, the start point of an LMDB snapshot.
958 * Each non-metapage up to #MDB_meta.%mm_last_pg is reachable exactly once
959 * in the snapshot: Either used by a database or listed in a freeDB record.
961 typedef struct MDB_page {
962 #define mp_pgno mp_p.p_pgno
963 #define mp_next mp_p.p_next
965 pgno_t p_pgno; /**< page number */
966 struct MDB_page *p_next; /**< for in-memory list of freed pages */
968 uint16_t mp_pad; /**< key size if this is a LEAF2 page */
969 /** @defgroup mdb_page Page Flags
971 * Flags for the page headers.
974 #define P_BRANCH 0x01 /**< branch page */
975 #define P_LEAF 0x02 /**< leaf page */
976 #define P_OVERFLOW 0x04 /**< overflow page */
977 #define P_META 0x08 /**< meta page */
978 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
979 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
980 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
981 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
982 #define P_KEEP 0x8000 /**< leave this page alone during spill */
984 uint16_t mp_flags; /**< @ref mdb_page */
985 #define mp_lower mp_pb.pb.pb_lower
986 #define mp_upper mp_pb.pb.pb_upper
987 #define mp_pages mp_pb.pb_pages
990 indx_t pb_lower; /**< lower bound of free space */
991 indx_t pb_upper; /**< upper bound of free space */
993 uint32_t pb_pages; /**< number of overflow pages */
995 indx_t mp_ptrs[1]; /**< dynamic size */
998 /** Size of the page header, excluding dynamic data at the end */
999 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
1001 /** Address of first usable data byte in a page, after the header */
1002 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
1004 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
1005 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
1007 /** Number of nodes on a page */
1008 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
1010 /** The amount of space remaining in the page */
1011 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
1013 /** The percentage of space used in the page, in tenths of a percent. */
1014 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
1015 ((env)->me_psize - PAGEHDRSZ))
1016 /** The minimum page fill factor, in tenths of a percent.
1017 * Pages emptier than this are candidates for merging.
1019 #define FILL_THRESHOLD 250
1021 /** Test if a page is a leaf page */
1022 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
1023 /** Test if a page is a LEAF2 page */
1024 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
1025 /** Test if a page is a branch page */
1026 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
1027 /** Test if a page is an overflow page */
1028 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
1029 /** Test if a page is a sub page */
1030 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
1032 /** The number of overflow pages needed to store the given size. */
1033 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
1035 /** Link in #MDB_txn.%mt_loose_pgs list.
1036 * Kept outside the page header, which is needed when reusing the page.
1038 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
1040 /** Header for a single key/data pair within a page.
1041 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
1042 * We guarantee 2-byte alignment for 'MDB_node's.
1044 * #mn_lo and #mn_hi are used for data size on leaf nodes, and for child
1045 * pgno on branch nodes. On 64 bit platforms, #mn_flags is also used
1046 * for pgno. (Branch nodes have no flags). Lo and hi are in host byte
1047 * order in case some accesses can be optimized to 32-bit word access.
1049 * Leaf node flags describe node contents. #F_BIGDATA says the node's
1050 * data part is the page number of an overflow page with actual data.
1051 * #F_DUPDATA and #F_SUBDATA can be combined giving duplicate data in
1052 * a sub-page/sub-database, and named databases (just #F_SUBDATA).
1054 typedef struct MDB_node {
1055 /** part of data size or pgno
1057 #if BYTE_ORDER == LITTLE_ENDIAN
1058 unsigned short mn_lo, mn_hi;
1060 unsigned short mn_hi, mn_lo;
1063 /** @defgroup mdb_node Node Flags
1065 * Flags for node headers.
1068 #define F_BIGDATA 0x01 /**< data put on overflow page */
1069 #define F_SUBDATA 0x02 /**< data is a sub-database */
1070 #define F_DUPDATA 0x04 /**< data has duplicates */
1072 /** valid flags for #mdb_node_add() */
1073 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
1076 unsigned short mn_flags; /**< @ref mdb_node */
1077 unsigned short mn_ksize; /**< key size */
1078 char mn_data[1]; /**< key and data are appended here */
1081 /** Size of the node header, excluding dynamic data at the end */
1082 #define NODESIZE offsetof(MDB_node, mn_data)
1084 /** Bit position of top word in page number, for shifting mn_flags */
1085 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
1087 /** Size of a node in a branch page with a given key.
1088 * This is just the node header plus the key, there is no data.
1090 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
1092 /** Size of a node in a leaf page with a given key and data.
1093 * This is node header plus key plus data size.
1095 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
1097 /** Address of node \b i in page \b p */
1098 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
1100 /** Address of the key for the node */
1101 #define NODEKEY(node) (void *)((node)->mn_data)
1103 /** Address of the data for a node */
1104 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
1106 /** Get the page number pointed to by a branch node */
1107 #define NODEPGNO(node) \
1108 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
1109 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
1110 /** Set the page number in a branch node */
1111 #define SETPGNO(node,pgno) do { \
1112 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
1113 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
1115 /** Get the size of the data in a leaf node */
1116 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
1117 /** Set the size of the data for a leaf node */
1118 #define SETDSZ(node,size) do { \
1119 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
1120 /** The size of a key in a node */
1121 #define NODEKSZ(node) ((node)->mn_ksize)
1123 /** Copy a page number from src to dst */
1124 #ifdef MISALIGNED_OK
1125 #define COPY_PGNO(dst,src) dst = src
1127 #if MDB_SIZE_MAX > 0xffffffffU
1128 #define COPY_PGNO(dst,src) do { \
1129 unsigned short *s, *d; \
1130 s = (unsigned short *)&(src); \
1131 d = (unsigned short *)&(dst); \
1138 #define COPY_PGNO(dst,src) do { \
1139 unsigned short *s, *d; \
1140 s = (unsigned short *)&(src); \
1141 d = (unsigned short *)&(dst); \
1147 /** The address of a key in a LEAF2 page.
1148 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
1149 * There are no node headers, keys are stored contiguously.
1151 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
1153 /** Set the \b node's key into \b keyptr, if requested. */
1154 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
1155 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
1157 /** Set the \b node's key into \b key. */
1158 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
1160 /** Information about a single database in the environment. */
1161 typedef struct MDB_db {
1162 uint32_t md_pad; /**< also ksize for LEAF2 pages */
1163 uint16_t md_flags; /**< @ref mdb_dbi_open */
1164 uint16_t md_depth; /**< depth of this tree */
1165 pgno_t md_branch_pages; /**< number of internal pages */
1166 pgno_t md_leaf_pages; /**< number of leaf pages */
1167 pgno_t md_overflow_pages; /**< number of overflow pages */
1168 mdb_size_t md_entries; /**< number of data items */
1169 pgno_t md_root; /**< the root page of this tree */
1172 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
1173 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
1174 /** #mdb_dbi_open() flags */
1175 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
1176 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
1178 /** Handle for the DB used to track free pages. */
1180 /** Handle for the default DB. */
1182 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
1185 /** Number of meta pages - also hardcoded elsewhere */
1188 /** Meta page content.
1189 * A meta page is the start point for accessing a database snapshot.
1190 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
1192 typedef struct MDB_meta {
1193 /** Stamp identifying this as an LMDB file. It must be set
1196 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
1197 uint32_t mm_version;
1199 union { /* always zero since we don't support fixed mapping in MDB_VL32 */
1203 #define mm_address mm_un.mmun_address
1205 void *mm_address; /**< address for fixed mapping */
1207 mdb_size_t mm_mapsize; /**< size of mmap region */
1208 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
1209 /** The size of pages used in this DB */
1210 #define mm_psize mm_dbs[FREE_DBI].md_pad
1211 /** Any persistent environment flags. @ref mdb_env */
1212 #define mm_flags mm_dbs[FREE_DBI].md_flags
1213 /** Last used page in the datafile.
1214 * Actually the file may be shorter if the freeDB lists the final pages.
1217 volatile txnid_t mm_txnid; /**< txnid that committed this page */
1220 /** Buffer for a stack-allocated meta page.
1221 * The members define size and alignment, and silence type
1222 * aliasing warnings. They are not used directly; that could
1223 * mean incorrectly using several union members in parallel.
1225 typedef union MDB_metabuf {
1228 char mm_pad[PAGEHDRSZ];
1233 /** Auxiliary DB info.
1234 * The information here is mostly static/read-only. There is
1235 * only a single copy of this record in the environment.
1237 typedef struct MDB_dbx {
1238 MDB_val md_name; /**< name of the database */
1239 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1240 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1241 MDB_rel_func *md_rel; /**< user relocate function */
1242 void *md_relctx; /**< user-provided context for md_rel */
1245 /** A database transaction.
1246 * Every operation requires a transaction handle.
1249 MDB_txn *mt_parent; /**< parent of a nested txn */
1250 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1252 pgno_t mt_next_pgno; /**< next unallocated page */
1254 pgno_t mt_last_pgno; /**< last written page */
1256 /** The ID of this transaction. IDs are integers incrementing from 1.
1257 * Only committed write transactions increment the ID. If a transaction
1258 * aborts, the ID may be re-used by the next writer.
1261 MDB_env *mt_env; /**< the DB environment */
1262 /** The list of pages that became unused during this transaction.
1264 MDB_IDL mt_free_pgs;
1265 /** The list of loose pages that became unused and may be reused
1266 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1268 MDB_page *mt_loose_pgs;
1269 /** Number of loose pages (#mt_loose_pgs) */
1271 /** The sorted list of dirty pages we temporarily wrote to disk
1272 * because the dirty list was full. page numbers in here are
1273 * shifted left by 1, deleted slots have the LSB set.
1275 MDB_IDL mt_spill_pgs;
1277 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1278 MDB_ID2L dirty_list;
1279 /** For read txns: This thread/txn's reader table slot, or NULL. */
1282 /** Array of records for each DB known in the environment. */
1284 /** Array of MDB_db records for each known DB */
1286 /** Array of sequence numbers for each DB handle */
1287 unsigned int *mt_dbiseqs;
1288 /** @defgroup mt_dbflag Transaction DB Flags
1292 #define DB_DIRTY 0x01 /**< DB was written in this txn */
1293 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1294 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1295 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1296 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1297 #define DB_DUPDATA 0x20 /**< DB is #MDB_DUPSORT data */
1299 /** In write txns, array of cursors for each DB */
1300 MDB_cursor **mt_cursors;
1301 /** Array of flags for each DB */
1302 unsigned char *mt_dbflags;
1304 /** List of read-only pages (actually chunks) */
1306 /** We map chunks of 16 pages. Even though Windows uses 4KB pages, all
1307 * mappings must begin on 64KB boundaries. So we round off all pgnos to
1308 * a chunk boundary. We do the same on Linux for symmetry, and also to
1309 * reduce the frequency of mmap/munmap calls.
1311 #define MDB_RPAGE_CHUNK 16
1312 #define MDB_TRPAGE_SIZE 4096 /**< size of #mt_rpages array of chunks */
1313 #define MDB_TRPAGE_MAX (MDB_TRPAGE_SIZE-1) /**< maximum chunk index */
1314 unsigned int mt_rpcheck; /**< threshold for reclaiming unref'd chunks */
1316 /** Number of DB records in use, or 0 when the txn is finished.
1317 * This number only ever increments until the txn finishes; we
1318 * don't decrement it when individual DB handles are closed.
1322 /** @defgroup mdb_txn Transaction Flags
1326 /** #mdb_txn_begin() flags */
1327 #define MDB_TXN_BEGIN_FLAGS (MDB_NOMETASYNC|MDB_NOSYNC|MDB_RDONLY)
1328 #define MDB_TXN_NOMETASYNC MDB_NOMETASYNC /**< don't sync meta for this txn on commit */
1329 #define MDB_TXN_NOSYNC MDB_NOSYNC /**< don't sync this txn on commit */
1330 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1331 /* internal txn flags */
1332 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1333 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1334 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1335 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1336 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1337 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1338 /** most operations on the txn are currently illegal */
1339 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1341 unsigned int mt_flags; /**< @ref mdb_txn */
1342 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1343 * Includes ancestor txns' dirty pages not hidden by other txns'
1344 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1345 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1347 unsigned int mt_dirty_room;
1350 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1351 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1352 * raise this on a 64 bit machine.
1354 #define CURSOR_STACK 32
1358 /** Cursors are used for all DB operations.
1359 * A cursor holds a path of (page pointer, key index) from the DB
1360 * root to a position in the DB, plus other state. #MDB_DUPSORT
1361 * cursors include an xcursor to the current data item. Write txns
1362 * track their cursors and keep them up to date when data moves.
1363 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1364 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1367 /** Next cursor on this DB in this txn */
1368 MDB_cursor *mc_next;
1369 /** Backup of the original cursor if this cursor is a shadow */
1370 MDB_cursor *mc_backup;
1371 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1372 struct MDB_xcursor *mc_xcursor;
1373 /** The transaction that owns this cursor */
1375 /** The database handle this cursor operates on */
1377 /** The database record for this cursor */
1379 /** The database auxiliary record for this cursor */
1381 /** The @ref mt_dbflag for this database */
1382 unsigned char *mc_dbflag;
1383 unsigned short mc_snum; /**< number of pushed pages */
1384 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1385 /** @defgroup mdb_cursor Cursor Flags
1387 * Cursor state flags.
1390 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1391 #define C_EOF 0x02 /**< No more data */
1392 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1393 #define C_DEL 0x08 /**< last op was a cursor_del */
1394 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1395 #define C_WRITEMAP MDB_TXN_WRITEMAP /**< Copy of txn flag */
1396 /** Read-only cursor into the txn's original snapshot in the map.
1397 * Set for read-only txns, and in #mdb_page_alloc() for #FREE_DBI when
1398 * #MDB_DEVEL & 2. Only implements code which is necessary for this.
1400 #define C_ORIG_RDONLY MDB_TXN_RDONLY
1402 unsigned int mc_flags; /**< @ref mdb_cursor */
1403 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1404 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1406 MDB_page *mc_ovpg; /**< a referenced overflow page */
1407 # define MC_OVPG(mc) ((mc)->mc_ovpg)
1408 # define MC_SET_OVPG(mc, pg) ((mc)->mc_ovpg = (pg))
1410 # define MC_OVPG(mc) ((MDB_page *)0)
1411 # define MC_SET_OVPG(mc, pg) ((void)0)
1415 /** Context for sorted-dup records.
1416 * We could have gone to a fully recursive design, with arbitrarily
1417 * deep nesting of sub-databases. But for now we only handle these
1418 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1420 typedef struct MDB_xcursor {
1421 /** A sub-cursor for traversing the Dup DB */
1422 MDB_cursor mx_cursor;
1423 /** The database record for this Dup DB */
1425 /** The auxiliary DB record for this Dup DB */
1427 /** The @ref mt_dbflag for this Dup DB */
1428 unsigned char mx_dbflag;
1431 /** Check if there is an inited xcursor */
1432 #define XCURSOR_INITED(mc) \
1433 ((mc)->mc_xcursor && ((mc)->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
1435 /** Update the xcursor's sub-page pointer, if any, in \b mc. Needed
1436 * when the node which contains the sub-page may have moved. Called
1437 * with leaf page \b mp = mc->mc_pg[\b top].
1439 #define XCURSOR_REFRESH(mc, top, mp) do { \
1440 MDB_page *xr_pg = (mp); \
1441 MDB_node *xr_node; \
1442 if (!XCURSOR_INITED(mc) || (mc)->mc_ki[top] >= NUMKEYS(xr_pg)) break; \
1443 xr_node = NODEPTR(xr_pg, (mc)->mc_ki[top]); \
1444 if ((xr_node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) \
1445 (mc)->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(xr_node); \
1448 /** State of FreeDB old pages, stored in the MDB_env */
1449 typedef struct MDB_pgstate {
1450 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1451 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1454 /** The database environment. */
1456 HANDLE me_fd; /**< The main data file */
1457 HANDLE me_lfd; /**< The lock file */
1458 HANDLE me_mfd; /**< For writing and syncing the meta pages */
1459 #if defined(MDB_VL32) && defined(_WIN32)
1460 HANDLE me_fmh; /**< File Mapping handle */
1462 /** Failed to update the meta page. Probably an I/O error. */
1463 #define MDB_FATAL_ERROR 0x80000000U
1464 /** Some fields are initialized. */
1465 #define MDB_ENV_ACTIVE 0x20000000U
1466 /** me_txkey is set */
1467 #define MDB_ENV_TXKEY 0x10000000U
1468 /** fdatasync is unreliable */
1469 #define MDB_FSYNCONLY 0x08000000U
1470 uint32_t me_flags; /**< @ref mdb_env */
1471 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1472 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1473 unsigned int me_maxreaders; /**< size of the reader table */
1474 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1475 volatile int me_close_readers;
1476 MDB_dbi me_numdbs; /**< number of DBs opened */
1477 MDB_dbi me_maxdbs; /**< size of the DB table */
1478 MDB_PID_T me_pid; /**< process ID of this env */
1479 char *me_path; /**< path to the DB files */
1480 char *me_map; /**< the memory map of the data file */
1481 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1482 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1483 void *me_pbuf; /**< scratch area for DUPSORT put() */
1484 MDB_txn *me_txn; /**< current write transaction */
1485 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1486 mdb_size_t me_mapsize; /**< size of the data memory map */
1487 off_t me_size; /**< current file size */
1488 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1489 MDB_dbx *me_dbxs; /**< array of static DB info */
1490 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1491 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1492 pthread_key_t me_txkey; /**< thread-key for readers */
1493 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1494 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1495 # define me_pglast me_pgstate.mf_pglast
1496 # define me_pghead me_pgstate.mf_pghead
1497 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1498 /** IDL of pages that became unused in a write txn */
1499 MDB_IDL me_free_pgs;
1500 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1501 MDB_ID2L me_dirty_list;
1502 /** Max number of freelist items that can fit in a single overflow page */
1504 /** Max size of a node on a page */
1505 unsigned int me_nodemax;
1506 #if !(MDB_MAXKEYSIZE)
1507 unsigned int me_maxkey; /**< max size of a key */
1509 int me_live_reader; /**< have liveness lock in reader table */
1511 int me_pidquery; /**< Used in OpenProcess */
1513 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1514 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1515 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1517 mdb_mutex_t me_rmutex;
1518 mdb_mutex_t me_wmutex;
1519 # if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
1520 /** Half-initialized name of mutexes, to be completed by #MUTEXNAME() */
1521 char me_mutexname[sizeof(MUTEXNAME_PREFIX) + 11];
1525 MDB_ID3L me_rpages; /**< like #mt_rpages, but global to env */
1526 pthread_mutex_t me_rpmutex; /**< control access to #me_rpages */
1527 #define MDB_ERPAGE_SIZE 16384
1528 #define MDB_ERPAGE_MAX (MDB_ERPAGE_SIZE-1)
1529 unsigned int me_rpcheck;
1531 void *me_userctx; /**< User-settable context */
1532 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1535 /** Nested transaction */
1536 typedef struct MDB_ntxn {
1537 MDB_txn mnt_txn; /**< the transaction */
1538 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1541 /** max number of pages to commit in one writev() call */
1542 #define MDB_COMMIT_PAGES 64
1543 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1544 #undef MDB_COMMIT_PAGES
1545 #define MDB_COMMIT_PAGES IOV_MAX
1548 /** max bytes to write in one call */
1549 #define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
1551 /** Check \b txn and \b dbi arguments to a function */
1552 #define TXN_DBI_EXIST(txn, dbi, validity) \
1553 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1555 /** Check for misused \b dbi handles */
1556 #define TXN_DBI_CHANGED(txn, dbi) \
1557 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1559 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1560 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1561 static int mdb_page_touch(MDB_cursor *mc);
1563 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1564 "reset-tmp", "fail-begin", "fail-beginchild"}
1566 /* mdb_txn_end operation number, for logging */
1567 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1568 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1570 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1571 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1572 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1573 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1574 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1576 static int mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
1577 static int mdb_page_search_root(MDB_cursor *mc,
1578 MDB_val *key, int modify);
1579 #define MDB_PS_MODIFY 1
1580 #define MDB_PS_ROOTONLY 2
1581 #define MDB_PS_FIRST 4
1582 #define MDB_PS_LAST 8
1583 static int mdb_page_search(MDB_cursor *mc,
1584 MDB_val *key, int flags);
1585 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1587 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1588 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1589 pgno_t newpgno, unsigned int nflags);
1591 static int mdb_env_read_header(MDB_env *env, int prev, MDB_meta *meta);
1592 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1593 static int mdb_env_write_meta(MDB_txn *txn);
1594 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1595 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1597 static void mdb_env_close0(MDB_env *env, int excl);
1599 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1600 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1601 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1602 static void mdb_node_del(MDB_cursor *mc, int ksize);
1603 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1604 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1605 static int mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
1606 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1607 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1609 static int mdb_rebalance(MDB_cursor *mc);
1610 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1612 static void mdb_cursor_pop(MDB_cursor *mc);
1613 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1615 static int mdb_cursor_del0(MDB_cursor *mc);
1616 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1617 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1618 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1619 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1620 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1622 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1623 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1625 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1626 static void mdb_xcursor_init0(MDB_cursor *mc);
1627 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1628 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1630 static int mdb_drop0(MDB_cursor *mc, int subs);
1631 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1632 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1635 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1638 /** Compare two items pointing at '#mdb_size_t's of unknown alignment. */
1639 #ifdef MISALIGNED_OK
1640 # define mdb_cmp_clong mdb_cmp_long
1642 # define mdb_cmp_clong mdb_cmp_cint
1645 /** True if we need #mdb_cmp_clong() instead of \b cmp for #MDB_INTEGERDUP */
1646 #define NEED_CMP_CLONG(cmp, ksize) \
1647 (UINT_MAX < MDB_SIZE_MAX && \
1648 (cmp) == mdb_cmp_int && (ksize) == sizeof(mdb_size_t))
1651 static SECURITY_DESCRIPTOR mdb_null_sd;
1652 static SECURITY_ATTRIBUTES mdb_all_sa;
1653 static int mdb_sec_inited;
1656 static int utf8_to_utf16(const char *src, struct MDB_name *dst, int xtra);
1659 /** Return the library version info. */
1661 mdb_version(int *major, int *minor, int *patch)
1663 if (major) *major = MDB_VERSION_MAJOR;
1664 if (minor) *minor = MDB_VERSION_MINOR;
1665 if (patch) *patch = MDB_VERSION_PATCH;
1666 return MDB_VERSION_STRING;
1669 /** Table of descriptions for LMDB @ref errors */
1670 static char *const mdb_errstr[] = {
1671 "MDB_KEYEXIST: Key/data pair already exists",
1672 "MDB_NOTFOUND: No matching key/data pair found",
1673 "MDB_PAGE_NOTFOUND: Requested page not found",
1674 "MDB_CORRUPTED: Located page was wrong type",
1675 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1676 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1677 "MDB_INVALID: File is not an LMDB file",
1678 "MDB_MAP_FULL: Environment mapsize limit reached",
1679 "MDB_DBS_FULL: Environment maxdbs limit reached",
1680 "MDB_READERS_FULL: Environment maxreaders limit reached",
1681 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1682 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1683 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1684 "MDB_PAGE_FULL: Internal error - page has no more space",
1685 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1686 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1687 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1688 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1689 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1690 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1691 "MDB_PROBLEM: Unexpected problem - txn should abort",
1695 mdb_strerror(int err)
1698 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1699 * This works as long as no function between the call to mdb_strerror
1700 * and the actual use of the message uses more than 4K of stack.
1702 #define MSGSIZE 1024
1703 #define PADSIZE 4096
1704 char buf[MSGSIZE+PADSIZE], *ptr = buf;
1708 return ("Successful return: 0");
1710 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1711 i = err - MDB_KEYEXIST;
1712 return mdb_errstr[i];
1716 /* These are the C-runtime error codes we use. The comment indicates
1717 * their numeric value, and the Win32 error they would correspond to
1718 * if the error actually came from a Win32 API. A major mess, we should
1719 * have used LMDB-specific error codes for everything.
1722 case ENOENT: /* 2, FILE_NOT_FOUND */
1723 case EIO: /* 5, ACCESS_DENIED */
1724 case ENOMEM: /* 12, INVALID_ACCESS */
1725 case EACCES: /* 13, INVALID_DATA */
1726 case EBUSY: /* 16, CURRENT_DIRECTORY */
1727 case EINVAL: /* 22, BAD_COMMAND */
1728 case ENOSPC: /* 28, OUT_OF_PAPER */
1729 return strerror(err);
1734 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1735 FORMAT_MESSAGE_IGNORE_INSERTS,
1736 NULL, err, 0, ptr, MSGSIZE, (va_list *)buf+MSGSIZE);
1739 return strerror(err);
1743 /** assert(3) variant in cursor context */
1744 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1745 /** assert(3) variant in transaction context */
1746 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1747 /** assert(3) variant in environment context */
1748 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1751 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1752 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1755 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1756 const char *func, const char *file, int line)
1759 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1760 file, line, expr_txt, func);
1761 if (env->me_assert_func)
1762 env->me_assert_func(env, buf);
1763 fprintf(stderr, "%s\n", buf);
1767 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1771 /** Return the page number of \b mp which may be sub-page, for debug output */
1773 mdb_dbg_pgno(MDB_page *mp)
1776 COPY_PGNO(ret, mp->mp_pgno);
1780 /** Display a key in hexadecimal and return the address of the result.
1781 * @param[in] key the key to display
1782 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1783 * @return The key in hexadecimal form.
1786 mdb_dkey(MDB_val *key, char *buf)
1789 unsigned char *c = key->mv_data;
1795 if (key->mv_size > DKBUF_MAXKEYSIZE)
1796 return "MDB_MAXKEYSIZE";
1797 /* may want to make this a dynamic check: if the key is mostly
1798 * printable characters, print it as-is instead of converting to hex.
1802 for (i=0; i<key->mv_size; i++)
1803 ptr += sprintf(ptr, "%02x", *c++);
1805 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1811 mdb_leafnode_type(MDB_node *n)
1813 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1814 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1815 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1818 /** Display all the keys in the page. */
1820 mdb_page_list(MDB_page *mp)
1822 pgno_t pgno = mdb_dbg_pgno(mp);
1823 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1825 unsigned int i, nkeys, nsize, total = 0;
1829 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1830 case P_BRANCH: type = "Branch page"; break;
1831 case P_LEAF: type = "Leaf page"; break;
1832 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1833 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1834 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1836 fprintf(stderr, "Overflow page %"Yu" pages %u%s\n",
1837 pgno, mp->mp_pages, state);
1840 fprintf(stderr, "Meta-page %"Yu" txnid %"Yu"\n",
1841 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1844 fprintf(stderr, "Bad page %"Yu" flags 0x%X\n", pgno, mp->mp_flags);
1848 nkeys = NUMKEYS(mp);
1849 fprintf(stderr, "%s %"Yu" numkeys %d%s\n", type, pgno, nkeys, state);
1851 for (i=0; i<nkeys; i++) {
1852 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1853 key.mv_size = nsize = mp->mp_pad;
1854 key.mv_data = LEAF2KEY(mp, i, nsize);
1856 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1859 node = NODEPTR(mp, i);
1860 key.mv_size = node->mn_ksize;
1861 key.mv_data = node->mn_data;
1862 nsize = NODESIZE + key.mv_size;
1863 if (IS_BRANCH(mp)) {
1864 fprintf(stderr, "key %d: page %"Yu", %s\n", i, NODEPGNO(node),
1868 if (F_ISSET(node->mn_flags, F_BIGDATA))
1869 nsize += sizeof(pgno_t);
1871 nsize += NODEDSZ(node);
1873 nsize += sizeof(indx_t);
1874 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1875 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1877 total = EVEN(total);
1879 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1880 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1884 mdb_cursor_chk(MDB_cursor *mc)
1890 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1891 for (i=0; i<mc->mc_top; i++) {
1893 node = NODEPTR(mp, mc->mc_ki[i]);
1894 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1897 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1899 if (XCURSOR_INITED(mc)) {
1900 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1901 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1902 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1910 /** Count all the pages in each DB and in the freelist
1911 * and make sure it matches the actual number of pages
1913 * All named DBs must be open for a correct count.
1915 static void mdb_audit(MDB_txn *txn)
1919 MDB_ID freecount, count;
1924 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1925 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1926 freecount += *(MDB_ID *)data.mv_data;
1927 mdb_tassert(txn, rc == MDB_NOTFOUND);
1930 for (i = 0; i<txn->mt_numdbs; i++) {
1932 if (!(txn->mt_dbflags[i] & DB_VALID))
1934 mdb_cursor_init(&mc, txn, i, &mx);
1935 if (txn->mt_dbs[i].md_root == P_INVALID)
1937 count += txn->mt_dbs[i].md_branch_pages +
1938 txn->mt_dbs[i].md_leaf_pages +
1939 txn->mt_dbs[i].md_overflow_pages;
1940 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1941 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1942 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1945 mp = mc.mc_pg[mc.mc_top];
1946 for (j=0; j<NUMKEYS(mp); j++) {
1947 MDB_node *leaf = NODEPTR(mp, j);
1948 if (leaf->mn_flags & F_SUBDATA) {
1950 memcpy(&db, NODEDATA(leaf), sizeof(db));
1951 count += db.md_branch_pages + db.md_leaf_pages +
1952 db.md_overflow_pages;
1956 mdb_tassert(txn, rc == MDB_NOTFOUND);
1959 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1960 fprintf(stderr, "audit: %"Yu" freecount: %"Yu" count: %"Yu" total: %"Yu" next_pgno: %"Yu"\n",
1961 txn->mt_txnid, freecount, count+NUM_METAS,
1962 freecount+count+NUM_METAS, txn->mt_next_pgno);
1968 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1970 return txn->mt_dbxs[dbi].md_cmp(a, b);
1974 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1976 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1977 if (NEED_CMP_CLONG(dcmp, a->mv_size))
1978 dcmp = mdb_cmp_clong;
1982 /** Allocate memory for a page.
1983 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1984 * Set #MDB_TXN_ERROR on failure.
1987 mdb_page_malloc(MDB_txn *txn, unsigned num)
1989 MDB_env *env = txn->mt_env;
1990 MDB_page *ret = env->me_dpages;
1991 size_t psize = env->me_psize, sz = psize, off;
1992 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1993 * For a single page alloc, we init everything after the page header.
1994 * For multi-page, we init the final page; if the caller needed that
1995 * many pages they will be filling in at least up to the last page.
1999 VGMEMP_ALLOC(env, ret, sz);
2000 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
2001 env->me_dpages = ret->mp_next;
2004 psize -= off = PAGEHDRSZ;
2009 if ((ret = malloc(sz)) != NULL) {
2010 VGMEMP_ALLOC(env, ret, sz);
2011 if (!(env->me_flags & MDB_NOMEMINIT)) {
2012 memset((char *)ret + off, 0, psize);
2016 txn->mt_flags |= MDB_TXN_ERROR;
2020 /** Free a single page.
2021 * Saves single pages to a list, for future reuse.
2022 * (This is not used for multi-page overflow pages.)
2025 mdb_page_free(MDB_env *env, MDB_page *mp)
2027 mp->mp_next = env->me_dpages;
2028 VGMEMP_FREE(env, mp);
2029 env->me_dpages = mp;
2032 /** Free a dirty page */
2034 mdb_dpage_free(MDB_env *env, MDB_page *dp)
2036 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
2037 mdb_page_free(env, dp);
2039 /* large pages just get freed directly */
2040 VGMEMP_FREE(env, dp);
2045 /** Return all dirty pages to dpage list */
2047 mdb_dlist_free(MDB_txn *txn)
2049 MDB_env *env = txn->mt_env;
2050 MDB_ID2L dl = txn->mt_u.dirty_list;
2051 unsigned i, n = dl[0].mid;
2053 for (i = 1; i <= n; i++) {
2054 mdb_dpage_free(env, dl[i].mptr);
2061 mdb_page_unref(MDB_txn *txn, MDB_page *mp)
2064 MDB_ID3L tl = txn->mt_rpages;
2066 if (mp->mp_flags & (P_SUBP|P_DIRTY))
2068 rem = mp->mp_pgno & (MDB_RPAGE_CHUNK-1);
2069 pgno = mp->mp_pgno ^ rem;
2070 x = mdb_mid3l_search(tl, pgno);
2071 if (x != tl[0].mid && tl[x+1].mid == mp->mp_pgno)
2076 #define MDB_PAGE_UNREF(txn, mp) mdb_page_unref(txn, mp)
2079 mdb_cursor_unref(MDB_cursor *mc)
2082 if (mc->mc_txn->mt_rpages[0].mid) {
2083 if (!mc->mc_snum || !mc->mc_pg[0] || IS_SUBP(mc->mc_pg[0]))
2085 for (i=0; i<mc->mc_snum; i++)
2086 mdb_page_unref(mc->mc_txn, mc->mc_pg[i]);
2088 mdb_page_unref(mc->mc_txn, mc->mc_ovpg);
2092 mc->mc_snum = mc->mc_top = 0;
2093 mc->mc_pg[0] = NULL;
2094 mc->mc_flags &= ~C_INITIALIZED;
2096 #define MDB_CURSOR_UNREF(mc, force) \
2097 (((force) || ((mc)->mc_flags & C_INITIALIZED)) \
2098 ? mdb_cursor_unref(mc) \
2102 #define MDB_PAGE_UNREF(txn, mp)
2103 #define MDB_CURSOR_UNREF(mc, force) ((void)0)
2104 #endif /* MDB_VL32 */
2106 /** Loosen or free a single page.
2107 * Saves single pages to a list for future reuse
2108 * in this same txn. It has been pulled from the freeDB
2109 * and already resides on the dirty list, but has been
2110 * deleted. Use these pages first before pulling again
2113 * If the page wasn't dirtied in this txn, just add it
2114 * to this txn's free list.
2117 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
2120 pgno_t pgno = mp->mp_pgno;
2121 MDB_txn *txn = mc->mc_txn;
2123 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
2124 if (txn->mt_parent) {
2125 MDB_ID2 *dl = txn->mt_u.dirty_list;
2126 /* If txn has a parent, make sure the page is in our
2130 unsigned x = mdb_mid2l_search(dl, pgno);
2131 if (x <= dl[0].mid && dl[x].mid == pgno) {
2132 if (mp != dl[x].mptr) { /* bad cursor? */
2133 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2134 txn->mt_flags |= MDB_TXN_ERROR;
2142 /* no parent txn, so it's just ours */
2147 DPRINTF(("loosen db %d page %"Yu, DDBI(mc), mp->mp_pgno));
2148 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
2149 txn->mt_loose_pgs = mp;
2150 txn->mt_loose_count++;
2151 mp->mp_flags |= P_LOOSE;
2153 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
2161 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
2162 * @param[in] mc A cursor handle for the current operation.
2163 * @param[in] pflags Flags of the pages to update:
2164 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
2165 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
2166 * @return 0 on success, non-zero on failure.
2169 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
2171 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
2172 MDB_txn *txn = mc->mc_txn;
2173 MDB_cursor *m3, *m0 = mc;
2178 int rc = MDB_SUCCESS, level;
2180 /* Mark pages seen by cursors: First m0, then tracked cursors */
2181 for (i = txn->mt_numdbs;; ) {
2182 if (mc->mc_flags & C_INITIALIZED) {
2183 for (m3 = mc;; m3 = &mx->mx_cursor) {
2185 for (j=0; j<m3->mc_snum; j++) {
2187 if ((mp->mp_flags & Mask) == pflags)
2188 mp->mp_flags ^= P_KEEP;
2190 mx = m3->mc_xcursor;
2191 /* Proceed to mx if it is at a sub-database */
2192 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
2194 if (! (mp && (mp->mp_flags & P_LEAF)))
2196 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
2197 if (!(leaf->mn_flags & F_SUBDATA))
2202 for (; !mc || mc == m0; mc = txn->mt_cursors[--i])
2209 /* Mark dirty root pages */
2210 for (i=0; i<txn->mt_numdbs; i++) {
2211 if (txn->mt_dbflags[i] & DB_DIRTY) {
2212 pgno_t pgno = txn->mt_dbs[i].md_root;
2213 if (pgno == P_INVALID)
2215 if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
2217 if ((dp->mp_flags & Mask) == pflags && level <= 1)
2218 dp->mp_flags ^= P_KEEP;
2226 static int mdb_page_flush(MDB_txn *txn, int keep);
2228 /** Spill pages from the dirty list back to disk.
2229 * This is intended to prevent running into #MDB_TXN_FULL situations,
2230 * but note that they may still occur in a few cases:
2231 * 1) our estimate of the txn size could be too small. Currently this
2232 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
2233 * 2) child txns may run out of space if their parents dirtied a
2234 * lot of pages and never spilled them. TODO: we probably should do
2235 * a preemptive spill during #mdb_txn_begin() of a child txn, if
2236 * the parent's dirty_room is below a given threshold.
2238 * Otherwise, if not using nested txns, it is expected that apps will
2239 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
2240 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
2241 * If the txn never references them again, they can be left alone.
2242 * If the txn only reads them, they can be used without any fuss.
2243 * If the txn writes them again, they can be dirtied immediately without
2244 * going thru all of the work of #mdb_page_touch(). Such references are
2245 * handled by #mdb_page_unspill().
2247 * Also note, we never spill DB root pages, nor pages of active cursors,
2248 * because we'll need these back again soon anyway. And in nested txns,
2249 * we can't spill a page in a child txn if it was already spilled in a
2250 * parent txn. That would alter the parent txns' data even though
2251 * the child hasn't committed yet, and we'd have no way to undo it if
2252 * the child aborted.
2254 * @param[in] m0 cursor A cursor handle identifying the transaction and
2255 * database for which we are checking space.
2256 * @param[in] key For a put operation, the key being stored.
2257 * @param[in] data For a put operation, the data being stored.
2258 * @return 0 on success, non-zero on failure.
2261 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
2263 MDB_txn *txn = m0->mc_txn;
2265 MDB_ID2L dl = txn->mt_u.dirty_list;
2266 unsigned int i, j, need;
2269 if (m0->mc_flags & C_SUB)
2272 /* Estimate how much space this op will take */
2273 i = m0->mc_db->md_depth;
2274 /* Named DBs also dirty the main DB */
2275 if (m0->mc_dbi >= CORE_DBS)
2276 i += txn->mt_dbs[MAIN_DBI].md_depth;
2277 /* For puts, roughly factor in the key+data size */
2279 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
2280 i += i; /* double it for good measure */
2283 if (txn->mt_dirty_room > i)
2286 if (!txn->mt_spill_pgs) {
2287 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
2288 if (!txn->mt_spill_pgs)
2291 /* purge deleted slots */
2292 MDB_IDL sl = txn->mt_spill_pgs;
2293 unsigned int num = sl[0];
2295 for (i=1; i<=num; i++) {
2302 /* Preserve pages which may soon be dirtied again */
2303 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2306 /* Less aggressive spill - we originally spilled the entire dirty list,
2307 * with a few exceptions for cursor pages and DB root pages. But this
2308 * turns out to be a lot of wasted effort because in a large txn many
2309 * of those pages will need to be used again. So now we spill only 1/8th
2310 * of the dirty pages. Testing revealed this to be a good tradeoff,
2311 * better than 1/2, 1/4, or 1/10.
2313 if (need < MDB_IDL_UM_MAX / 8)
2314 need = MDB_IDL_UM_MAX / 8;
2316 /* Save the page IDs of all the pages we're flushing */
2317 /* flush from the tail forward, this saves a lot of shifting later on. */
2318 for (i=dl[0].mid; i && need; i--) {
2319 MDB_ID pn = dl[i].mid << 1;
2321 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2323 /* Can't spill twice, make sure it's not already in a parent's
2326 if (txn->mt_parent) {
2328 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2329 if (tx2->mt_spill_pgs) {
2330 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2331 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2332 dp->mp_flags |= P_KEEP;
2340 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2344 mdb_midl_sort(txn->mt_spill_pgs);
2346 /* Flush the spilled part of dirty list */
2347 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2350 /* Reset any dirty pages we kept that page_flush didn't see */
2351 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2354 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2358 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2360 mdb_find_oldest(MDB_txn *txn)
2363 txnid_t mr, oldest = txn->mt_txnid - 1;
2364 if (txn->mt_env->me_txns) {
2365 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2366 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2377 /** Add a page to the txn's dirty list */
2379 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2382 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2384 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2385 insert = mdb_mid2l_append;
2387 insert = mdb_mid2l_insert;
2389 mid.mid = mp->mp_pgno;
2391 rc = insert(txn->mt_u.dirty_list, &mid);
2392 mdb_tassert(txn, rc == 0);
2393 txn->mt_dirty_room--;
2396 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2397 * me_pghead and mt_next_pgno. Set #MDB_TXN_ERROR on failure.
2399 * If there are free pages available from older transactions, they
2400 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2401 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2402 * and move me_pglast to say which records were consumed. Only this
2403 * function can create me_pghead and move me_pglast/mt_next_pgno.
2404 * When #MDB_DEVEL & 2, it is not affected by #mdb_freelist_save(): it
2405 * then uses the transaction's original snapshot of the freeDB.
2406 * @param[in] mc cursor A cursor handle identifying the transaction and
2407 * database for which we are allocating.
2408 * @param[in] num the number of pages to allocate.
2409 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2410 * will always be satisfied by a single contiguous chunk of memory.
2411 * @return 0 on success, non-zero on failure.
2414 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2416 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2417 /* Get at most <Max_retries> more freeDB records once me_pghead
2418 * has enough pages. If not enough, use new pages from the map.
2419 * If <Paranoid> and mc is updating the freeDB, only get new
2420 * records if me_pghead is empty. Then the freelist cannot play
2421 * catch-up with itself by growing while trying to save it.
2423 enum { Paranoid = 1, Max_retries = 500 };
2425 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2427 int rc, retry = num * 60;
2428 MDB_txn *txn = mc->mc_txn;
2429 MDB_env *env = txn->mt_env;
2430 pgno_t pgno, *mop = env->me_pghead;
2431 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2433 txnid_t oldest = 0, last;
2438 /* If there are any loose pages, just use them */
2439 if (num == 1 && txn->mt_loose_pgs) {
2440 np = txn->mt_loose_pgs;
2441 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2442 txn->mt_loose_count--;
2443 DPRINTF(("db %d use loose page %"Yu, DDBI(mc), np->mp_pgno));
2450 /* If our dirty list is already full, we can't do anything */
2451 if (txn->mt_dirty_room == 0) {
2456 for (op = MDB_FIRST;; op = MDB_NEXT) {
2461 /* Seek a big enough contiguous page range. Prefer
2462 * pages at the tail, just truncating the list.
2468 if (mop[i-n2] == pgno+n2)
2475 if (op == MDB_FIRST) { /* 1st iteration */
2476 /* Prepare to fetch more and coalesce */
2477 last = env->me_pglast;
2478 oldest = env->me_pgoldest;
2479 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2480 #if (MDB_DEVEL) & 2 /* "& 2" so MDB_DEVEL=1 won't hide bugs breaking freeDB */
2481 /* Use original snapshot. TODO: Should need less care in code
2482 * which modifies the database. Maybe we can delete some code?
2484 m2.mc_flags |= C_ORIG_RDONLY;
2485 m2.mc_db = &env->me_metas[(txn->mt_txnid-1) & 1]->mm_dbs[FREE_DBI];
2486 m2.mc_dbflag = (unsigned char *)""; /* probably unnecessary */
2490 key.mv_data = &last; /* will look up last+1 */
2491 key.mv_size = sizeof(last);
2493 if (Paranoid && mc->mc_dbi == FREE_DBI)
2496 if (Paranoid && retry < 0 && mop_len)
2500 /* Do not fetch more if the record will be too recent */
2501 if (oldest <= last) {
2503 oldest = mdb_find_oldest(txn);
2504 env->me_pgoldest = oldest;
2510 rc = mdb_cursor_get(&m2, &key, NULL, op);
2512 if (rc == MDB_NOTFOUND)
2516 last = *(txnid_t*)key.mv_data;
2517 if (oldest <= last) {
2519 oldest = mdb_find_oldest(txn);
2520 env->me_pgoldest = oldest;
2526 np = m2.mc_pg[m2.mc_top];
2527 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2528 if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
2531 idl = (MDB_ID *) data.mv_data;
2534 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2539 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2541 mop = env->me_pghead;
2543 env->me_pglast = last;
2545 DPRINTF(("IDL read txn %"Yu" root %"Yu" num %u",
2546 last, txn->mt_dbs[FREE_DBI].md_root, i));
2548 DPRINTF(("IDL %"Yu, idl[j]));
2550 /* Merge in descending sorted order */
2551 mdb_midl_xmerge(mop, idl);
2555 /* Use new pages from the map when nothing suitable in the freeDB */
2557 pgno = txn->mt_next_pgno;
2558 if (pgno + num >= env->me_maxpg) {
2559 DPUTS("DB size maxed out");
2563 #if defined(_WIN32) && !defined(MDB_VL32)
2564 if (!(env->me_flags & MDB_RDONLY)) {
2566 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
2567 p = VirtualAlloc(p, env->me_psize * num, MEM_COMMIT,
2568 (env->me_flags & MDB_WRITEMAP) ? PAGE_READWRITE:
2571 DPUTS("VirtualAlloc failed");
2579 if (env->me_flags & MDB_WRITEMAP) {
2580 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2582 if (!(np = mdb_page_malloc(txn, num))) {
2588 mop[0] = mop_len -= num;
2589 /* Move any stragglers down */
2590 for (j = i-num; j < mop_len; )
2591 mop[++j] = mop[++i];
2593 txn->mt_next_pgno = pgno + num;
2596 mdb_page_dirty(txn, np);
2602 txn->mt_flags |= MDB_TXN_ERROR;
2606 /** Copy the used portions of a non-overflow page.
2607 * @param[in] dst page to copy into
2608 * @param[in] src page to copy from
2609 * @param[in] psize size of a page
2612 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2614 enum { Align = sizeof(pgno_t) };
2615 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2617 /* If page isn't full, just copy the used portion. Adjust
2618 * alignment so memcpy may copy words instead of bytes.
2620 if ((unused &= -Align) && !IS_LEAF2(src)) {
2621 upper = (upper + PAGEBASE) & -Align;
2622 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2623 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2626 memcpy(dst, src, psize - unused);
2630 /** Pull a page off the txn's spill list, if present.
2631 * If a page being referenced was spilled to disk in this txn, bring
2632 * it back and make it dirty/writable again.
2633 * @param[in] txn the transaction handle.
2634 * @param[in] mp the page being referenced. It must not be dirty.
2635 * @param[out] ret the writable page, if any. ret is unchanged if
2636 * mp wasn't spilled.
2639 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2641 MDB_env *env = txn->mt_env;
2644 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2646 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2647 if (!tx2->mt_spill_pgs)
2649 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2650 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2653 if (txn->mt_dirty_room == 0)
2654 return MDB_TXN_FULL;
2655 if (IS_OVERFLOW(mp))
2659 if (env->me_flags & MDB_WRITEMAP) {
2662 np = mdb_page_malloc(txn, num);
2666 memcpy(np, mp, num * env->me_psize);
2668 mdb_page_copy(np, mp, env->me_psize);
2671 /* If in current txn, this page is no longer spilled.
2672 * If it happens to be the last page, truncate the spill list.
2673 * Otherwise mark it as deleted by setting the LSB.
2675 if (x == txn->mt_spill_pgs[0])
2676 txn->mt_spill_pgs[0]--;
2678 txn->mt_spill_pgs[x] |= 1;
2679 } /* otherwise, if belonging to a parent txn, the
2680 * page remains spilled until child commits
2683 mdb_page_dirty(txn, np);
2684 np->mp_flags |= P_DIRTY;
2692 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2693 * Set #MDB_TXN_ERROR on failure.
2694 * @param[in] mc cursor pointing to the page to be touched
2695 * @return 0 on success, non-zero on failure.
2698 mdb_page_touch(MDB_cursor *mc)
2700 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2701 MDB_txn *txn = mc->mc_txn;
2702 MDB_cursor *m2, *m3;
2706 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2707 if (txn->mt_flags & MDB_TXN_SPILLS) {
2709 rc = mdb_page_unspill(txn, mp, &np);
2715 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2716 (rc = mdb_page_alloc(mc, 1, &np)))
2719 DPRINTF(("touched db %d page %"Yu" -> %"Yu, DDBI(mc),
2720 mp->mp_pgno, pgno));
2721 mdb_cassert(mc, mp->mp_pgno != pgno);
2722 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2723 /* Update the parent page, if any, to point to the new page */
2725 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2726 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2727 SETPGNO(node, pgno);
2729 mc->mc_db->md_root = pgno;
2731 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2732 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2734 /* If txn has a parent, make sure the page is in our
2738 unsigned x = mdb_mid2l_search(dl, pgno);
2739 if (x <= dl[0].mid && dl[x].mid == pgno) {
2740 if (mp != dl[x].mptr) { /* bad cursor? */
2741 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2742 txn->mt_flags |= MDB_TXN_ERROR;
2748 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2750 np = mdb_page_malloc(txn, 1);
2755 rc = mdb_mid2l_insert(dl, &mid);
2756 mdb_cassert(mc, rc == 0);
2761 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2763 np->mp_flags |= P_DIRTY;
2766 /* Adjust cursors pointing to mp */
2767 mc->mc_pg[mc->mc_top] = np;
2768 m2 = txn->mt_cursors[mc->mc_dbi];
2769 if (mc->mc_flags & C_SUB) {
2770 for (; m2; m2=m2->mc_next) {
2771 m3 = &m2->mc_xcursor->mx_cursor;
2772 if (m3->mc_snum < mc->mc_snum) continue;
2773 if (m3->mc_pg[mc->mc_top] == mp)
2774 m3->mc_pg[mc->mc_top] = np;
2777 for (; m2; m2=m2->mc_next) {
2778 if (m2->mc_snum < mc->mc_snum) continue;
2779 if (m2 == mc) continue;
2780 if (m2->mc_pg[mc->mc_top] == mp) {
2781 m2->mc_pg[mc->mc_top] = np;
2783 XCURSOR_REFRESH(m2, mc->mc_top, np);
2787 MDB_PAGE_UNREF(mc->mc_txn, mp);
2791 txn->mt_flags |= MDB_TXN_ERROR;
2796 mdb_env_sync0(MDB_env *env, int force, pgno_t numpgs)
2799 if (env->me_flags & MDB_RDONLY)
2801 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2802 if (env->me_flags & MDB_WRITEMAP) {
2803 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2804 ? MS_ASYNC : MS_SYNC;
2805 if (MDB_MSYNC(env->me_map, env->me_psize * numpgs, flags))
2808 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2812 #ifdef BROKEN_FDATASYNC
2813 if (env->me_flags & MDB_FSYNCONLY) {
2814 if (fsync(env->me_fd))
2818 if (MDB_FDATASYNC(env->me_fd))
2826 mdb_env_sync(MDB_env *env, int force)
2828 MDB_meta *m = mdb_env_pick_meta(env);
2829 return mdb_env_sync0(env, force, m->mm_last_pg+1);
2832 /** Back up parent txn's cursors, then grab the originals for tracking */
2834 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2836 MDB_cursor *mc, *bk;
2841 for (i = src->mt_numdbs; --i >= 0; ) {
2842 if ((mc = src->mt_cursors[i]) != NULL) {
2843 size = sizeof(MDB_cursor);
2845 size += sizeof(MDB_xcursor);
2846 for (; mc; mc = bk->mc_next) {
2852 mc->mc_db = &dst->mt_dbs[i];
2853 /* Kill pointers into src to reduce abuse: The
2854 * user may not use mc until dst ends. But we need a valid
2855 * txn pointer here for cursor fixups to keep working.
2858 mc->mc_dbflag = &dst->mt_dbflags[i];
2859 if ((mx = mc->mc_xcursor) != NULL) {
2860 *(MDB_xcursor *)(bk+1) = *mx;
2861 mx->mx_cursor.mc_txn = dst;
2863 mc->mc_next = dst->mt_cursors[i];
2864 dst->mt_cursors[i] = mc;
2871 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2872 * @param[in] txn the transaction handle.
2873 * @param[in] merge true to keep changes to parent cursors, false to revert.
2874 * @return 0 on success, non-zero on failure.
2877 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2879 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2883 for (i = txn->mt_numdbs; --i >= 0; ) {
2884 for (mc = cursors[i]; mc; mc = next) {
2886 if ((bk = mc->mc_backup) != NULL) {
2888 /* Commit changes to parent txn */
2889 mc->mc_next = bk->mc_next;
2890 mc->mc_backup = bk->mc_backup;
2891 mc->mc_txn = bk->mc_txn;
2892 mc->mc_db = bk->mc_db;
2893 mc->mc_dbflag = bk->mc_dbflag;
2894 if ((mx = mc->mc_xcursor) != NULL)
2895 mx->mx_cursor.mc_txn = bk->mc_txn;
2897 /* Abort nested txn */
2899 if ((mx = mc->mc_xcursor) != NULL)
2900 *mx = *(MDB_xcursor *)(bk+1);
2904 /* Only malloced cursors are permanently tracked. */
2911 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2917 Pidset = F_SETLK, Pidcheck = F_GETLK
2921 /** Set or check a pid lock. Set returns 0 on success.
2922 * Check returns 0 if the process is certainly dead, nonzero if it may
2923 * be alive (the lock exists or an error happened so we do not know).
2925 * On Windows Pidset is a no-op, we merely check for the existence
2926 * of the process with the given pid. On POSIX we use a single byte
2927 * lock on the lockfile, set at an offset equal to the pid.
2930 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2932 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2935 if (op == Pidcheck) {
2936 h = OpenProcess(env->me_pidquery, FALSE, pid);
2937 /* No documented "no such process" code, but other program use this: */
2939 return ErrCode() != ERROR_INVALID_PARAMETER;
2940 /* A process exists until all handles to it close. Has it exited? */
2941 ret = WaitForSingleObject(h, 0) != 0;
2948 struct flock lock_info;
2949 memset(&lock_info, 0, sizeof(lock_info));
2950 lock_info.l_type = F_WRLCK;
2951 lock_info.l_whence = SEEK_SET;
2952 lock_info.l_start = pid;
2953 lock_info.l_len = 1;
2954 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2955 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2957 } else if ((rc = ErrCode()) == EINTR) {
2965 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2966 * @param[in] txn the transaction handle to initialize
2967 * @return 0 on success, non-zero on failure.
2970 mdb_txn_renew0(MDB_txn *txn)
2972 MDB_env *env = txn->mt_env;
2973 MDB_txninfo *ti = env->me_txns;
2975 unsigned int i, nr, flags = txn->mt_flags;
2977 int rc, new_notls = 0;
2979 if ((flags &= MDB_TXN_RDONLY) != 0) {
2981 meta = mdb_env_pick_meta(env);
2982 txn->mt_txnid = meta->mm_txnid;
2983 txn->mt_u.reader = NULL;
2985 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2986 pthread_getspecific(env->me_txkey);
2988 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2989 return MDB_BAD_RSLOT;
2991 MDB_PID_T pid = env->me_pid;
2992 MDB_THR_T tid = pthread_self();
2993 mdb_mutexref_t rmutex = env->me_rmutex;
2995 if (!env->me_live_reader) {
2996 rc = mdb_reader_pid(env, Pidset, pid);
2999 env->me_live_reader = 1;
3002 if (LOCK_MUTEX(rc, env, rmutex))
3004 nr = ti->mti_numreaders;
3005 for (i=0; i<nr; i++)
3006 if (ti->mti_readers[i].mr_pid == 0)
3008 if (i == env->me_maxreaders) {
3009 UNLOCK_MUTEX(rmutex);
3010 return MDB_READERS_FULL;
3012 r = &ti->mti_readers[i];
3013 /* Claim the reader slot, carefully since other code
3014 * uses the reader table un-mutexed: First reset the
3015 * slot, next publish it in mti_numreaders. After
3016 * that, it is safe for mdb_env_close() to touch it.
3017 * When it will be closed, we can finally claim it.
3020 r->mr_txnid = (txnid_t)-1;
3023 ti->mti_numreaders = ++nr;
3024 env->me_close_readers = nr;
3026 UNLOCK_MUTEX(rmutex);
3028 new_notls = (env->me_flags & MDB_NOTLS);
3029 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
3034 do /* LY: Retry on a race, ITS#7970. */
3035 r->mr_txnid = ti->mti_txnid;
3036 while(r->mr_txnid != ti->mti_txnid);
3037 txn->mt_txnid = r->mr_txnid;
3038 txn->mt_u.reader = r;
3039 meta = env->me_metas[txn->mt_txnid & 1];
3043 /* Not yet touching txn == env->me_txn0, it may be active */
3045 if (LOCK_MUTEX(rc, env, env->me_wmutex))
3047 txn->mt_txnid = ti->mti_txnid;
3048 meta = env->me_metas[txn->mt_txnid & 1];
3050 meta = mdb_env_pick_meta(env);
3051 txn->mt_txnid = meta->mm_txnid;
3055 if (txn->mt_txnid == mdb_debug_start)
3058 txn->mt_child = NULL;
3059 txn->mt_loose_pgs = NULL;
3060 txn->mt_loose_count = 0;
3061 txn->mt_dirty_room = MDB_IDL_UM_MAX;
3062 txn->mt_u.dirty_list = env->me_dirty_list;
3063 txn->mt_u.dirty_list[0].mid = 0;
3064 txn->mt_free_pgs = env->me_free_pgs;
3065 txn->mt_free_pgs[0] = 0;
3066 txn->mt_spill_pgs = NULL;
3068 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
3071 /* Copy the DB info and flags */
3072 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
3074 /* Moved to here to avoid a data race in read TXNs */
3075 txn->mt_next_pgno = meta->mm_last_pg+1;
3077 txn->mt_last_pgno = txn->mt_next_pgno - 1;
3080 txn->mt_flags = flags;
3083 txn->mt_numdbs = env->me_numdbs;
3084 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3085 x = env->me_dbflags[i];
3086 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
3087 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
3089 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
3090 txn->mt_dbflags[FREE_DBI] = DB_VALID;
3092 if (env->me_flags & MDB_FATAL_ERROR) {
3093 DPUTS("environment had fatal error, must shutdown!");
3095 } else if (env->me_maxpg < txn->mt_next_pgno) {
3096 rc = MDB_MAP_RESIZED;
3100 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
3105 mdb_txn_renew(MDB_txn *txn)
3109 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
3112 rc = mdb_txn_renew0(txn);
3113 if (rc == MDB_SUCCESS) {
3114 DPRINTF(("renew txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3115 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
3116 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
3122 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
3126 int rc, size, tsize;
3128 flags &= MDB_TXN_BEGIN_FLAGS;
3129 flags |= env->me_flags & MDB_WRITEMAP;
3131 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
3135 /* Nested transactions: Max 1 child, write txns only, no writemap */
3136 flags |= parent->mt_flags;
3137 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
3138 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
3140 /* Child txns save MDB_pgstate and use own copy of cursors */
3141 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
3142 size += tsize = sizeof(MDB_ntxn);
3143 } else if (flags & MDB_RDONLY) {
3144 size = env->me_maxdbs * (sizeof(MDB_db)+1);
3145 size += tsize = sizeof(MDB_txn);
3147 /* Reuse preallocated write txn. However, do not touch it until
3148 * mdb_txn_renew0() succeeds, since it currently may be active.
3153 if ((txn = calloc(1, size)) == NULL) {
3154 DPRINTF(("calloc: %s", strerror(errno)));
3159 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
3160 if (!txn->mt_rpages) {
3164 txn->mt_rpages[0].mid = 0;
3165 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
3168 txn->mt_dbxs = env->me_dbxs; /* static */
3169 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
3170 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
3171 txn->mt_flags = flags;
3176 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
3177 txn->mt_dbiseqs = parent->mt_dbiseqs;
3178 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
3179 if (!txn->mt_u.dirty_list ||
3180 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
3182 free(txn->mt_u.dirty_list);
3186 txn->mt_txnid = parent->mt_txnid;
3187 txn->mt_dirty_room = parent->mt_dirty_room;
3188 txn->mt_u.dirty_list[0].mid = 0;
3189 txn->mt_spill_pgs = NULL;
3190 txn->mt_next_pgno = parent->mt_next_pgno;
3191 parent->mt_flags |= MDB_TXN_HAS_CHILD;
3192 parent->mt_child = txn;
3193 txn->mt_parent = parent;
3194 txn->mt_numdbs = parent->mt_numdbs;
3196 txn->mt_rpages = parent->mt_rpages;
3198 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3199 /* Copy parent's mt_dbflags, but clear DB_NEW */
3200 for (i=0; i<txn->mt_numdbs; i++)
3201 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
3203 ntxn = (MDB_ntxn *)txn;
3204 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
3205 if (env->me_pghead) {
3206 size = MDB_IDL_SIZEOF(env->me_pghead);
3207 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
3209 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
3214 rc = mdb_cursor_shadow(parent, txn);
3216 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
3217 } else { /* MDB_RDONLY */
3218 txn->mt_dbiseqs = env->me_dbiseqs;
3220 rc = mdb_txn_renew0(txn);
3223 if (txn != env->me_txn0) {
3225 free(txn->mt_rpages);
3230 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
3232 DPRINTF(("begin txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3233 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
3234 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
3241 mdb_txn_env(MDB_txn *txn)
3243 if(!txn) return NULL;
3248 mdb_txn_id(MDB_txn *txn)
3251 return txn->mt_txnid;
3254 /** Export or close DBI handles opened in this txn. */
3256 mdb_dbis_update(MDB_txn *txn, int keep)
3259 MDB_dbi n = txn->mt_numdbs;
3260 MDB_env *env = txn->mt_env;
3261 unsigned char *tdbflags = txn->mt_dbflags;
3263 for (i = n; --i >= CORE_DBS;) {
3264 if (tdbflags[i] & DB_NEW) {
3266 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
3268 char *ptr = env->me_dbxs[i].md_name.mv_data;
3270 env->me_dbxs[i].md_name.mv_data = NULL;
3271 env->me_dbxs[i].md_name.mv_size = 0;
3272 env->me_dbflags[i] = 0;
3273 env->me_dbiseqs[i]++;
3279 if (keep && env->me_numdbs < n)
3283 /** End a transaction, except successful commit of a nested transaction.
3284 * May be called twice for readonly txns: First reset it, then abort.
3285 * @param[in] txn the transaction handle to end
3286 * @param[in] mode why and how to end the transaction
3289 mdb_txn_end(MDB_txn *txn, unsigned mode)
3291 MDB_env *env = txn->mt_env;
3293 static const char *const names[] = MDB_END_NAMES;
3296 /* Export or close DBI handles opened in this txn */
3297 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
3299 DPRINTF(("%s txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3300 names[mode & MDB_END_OPMASK],
3301 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
3302 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
3304 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3305 if (txn->mt_u.reader) {
3306 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
3307 if (!(env->me_flags & MDB_NOTLS)) {
3308 txn->mt_u.reader = NULL; /* txn does not own reader */
3309 } else if (mode & MDB_END_SLOT) {
3310 txn->mt_u.reader->mr_pid = 0;
3311 txn->mt_u.reader = NULL;
3312 } /* else txn owns the slot until it does MDB_END_SLOT */
3314 txn->mt_numdbs = 0; /* prevent further DBI activity */
3315 txn->mt_flags |= MDB_TXN_FINISHED;
3317 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
3318 pgno_t *pghead = env->me_pghead;
3320 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
3321 mdb_cursors_close(txn, 0);
3322 if (!(env->me_flags & MDB_WRITEMAP)) {
3323 mdb_dlist_free(txn);
3327 txn->mt_flags = MDB_TXN_FINISHED;
3329 if (!txn->mt_parent) {
3330 mdb_midl_shrink(&txn->mt_free_pgs);
3331 env->me_free_pgs = txn->mt_free_pgs;
3333 env->me_pghead = NULL;
3337 mode = 0; /* txn == env->me_txn0, do not free() it */
3339 /* The writer mutex was locked in mdb_txn_begin. */
3341 UNLOCK_MUTEX(env->me_wmutex);
3343 txn->mt_parent->mt_child = NULL;
3344 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
3345 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
3346 mdb_midl_free(txn->mt_free_pgs);
3347 mdb_midl_free(txn->mt_spill_pgs);
3348 free(txn->mt_u.dirty_list);
3351 mdb_midl_free(pghead);
3354 if (!txn->mt_parent) {
3355 MDB_ID3L el = env->me_rpages, tl = txn->mt_rpages;
3356 unsigned i, x, n = tl[0].mid;
3357 pthread_mutex_lock(&env->me_rpmutex);
3358 for (i = 1; i <= n; i++) {
3359 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
3360 /* tmp overflow pages that we didn't share in env */
3361 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3363 x = mdb_mid3l_search(el, tl[i].mid);
3364 if (tl[i].mptr == el[x].mptr) {
3367 /* another tmp overflow page */
3368 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3372 pthread_mutex_unlock(&env->me_rpmutex);
3374 if (mode & MDB_END_FREE)
3378 if (mode & MDB_END_FREE)
3383 mdb_txn_reset(MDB_txn *txn)
3388 /* This call is only valid for read-only txns */
3389 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3392 mdb_txn_end(txn, MDB_END_RESET);
3396 mdb_txn_abort(MDB_txn *txn)
3402 mdb_txn_abort(txn->mt_child);
3404 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3407 /** Save the freelist as of this transaction to the freeDB.
3408 * This changes the freelist. Keep trying until it stabilizes.
3410 * When (MDB_DEVEL) & 2, the changes do not affect #mdb_page_alloc(),
3411 * it then uses the transaction's original snapshot of the freeDB.
3414 mdb_freelist_save(MDB_txn *txn)
3416 /* env->me_pghead[] can grow and shrink during this call.
3417 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3418 * Page numbers cannot disappear from txn->mt_free_pgs[].
3421 MDB_env *env = txn->mt_env;
3422 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3423 txnid_t pglast = 0, head_id = 0;
3424 pgno_t freecnt = 0, *free_pgs, *mop;
3425 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3427 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3429 if (env->me_pghead) {
3430 /* Make sure first page of freeDB is touched and on freelist */
3431 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3432 if (rc && rc != MDB_NOTFOUND)
3436 if (!env->me_pghead && txn->mt_loose_pgs) {
3437 /* Put loose page numbers in mt_free_pgs, since
3438 * we may be unable to return them to me_pghead.
3440 MDB_page *mp = txn->mt_loose_pgs;
3441 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3443 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3444 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3445 txn->mt_loose_pgs = NULL;
3446 txn->mt_loose_count = 0;
3449 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3450 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3451 ? SSIZE_MAX : maxfree_1pg;
3454 /* Come back here after each Put() in case freelist changed */
3459 /* If using records from freeDB which we have not yet
3460 * deleted, delete them and any we reserved for me_pghead.
3462 while (pglast < env->me_pglast) {
3463 rc = mdb_cursor_first(&mc, &key, NULL);
3466 pglast = head_id = *(txnid_t *)key.mv_data;
3467 total_room = head_room = 0;
3468 mdb_tassert(txn, pglast <= env->me_pglast);
3469 rc = mdb_cursor_del(&mc, 0);
3474 /* Save the IDL of pages freed by this txn, to a single record */
3475 if (freecnt < txn->mt_free_pgs[0]) {
3477 /* Make sure last page of freeDB is touched and on freelist */
3478 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3479 if (rc && rc != MDB_NOTFOUND)
3482 free_pgs = txn->mt_free_pgs;
3483 /* Write to last page of freeDB */
3484 key.mv_size = sizeof(txn->mt_txnid);
3485 key.mv_data = &txn->mt_txnid;
3487 freecnt = free_pgs[0];
3488 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3489 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3492 /* Retry if mt_free_pgs[] grew during the Put() */
3493 free_pgs = txn->mt_free_pgs;
3494 } while (freecnt < free_pgs[0]);
3495 mdb_midl_sort(free_pgs);
3496 memcpy(data.mv_data, free_pgs, data.mv_size);
3499 unsigned int i = free_pgs[0];
3500 DPRINTF(("IDL write txn %"Yu" root %"Yu" num %u",
3501 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3503 DPRINTF(("IDL %"Yu, free_pgs[i]));
3509 mop = env->me_pghead;
3510 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3512 /* Reserve records for me_pghead[]. Split it if multi-page,
3513 * to avoid searching freeDB for a page range. Use keys in
3514 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3516 if (total_room >= mop_len) {
3517 if (total_room == mop_len || --more < 0)
3519 } else if (head_room >= maxfree_1pg && head_id > 1) {
3520 /* Keep current record (overflow page), add a new one */
3524 /* (Re)write {key = head_id, IDL length = head_room} */
3525 total_room -= head_room;
3526 head_room = mop_len - total_room;
3527 if (head_room > maxfree_1pg && head_id > 1) {
3528 /* Overflow multi-page for part of me_pghead */
3529 head_room /= head_id; /* amortize page sizes */
3530 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3531 } else if (head_room < 0) {
3532 /* Rare case, not bothering to delete this record */
3535 key.mv_size = sizeof(head_id);
3536 key.mv_data = &head_id;
3537 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3538 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3541 /* IDL is initially empty, zero out at least the length */
3542 pgs = (pgno_t *)data.mv_data;
3543 j = head_room > clean_limit ? head_room : 0;
3547 total_room += head_room;
3550 /* Return loose page numbers to me_pghead, though usually none are
3551 * left at this point. The pages themselves remain in dirty_list.
3553 if (txn->mt_loose_pgs) {
3554 MDB_page *mp = txn->mt_loose_pgs;
3555 unsigned count = txn->mt_loose_count;
3557 /* Room for loose pages + temp IDL with same */
3558 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3560 mop = env->me_pghead;
3561 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3562 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3563 loose[ ++count ] = mp->mp_pgno;
3565 mdb_midl_sort(loose);
3566 mdb_midl_xmerge(mop, loose);
3567 txn->mt_loose_pgs = NULL;
3568 txn->mt_loose_count = 0;
3572 /* Fill in the reserved me_pghead records */
3578 rc = mdb_cursor_first(&mc, &key, &data);
3579 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3580 txnid_t id = *(txnid_t *)key.mv_data;
3581 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3584 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3586 if (len > mop_len) {
3588 data.mv_size = (len + 1) * sizeof(MDB_ID);
3590 data.mv_data = mop -= len;
3593 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3595 if (rc || !(mop_len -= len))
3602 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3603 * @param[in] txn the transaction that's being committed
3604 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3605 * @return 0 on success, non-zero on failure.
3608 mdb_page_flush(MDB_txn *txn, int keep)
3610 MDB_env *env = txn->mt_env;
3611 MDB_ID2L dl = txn->mt_u.dirty_list;
3612 unsigned psize = env->me_psize, j;
3613 int i, pagecount = dl[0].mid, rc;
3617 MDB_page *dp = NULL;
3621 struct iovec iov[MDB_COMMIT_PAGES];
3622 ssize_t wsize = 0, wres;
3623 off_t wpos = 0, next_pos = 1; /* impossible pos, so pos != next_pos */
3629 if (env->me_flags & MDB_WRITEMAP) {
3630 /* Clear dirty flags */
3631 while (++i <= pagecount) {
3633 /* Don't flush this page yet */
3634 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3635 dp->mp_flags &= ~P_KEEP;
3639 dp->mp_flags &= ~P_DIRTY;
3644 /* Write the pages */
3646 if (++i <= pagecount) {
3648 /* Don't flush this page yet */
3649 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3650 dp->mp_flags &= ~P_KEEP;
3655 /* clear dirty flag */
3656 dp->mp_flags &= ~P_DIRTY;
3659 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3664 /* Windows actually supports scatter/gather I/O, but only on
3665 * unbuffered file handles. Since we're relying on the OS page
3666 * cache for all our data, that's self-defeating. So we just
3667 * write pages one at a time. We use the ov structure to set
3668 * the write offset, to at least save the overhead of a Seek
3671 DPRINTF(("committing page %"Yu, pgno));
3672 memset(&ov, 0, sizeof(ov));
3673 ov.Offset = pos & 0xffffffff;
3674 ov.OffsetHigh = pos >> 16 >> 16;
3675 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3677 DPRINTF(("WriteFile: %d", rc));
3681 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3682 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3685 /* Write previous page(s) */
3686 #ifdef MDB_USE_PWRITEV
3687 wres = pwritev(env->me_fd, iov, n, wpos);
3690 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3693 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3697 DPRINTF(("lseek: %s", strerror(rc)));
3700 wres = writev(env->me_fd, iov, n);
3703 if (wres != wsize) {
3708 DPRINTF(("Write error: %s", strerror(rc)));
3710 rc = EIO; /* TODO: Use which error code? */
3711 DPUTS("short write, filesystem full?");
3722 DPRINTF(("committing page %"Yu, pgno));
3723 next_pos = pos + size;
3724 iov[n].iov_len = size;
3725 iov[n].iov_base = (char *)dp;
3731 if (pgno > txn->mt_last_pgno)
3732 txn->mt_last_pgno = pgno;
3735 /* MIPS has cache coherency issues, this is a no-op everywhere else
3736 * Note: for any size >= on-chip cache size, entire on-chip cache is
3739 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3741 for (i = keep; ++i <= pagecount; ) {
3743 /* This is a page we skipped above */
3746 dl[j].mid = dp->mp_pgno;
3749 mdb_dpage_free(env, dp);
3754 txn->mt_dirty_room += i - j;
3760 mdb_txn_commit(MDB_txn *txn)
3763 unsigned int i, end_mode;
3769 /* mdb_txn_end() mode for a commit which writes nothing */
3770 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3772 if (txn->mt_child) {
3773 rc = mdb_txn_commit(txn->mt_child);
3780 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3784 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3785 DPUTS("txn has failed/finished, can't commit");
3787 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3792 if (txn->mt_parent) {
3793 MDB_txn *parent = txn->mt_parent;
3797 unsigned x, y, len, ps_len;
3799 /* Append our free list to parent's */
3800 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3803 mdb_midl_free(txn->mt_free_pgs);
3804 /* Failures after this must either undo the changes
3805 * to the parent or set MDB_TXN_ERROR in the parent.
3808 parent->mt_next_pgno = txn->mt_next_pgno;
3809 parent->mt_flags = txn->mt_flags;
3811 /* Merge our cursors into parent's and close them */
3812 mdb_cursors_close(txn, 1);
3814 /* Update parent's DB table. */
3815 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3816 parent->mt_numdbs = txn->mt_numdbs;
3817 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3818 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3819 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3820 /* preserve parent's DB_NEW status */
3821 x = parent->mt_dbflags[i] & DB_NEW;
3822 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3825 dst = parent->mt_u.dirty_list;
3826 src = txn->mt_u.dirty_list;
3827 /* Remove anything in our dirty list from parent's spill list */
3828 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3830 pspill[0] = (pgno_t)-1;
3831 /* Mark our dirty pages as deleted in parent spill list */
3832 for (i=0, len=src[0].mid; ++i <= len; ) {
3833 MDB_ID pn = src[i].mid << 1;
3834 while (pn > pspill[x])
3836 if (pn == pspill[x]) {
3841 /* Squash deleted pagenums if we deleted any */
3842 for (x=y; ++x <= ps_len; )
3843 if (!(pspill[x] & 1))
3844 pspill[++y] = pspill[x];
3848 /* Remove anything in our spill list from parent's dirty list */
3849 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3850 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3851 MDB_ID pn = txn->mt_spill_pgs[i];
3853 continue; /* deleted spillpg */
3855 y = mdb_mid2l_search(dst, pn);
3856 if (y <= dst[0].mid && dst[y].mid == pn) {
3858 while (y < dst[0].mid) {
3867 /* Find len = length of merging our dirty list with parent's */
3869 dst[0].mid = 0; /* simplify loops */
3870 if (parent->mt_parent) {
3871 len = x + src[0].mid;
3872 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3873 for (i = x; y && i; y--) {
3874 pgno_t yp = src[y].mid;
3875 while (yp < dst[i].mid)
3877 if (yp == dst[i].mid) {
3882 } else { /* Simplify the above for single-ancestor case */
3883 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3885 /* Merge our dirty list with parent's */
3887 for (i = len; y; dst[i--] = src[y--]) {
3888 pgno_t yp = src[y].mid;
3889 while (yp < dst[x].mid)
3890 dst[i--] = dst[x--];
3891 if (yp == dst[x].mid)
3892 free(dst[x--].mptr);
3894 mdb_tassert(txn, i == x);
3896 free(txn->mt_u.dirty_list);
3897 parent->mt_dirty_room = txn->mt_dirty_room;
3898 if (txn->mt_spill_pgs) {
3899 if (parent->mt_spill_pgs) {
3900 /* TODO: Prevent failure here, so parent does not fail */
3901 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3903 parent->mt_flags |= MDB_TXN_ERROR;
3904 mdb_midl_free(txn->mt_spill_pgs);
3905 mdb_midl_sort(parent->mt_spill_pgs);
3907 parent->mt_spill_pgs = txn->mt_spill_pgs;
3911 /* Append our loose page list to parent's */
3912 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3914 *lp = txn->mt_loose_pgs;
3915 parent->mt_loose_count += txn->mt_loose_count;
3917 parent->mt_child = NULL;
3918 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3923 if (txn != env->me_txn) {
3924 DPUTS("attempt to commit unknown transaction");
3929 mdb_cursors_close(txn, 0);
3931 if (!txn->mt_u.dirty_list[0].mid &&
3932 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3935 DPRINTF(("committing txn %"Yu" %p on mdbenv %p, root page %"Yu,
3936 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3938 /* Update DB root pointers */
3939 if (txn->mt_numdbs > CORE_DBS) {
3943 data.mv_size = sizeof(MDB_db);
3945 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3946 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3947 if (txn->mt_dbflags[i] & DB_DIRTY) {
3948 if (TXN_DBI_CHANGED(txn, i)) {
3952 data.mv_data = &txn->mt_dbs[i];
3953 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3961 rc = mdb_freelist_save(txn);
3965 mdb_midl_free(env->me_pghead);
3966 env->me_pghead = NULL;
3967 mdb_midl_shrink(&txn->mt_free_pgs);
3973 if ((rc = mdb_page_flush(txn, 0)))
3975 if (!F_ISSET(txn->mt_flags, MDB_TXN_NOSYNC) &&
3976 (rc = mdb_env_sync0(env, 0, txn->mt_next_pgno)))
3978 if ((rc = mdb_env_write_meta(txn)))
3980 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3983 mdb_txn_end(txn, end_mode);
3991 /** Read the environment parameters of a DB environment before
3992 * mapping it into memory.
3993 * @param[in] env the environment handle
3994 * @param[in] prev whether to read the backup meta page
3995 * @param[out] meta address of where to store the meta information
3996 * @return 0 on success, non-zero on failure.
3999 mdb_env_read_header(MDB_env *env, int prev, MDB_meta *meta)
4005 enum { Size = sizeof(pbuf) };
4007 /* We don't know the page size yet, so use a minimum value.
4008 * Read both meta pages so we can use the latest one.
4011 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
4015 memset(&ov, 0, sizeof(ov));
4017 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
4018 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
4021 rc = pread(env->me_fd, &pbuf, Size, off);
4024 if (rc == 0 && off == 0)
4026 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
4027 DPRINTF(("read: %s", mdb_strerror(rc)));
4031 p = (MDB_page *)&pbuf;
4033 if (!F_ISSET(p->mp_flags, P_META)) {
4034 DPRINTF(("page %"Yu" not a meta page", p->mp_pgno));
4039 if (m->mm_magic != MDB_MAGIC) {
4040 DPUTS("meta has invalid magic");
4044 if (m->mm_version != MDB_DATA_VERSION) {
4045 DPRINTF(("database is version %u, expected version %u",
4046 m->mm_version, MDB_DATA_VERSION));
4047 return MDB_VERSION_MISMATCH;
4050 if (off == 0 || (prev ? m->mm_txnid < meta->mm_txnid : m->mm_txnid > meta->mm_txnid))
4056 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
4058 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
4060 meta->mm_magic = MDB_MAGIC;
4061 meta->mm_version = MDB_DATA_VERSION;
4062 meta->mm_mapsize = env->me_mapsize;
4063 meta->mm_psize = env->me_psize;
4064 meta->mm_last_pg = NUM_METAS-1;
4065 meta->mm_flags = env->me_flags & 0xffff;
4066 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
4067 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
4068 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
4071 /** Write the environment parameters of a freshly created DB environment.
4072 * @param[in] env the environment handle
4073 * @param[in] meta the #MDB_meta to write
4074 * @return 0 on success, non-zero on failure.
4077 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
4085 memset(&ov, 0, sizeof(ov));
4086 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
4088 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
4091 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
4092 len = pwrite(fd, ptr, size, pos); \
4093 if (len == -1 && ErrCode() == EINTR) continue; \
4094 rc = (len >= 0); break; } while(1)
4097 DPUTS("writing new meta page");
4099 psize = env->me_psize;
4101 p = calloc(NUM_METAS, psize);
4105 p->mp_flags = P_META;
4106 *(MDB_meta *)METADATA(p) = *meta;
4108 q = (MDB_page *)((char *)p + psize);
4110 q->mp_flags = P_META;
4111 *(MDB_meta *)METADATA(q) = *meta;
4113 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
4116 else if ((unsigned) len == psize * NUM_METAS)
4124 /** Update the environment info to commit a transaction.
4125 * @param[in] txn the transaction that's being committed
4126 * @return 0 on success, non-zero on failure.
4129 mdb_env_write_meta(MDB_txn *txn)
4132 MDB_meta meta, metab, *mp;
4136 int rc, len, toggle;
4145 toggle = txn->mt_txnid & 1;
4146 DPRINTF(("writing meta page %d for root page %"Yu,
4147 toggle, txn->mt_dbs[MAIN_DBI].md_root));
4150 flags = txn->mt_flags | env->me_flags;
4151 mp = env->me_metas[toggle];
4152 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
4153 /* Persist any increases of mapsize config */
4154 if (mapsize < env->me_mapsize)
4155 mapsize = env->me_mapsize;
4157 if (flags & MDB_WRITEMAP) {
4158 mp->mm_mapsize = mapsize;
4159 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4160 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4161 mp->mm_last_pg = txn->mt_next_pgno - 1;
4162 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
4163 !(defined(__i386__) || defined(__x86_64__))
4164 /* LY: issue a memory barrier, if not x86. ITS#7969 */
4165 __sync_synchronize();
4167 mp->mm_txnid = txn->mt_txnid;
4168 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
4169 unsigned meta_size = env->me_psize;
4170 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
4171 ptr = (char *)mp - PAGEHDRSZ;
4172 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
4173 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
4177 if (MDB_MSYNC(ptr, meta_size, rc)) {
4184 metab.mm_txnid = mp->mm_txnid;
4185 metab.mm_last_pg = mp->mm_last_pg;
4187 meta.mm_mapsize = mapsize;
4188 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4189 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4190 meta.mm_last_pg = txn->mt_next_pgno - 1;
4191 meta.mm_txnid = txn->mt_txnid;
4193 off = offsetof(MDB_meta, mm_mapsize);
4194 ptr = (char *)&meta + off;
4195 len = sizeof(MDB_meta) - off;
4196 off += (char *)mp - env->me_map;
4198 /* Write to the SYNC fd unless MDB_NOSYNC/MDB_NOMETASYNC.
4199 * (me_mfd goes to the same file as me_fd, but writing to it
4200 * also syncs to disk. Avoids a separate fdatasync() call.)
4202 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
4205 memset(&ov, 0, sizeof(ov));
4207 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
4212 rc = pwrite(mfd, ptr, len, off);
4215 rc = rc < 0 ? ErrCode() : EIO;
4220 DPUTS("write failed, disk error?");
4221 /* On a failure, the pagecache still contains the new data.
4222 * Write some old data back, to prevent it from being used.
4223 * Use the non-SYNC fd; we know it will fail anyway.
4225 meta.mm_last_pg = metab.mm_last_pg;
4226 meta.mm_txnid = metab.mm_txnid;
4228 memset(&ov, 0, sizeof(ov));
4230 WriteFile(env->me_fd, ptr, len, NULL, &ov);
4232 r2 = pwrite(env->me_fd, ptr, len, off);
4233 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
4236 env->me_flags |= MDB_FATAL_ERROR;
4239 /* MIPS has cache coherency issues, this is a no-op everywhere else */
4240 CACHEFLUSH(env->me_map + off, len, DCACHE);
4242 /* Memory ordering issues are irrelevant; since the entire writer
4243 * is wrapped by wmutex, all of these changes will become visible
4244 * after the wmutex is unlocked. Since the DB is multi-version,
4245 * readers will get consistent data regardless of how fresh or
4246 * how stale their view of these values is.
4249 env->me_txns->mti_txnid = txn->mt_txnid;
4254 /** Check both meta pages to see which one is newer.
4255 * @param[in] env the environment handle
4256 * @return newest #MDB_meta.
4259 mdb_env_pick_meta(const MDB_env *env)
4261 MDB_meta *const *metas = env->me_metas;
4262 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
4266 mdb_env_create(MDB_env **env)
4270 e = calloc(1, sizeof(MDB_env));
4274 e->me_maxreaders = DEFAULT_READERS;
4275 e->me_maxdbs = e->me_numdbs = CORE_DBS;
4276 e->me_fd = INVALID_HANDLE_VALUE;
4277 e->me_lfd = INVALID_HANDLE_VALUE;
4278 e->me_mfd = INVALID_HANDLE_VALUE;
4279 #ifdef MDB_USE_POSIX_SEM
4280 e->me_rmutex = SEM_FAILED;
4281 e->me_wmutex = SEM_FAILED;
4282 #elif defined MDB_USE_SYSV_SEM
4283 e->me_rmutex->semid = -1;
4284 e->me_wmutex->semid = -1;
4286 e->me_pid = getpid();
4287 GET_PAGESIZE(e->me_os_psize);
4288 VGMEMP_CREATE(e,0,0);
4294 /** @brief Map a result from an NTAPI call to WIN32. */
4296 mdb_nt2win32(NTSTATUS st)
4301 GetOverlappedResult(NULL, &o, &br, FALSE);
4302 return GetLastError();
4307 mdb_env_map(MDB_env *env, void *addr)
4310 unsigned int flags = env->me_flags;
4313 int access = SECTION_MAP_READ;
4317 ULONG pageprot = PAGE_READONLY, secprot, alloctype;
4319 if (flags & MDB_WRITEMAP) {
4320 access |= SECTION_MAP_WRITE;
4321 pageprot = PAGE_READWRITE;
4323 if (flags & MDB_RDONLY) {
4324 secprot = PAGE_READONLY;
4328 secprot = PAGE_READWRITE;
4329 msize = env->me_mapsize;
4330 alloctype = MEM_RESERVE;
4333 rc = NtCreateSection(&mh, access, NULL, NULL, secprot, SEC_RESERVE, env->me_fd);
4335 return mdb_nt2win32(rc);
4338 msize = NUM_METAS * env->me_psize;
4340 rc = NtMapViewOfSection(mh, GetCurrentProcess(), &map, 0, 0, NULL, &msize, ViewUnmap, alloctype, pageprot);
4347 return mdb_nt2win32(rc);
4352 env->me_map = mmap(addr, NUM_METAS * env->me_psize, PROT_READ, MAP_SHARED,
4354 if (env->me_map == MAP_FAILED) {
4359 int prot = PROT_READ;
4360 if (flags & MDB_WRITEMAP) {
4362 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
4365 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
4367 if (env->me_map == MAP_FAILED) {
4372 if (flags & MDB_NORDAHEAD) {
4373 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
4375 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
4377 #ifdef POSIX_MADV_RANDOM
4378 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
4379 #endif /* POSIX_MADV_RANDOM */
4380 #endif /* MADV_RANDOM */
4384 /* Can happen because the address argument to mmap() is just a
4385 * hint. mmap() can pick another, e.g. if the range is in use.
4386 * The MAP_FIXED flag would prevent that, but then mmap could
4387 * instead unmap existing pages to make room for the new map.
4389 if (addr && env->me_map != addr)
4390 return EBUSY; /* TODO: Make a new MDB_* error code? */
4393 p = (MDB_page *)env->me_map;
4394 env->me_metas[0] = METADATA(p);
4395 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
4401 mdb_env_set_mapsize(MDB_env *env, mdb_size_t size)
4403 /* If env is already open, caller is responsible for making
4404 * sure there are no active txns.
4414 meta = mdb_env_pick_meta(env);
4416 size = meta->mm_mapsize;
4418 /* Silently round up to minimum if the size is too small */
4419 mdb_size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
4424 /* For MDB_VL32 this bit is a noop since we dynamically remap
4425 * chunks of the DB anyway.
4427 munmap(env->me_map, env->me_mapsize);
4428 env->me_mapsize = size;
4429 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4430 rc = mdb_env_map(env, old);
4433 #endif /* !MDB_VL32 */
4435 env->me_mapsize = size;
4437 env->me_maxpg = env->me_mapsize / env->me_psize;
4442 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4446 env->me_maxdbs = dbs + CORE_DBS;
4451 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4453 if (env->me_map || readers < 1)
4455 env->me_maxreaders = readers;
4460 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4462 if (!env || !readers)
4464 *readers = env->me_maxreaders;
4469 mdb_fsize(HANDLE fd, mdb_size_t *size)
4472 LARGE_INTEGER fsize;
4474 if (!GetFileSizeEx(fd, &fsize))
4477 *size = fsize.QuadPart;
4491 typedef wchar_t mdb_nchar_t;
4492 # define MDB_NAME(str) L##str
4493 # define mdb_name_cpy wcscpy
4495 /** Character type for file names: char on Unix, wchar_t on Windows */
4496 typedef char mdb_nchar_t;
4497 # define MDB_NAME(str) str /**< #mdb_nchar_t[] string literal */
4498 # define mdb_name_cpy strcpy /**< Copy name (#mdb_nchar_t string) */
4501 /** Filename - string of #mdb_nchar_t[] */
4502 typedef struct MDB_name {
4503 int mn_len; /**< Length */
4504 int mn_alloced; /**< True if #mn_val was malloced */
4505 mdb_nchar_t *mn_val; /**< Contents */
4508 /** Filename suffixes [datafile,lockfile][without,with MDB_NOSUBDIR] */
4509 static const mdb_nchar_t *const mdb_suffixes[2][2] = {
4510 { MDB_NAME("/data.mdb"), MDB_NAME("") },
4511 { MDB_NAME("/lock.mdb"), MDB_NAME("-lock") }
4514 #define MDB_SUFFLEN 9 /**< Max string length in #mdb_suffixes[] */
4516 /** Set up filename + scratch area for filename suffix, for opening files.
4517 * It should be freed with #mdb_fname_destroy().
4518 * On Windows, paths are converted from char *UTF-8 to wchar_t *UTF-16.
4520 * @param[in] path Pathname for #mdb_env_open().
4521 * @param[in] envflags Whether a subdir and/or lockfile will be used.
4522 * @param[out] fname Resulting filename, with room for a suffix if necessary.
4525 mdb_fname_init(const char *path, unsigned envflags, MDB_name *fname)
4527 int no_suffix = F_ISSET(envflags, MDB_NOSUBDIR|MDB_NOLOCK);
4528 fname->mn_alloced = 0;
4530 return utf8_to_utf16(path, fname, no_suffix ? 0 : MDB_SUFFLEN);
4532 fname->mn_len = strlen(path);
4534 fname->mn_val = (char *) path;
4535 else if ((fname->mn_val = malloc(fname->mn_len + MDB_SUFFLEN+1)) != NULL) {
4536 fname->mn_alloced = 1;
4537 strcpy(fname->mn_val, path);
4545 /** Destroy \b fname from #mdb_fname_init() */
4546 #define mdb_fname_destroy(fname) \
4547 do { if ((fname).mn_alloced) free((fname).mn_val); } while (0)
4549 #ifdef O_CLOEXEC /* POSIX.1-2008: Set FD_CLOEXEC atomically at open() */
4550 # define MDB_CLOEXEC O_CLOEXEC
4552 # define MDB_CLOEXEC 0
4555 /** File type, access mode etc. for #mdb_fopen() */
4556 enum mdb_fopen_type {
4558 MDB_O_RDONLY, MDB_O_RDWR, MDB_O_META, MDB_O_COPY, MDB_O_LOCKS
4560 /* A comment in mdb_fopen() explains some O_* flag choices. */
4561 MDB_O_RDONLY= O_RDONLY, /**< for RDONLY me_fd */
4562 MDB_O_RDWR = O_RDWR |O_CREAT, /**< for me_fd */
4563 MDB_O_META = O_WRONLY|MDB_DSYNC |MDB_CLOEXEC, /**< for me_mfd */
4564 MDB_O_COPY = O_WRONLY|O_CREAT|O_EXCL|MDB_CLOEXEC, /**< for #mdb_env_copy() */
4565 /** Bitmask for open() flags in enum #mdb_fopen_type. The other bits
4566 * distinguish otherwise-equal MDB_O_* constants from each other.
4568 MDB_O_MASK = MDB_O_RDWR|MDB_CLOEXEC | MDB_O_RDONLY|MDB_O_META|MDB_O_COPY,
4569 MDB_O_LOCKS = MDB_O_RDWR|MDB_CLOEXEC | ((MDB_O_MASK+1) & ~MDB_O_MASK) /**< for me_lfd */
4573 /** Open an LMDB file.
4574 * @param[in] env The LMDB environment.
4575 * @param[in,out] fname Path from from #mdb_fname_init(). A suffix is
4576 * appended if necessary to create the filename, without changing mn_len.
4577 * @param[in] which Determines file type, access mode, etc.
4578 * @param[in] mode The Unix permissions for the file, if we create it.
4579 * @param[out] res Resulting file handle.
4580 * @return 0 on success, non-zero on failure.
4583 mdb_fopen(const MDB_env *env, MDB_name *fname,
4584 enum mdb_fopen_type which, mdb_mode_t mode,
4587 int rc = MDB_SUCCESS;
4590 DWORD acc, share, disp, attrs;
4595 if (fname->mn_alloced) /* modifiable copy */
4596 mdb_name_cpy(fname->mn_val + fname->mn_len,
4597 mdb_suffixes[which==MDB_O_LOCKS][F_ISSET(env->me_flags, MDB_NOSUBDIR)]);
4599 /* The directory must already exist. Usually the file need not.
4600 * MDB_O_META requires the file because we already created it using
4601 * MDB_O_RDWR. MDB_O_COPY must not overwrite an existing file.
4603 * With MDB_O_COPY we do not want the OS to cache the writes, since
4604 * the source data is already in the OS cache.
4606 * The lockfile needs FD_CLOEXEC (close file descriptor on exec*())
4607 * to avoid the flock() issues noted under Caveats in lmdb.h.
4608 * Also set it for other filehandles which the user cannot get at
4609 * and close himself, which he may need after fork(). I.e. all but
4610 * me_fd, which programs do use via mdb_env_get_fd().
4614 acc = GENERIC_READ|GENERIC_WRITE;
4615 share = FILE_SHARE_READ|FILE_SHARE_WRITE;
4617 attrs = FILE_ATTRIBUTE_NORMAL;
4619 case MDB_O_RDONLY: /* read-only datafile */
4621 disp = OPEN_EXISTING;
4623 case MDB_O_META: /* for writing metapages */
4624 acc = GENERIC_WRITE;
4625 disp = OPEN_EXISTING;
4626 attrs = FILE_ATTRIBUTE_NORMAL|FILE_FLAG_WRITE_THROUGH;
4628 case MDB_O_COPY: /* mdb_env_copy() & co */
4629 acc = GENERIC_WRITE;
4632 attrs = FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH;
4634 default: break; /* silence gcc -Wswitch (not all enum values handled) */
4636 fd = CreateFileW(fname->mn_val, acc, share, NULL, disp, attrs, NULL);
4638 fd = open(fname->mn_val, which & MDB_O_MASK, mode);
4641 if (fd == INVALID_HANDLE_VALUE)
4645 if (which != MDB_O_RDONLY && which != MDB_O_RDWR) {
4646 /* Set CLOEXEC if we could not pass it to open() */
4647 if (!MDB_CLOEXEC && (flags = fcntl(fd, F_GETFD)) != -1)
4648 (void) fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
4650 if (which == MDB_O_COPY && env->me_psize >= env->me_os_psize) {
4651 /* This may require buffer alignment. There is no portable
4652 * way to ask how much, so we require OS pagesize alignment.
4654 # ifdef F_NOCACHE /* __APPLE__ */
4655 (void) fcntl(fd, F_NOCACHE, 1);
4656 # elif defined O_DIRECT
4657 /* open(...O_DIRECT...) would break on filesystems without
4658 * O_DIRECT support (ITS#7682). Try to set it here instead.
4660 if ((flags = fcntl(fd, F_GETFL)) != -1)
4661 (void) fcntl(fd, F_SETFL, flags | O_DIRECT);
4665 #endif /* !_WIN32 */
4672 #ifdef BROKEN_FDATASYNC
4673 #include <sys/utsname.h>
4674 #include <sys/vfs.h>
4677 /** Further setup required for opening an LMDB environment
4680 mdb_env_open2(MDB_env *env, int prev)
4682 unsigned int flags = env->me_flags;
4683 int i, newenv = 0, rc;
4687 /* See if we should use QueryLimited */
4689 if ((rc & 0xff) > 5)
4690 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4692 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4695 #ifdef BROKEN_FDATASYNC
4696 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4697 * https://lkml.org/lkml/2012/9/3/83
4698 * Kernels after 3.6-rc6 are known good.
4699 * https://lkml.org/lkml/2012/9/10/556
4700 * See if the DB is on ext3/ext4, then check for new enough kernel
4701 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4706 fstatfs(env->me_fd, &st);
4707 while (st.f_type == 0xEF53) {
4711 if (uts.release[0] < '3') {
4712 if (!strncmp(uts.release, "2.6.32.", 7)) {
4713 i = atoi(uts.release+7);
4715 break; /* 2.6.32.60 and newer is OK */
4716 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4717 i = atoi(uts.release+7);
4719 break; /* 2.6.34.15 and newer is OK */
4721 } else if (uts.release[0] == '3') {
4722 i = atoi(uts.release+2);
4724 break; /* 3.6 and newer is OK */
4726 i = atoi(uts.release+4);
4728 break; /* 3.5.4 and newer is OK */
4729 } else if (i == 2) {
4730 i = atoi(uts.release+4);
4732 break; /* 3.2.30 and newer is OK */
4734 } else { /* 4.x and newer is OK */
4737 env->me_flags |= MDB_FSYNCONLY;
4743 if ((i = mdb_env_read_header(env, prev, &meta)) != 0) {
4746 DPUTS("new mdbenv");
4748 env->me_psize = env->me_os_psize;
4749 if (env->me_psize > MAX_PAGESIZE)
4750 env->me_psize = MAX_PAGESIZE;
4751 memset(&meta, 0, sizeof(meta));
4752 mdb_env_init_meta0(env, &meta);
4753 meta.mm_mapsize = DEFAULT_MAPSIZE;
4755 env->me_psize = meta.mm_psize;
4758 /* Was a mapsize configured? */
4759 if (!env->me_mapsize) {
4760 env->me_mapsize = meta.mm_mapsize;
4763 /* Make sure mapsize >= committed data size. Even when using
4764 * mm_mapsize, which could be broken in old files (ITS#7789).
4766 mdb_size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4767 if (env->me_mapsize < minsize)
4768 env->me_mapsize = minsize;
4770 meta.mm_mapsize = env->me_mapsize;
4772 if (newenv && !(flags & MDB_FIXEDMAP)) {
4773 /* mdb_env_map() may grow the datafile. Write the metapages
4774 * first, so the file will be valid if initialization fails.
4775 * Except with FIXEDMAP, since we do not yet know mm_address.
4776 * We could fill in mm_address later, but then a different
4777 * program might end up doing that - one with a memory layout
4778 * and map address which does not suit the main program.
4780 rc = mdb_env_init_meta(env, &meta);
4786 /* For FIXEDMAP, make sure the file is non-empty before we attempt to map it */
4790 rc = WriteFile(env->me_fd, &dummy, 1, &len, NULL);
4798 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4803 if (flags & MDB_FIXEDMAP)
4804 meta.mm_address = env->me_map;
4805 i = mdb_env_init_meta(env, &meta);
4806 if (i != MDB_SUCCESS) {
4811 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4812 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4814 #if !(MDB_MAXKEYSIZE)
4815 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4817 env->me_maxpg = env->me_mapsize / env->me_psize;
4821 MDB_meta *meta = mdb_env_pick_meta(env);
4822 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4824 DPRINTF(("opened database version %u, pagesize %u",
4825 meta->mm_version, env->me_psize));
4826 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4827 DPRINTF(("depth: %u", db->md_depth));
4828 DPRINTF(("entries: %"Yu, db->md_entries));
4829 DPRINTF(("branch pages: %"Yu, db->md_branch_pages));
4830 DPRINTF(("leaf pages: %"Yu, db->md_leaf_pages));
4831 DPRINTF(("overflow pages: %"Yu, db->md_overflow_pages));
4832 DPRINTF(("root: %"Yu, db->md_root));
4840 /** Release a reader thread's slot in the reader lock table.
4841 * This function is called automatically when a thread exits.
4842 * @param[in] ptr This points to the slot in the reader lock table.
4845 mdb_env_reader_dest(void *ptr)
4847 MDB_reader *reader = ptr;
4850 if (reader->mr_pid == getpid()) /* catch pthread_exit() in child process */
4852 /* We omit the mutex, so do this atomically (i.e. skip mr_txnid) */
4857 /** Junk for arranging thread-specific callbacks on Windows. This is
4858 * necessarily platform and compiler-specific. Windows supports up
4859 * to 1088 keys. Let's assume nobody opens more than 64 environments
4860 * in a single process, for now. They can override this if needed.
4862 #ifndef MAX_TLS_KEYS
4863 #define MAX_TLS_KEYS 64
4865 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4866 static int mdb_tls_nkeys;
4868 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4872 case DLL_PROCESS_ATTACH: break;
4873 case DLL_THREAD_ATTACH: break;
4874 case DLL_THREAD_DETACH:
4875 for (i=0; i<mdb_tls_nkeys; i++) {
4876 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4878 mdb_env_reader_dest(r);
4882 case DLL_PROCESS_DETACH: break;
4887 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4889 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4893 /* Force some symbol references.
4894 * _tls_used forces the linker to create the TLS directory if not already done
4895 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4897 #pragma comment(linker, "/INCLUDE:_tls_used")
4898 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4899 #pragma const_seg(".CRT$XLB")
4900 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4901 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4904 #pragma comment(linker, "/INCLUDE:__tls_used")
4905 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4906 #pragma data_seg(".CRT$XLB")
4907 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4909 #endif /* WIN 32/64 */
4910 #endif /* !__GNUC__ */
4913 /** Downgrade the exclusive lock on the region back to shared */
4915 mdb_env_share_locks(MDB_env *env, int *excl)
4918 MDB_meta *meta = mdb_env_pick_meta(env);
4920 env->me_txns->mti_txnid = meta->mm_txnid;
4925 /* First acquire a shared lock. The Unlock will
4926 * then release the existing exclusive lock.
4928 memset(&ov, 0, sizeof(ov));
4929 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4932 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4938 struct flock lock_info;
4939 /* The shared lock replaces the existing lock */
4940 memset((void *)&lock_info, 0, sizeof(lock_info));
4941 lock_info.l_type = F_RDLCK;
4942 lock_info.l_whence = SEEK_SET;
4943 lock_info.l_start = 0;
4944 lock_info.l_len = 1;
4945 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4946 (rc = ErrCode()) == EINTR) ;
4947 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4954 /** Try to get exclusive lock, otherwise shared.
4955 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4958 mdb_env_excl_lock(MDB_env *env, int *excl)
4962 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4966 memset(&ov, 0, sizeof(ov));
4967 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4974 struct flock lock_info;
4975 memset((void *)&lock_info, 0, sizeof(lock_info));
4976 lock_info.l_type = F_WRLCK;
4977 lock_info.l_whence = SEEK_SET;
4978 lock_info.l_start = 0;
4979 lock_info.l_len = 1;
4980 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4981 (rc = ErrCode()) == EINTR) ;
4985 # ifndef MDB_USE_POSIX_MUTEX
4986 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4989 lock_info.l_type = F_RDLCK;
4990 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4991 (rc = ErrCode()) == EINTR) ;
5001 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
5003 * @(#) $Revision: 5.1 $
5004 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
5005 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
5007 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
5011 * Please do not copyright this code. This code is in the public domain.
5013 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
5014 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
5015 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
5016 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
5017 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
5018 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
5019 * PERFORMANCE OF THIS SOFTWARE.
5022 * chongo <Landon Curt Noll> /\oo/\
5023 * http://www.isthe.com/chongo/
5025 * Share and Enjoy! :-)
5028 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
5029 * @param[in] val value to hash
5030 * @param[in] len length of value
5031 * @return 64 bit hash
5034 mdb_hash(const void *val, size_t len)
5036 const unsigned char *s = (const unsigned char *) val, *end = s + len;
5037 mdb_hash_t hval = 0xcbf29ce484222325ULL;
5039 * FNV-1a hash each octet of the buffer
5042 hval = (hval ^ *s++) * 0x100000001b3ULL;
5044 /* return our new hash value */
5048 /** Hash the string and output the encoded hash.
5049 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
5050 * very short name limits. We don't care about the encoding being reversible,
5051 * we just want to preserve as many bits of the input as possible in a
5052 * small printable string.
5053 * @param[in] str string to hash
5054 * @param[out] encbuf an array of 11 chars to hold the hash
5056 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
5059 mdb_pack85(unsigned long long l, char *out)
5063 for (i=0; i<10 && l; i++) {
5064 *out++ = mdb_a85[l % 85];
5070 /** Init #MDB_env.me_mutexname[] except the char which #MUTEXNAME() will set.
5071 * Changes to this code must be reflected in #MDB_LOCK_FORMAT.
5074 mdb_env_mname_init(MDB_env *env)
5076 char *nm = env->me_mutexname;
5077 strcpy(nm, MUTEXNAME_PREFIX);
5078 mdb_pack85(env->me_txns->mti_mutexid, nm + sizeof(MUTEXNAME_PREFIX));
5081 /** Return env->me_mutexname after filling in ch ('r'/'w') for convenience */
5082 #define MUTEXNAME(env, ch) ( \
5083 (void) ((env)->me_mutexname[sizeof(MUTEXNAME_PREFIX)-1] = (ch)), \
5084 (env)->me_mutexname)
5088 /** Open and/or initialize the lock region for the environment.
5089 * @param[in] env The LMDB environment.
5090 * @param[in] fname Filename + scratch area, from #mdb_fname_init().
5091 * @param[in] mode The Unix permissions for the file, if we create it.
5092 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
5093 * @return 0 on success, non-zero on failure.
5096 mdb_env_setup_locks(MDB_env *env, MDB_name *fname, int mode, int *excl)
5099 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
5101 # define MDB_ERRCODE_ROFS EROFS
5103 #ifdef MDB_USE_SYSV_SEM
5110 rc = mdb_fopen(env, fname, MDB_O_LOCKS, mode, &env->me_lfd);
5112 /* Omit lockfile if read-only env on read-only filesystem */
5113 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
5119 if (!(env->me_flags & MDB_NOTLS)) {
5120 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
5123 env->me_flags |= MDB_ENV_TXKEY;
5125 /* Windows TLS callbacks need help finding their TLS info. */
5126 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
5130 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
5134 /* Try to get exclusive lock. If we succeed, then
5135 * nobody is using the lock region and we should initialize it.
5137 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
5140 size = GetFileSize(env->me_lfd, NULL);
5142 size = lseek(env->me_lfd, 0, SEEK_END);
5143 if (size == -1) goto fail_errno;
5145 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
5146 if (size < rsize && *excl > 0) {
5148 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
5149 || !SetEndOfFile(env->me_lfd))
5152 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
5156 size = rsize - sizeof(MDB_txninfo);
5157 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
5162 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
5164 if (!mh) goto fail_errno;
5165 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
5167 if (!env->me_txns) goto fail_errno;
5169 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
5171 if (m == MAP_FAILED) goto fail_errno;
5177 BY_HANDLE_FILE_INFORMATION stbuf;
5184 if (!mdb_sec_inited) {
5185 InitializeSecurityDescriptor(&mdb_null_sd,
5186 SECURITY_DESCRIPTOR_REVISION);
5187 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
5188 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
5189 mdb_all_sa.bInheritHandle = FALSE;
5190 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
5193 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
5194 idbuf.volume = stbuf.dwVolumeSerialNumber;
5195 idbuf.nhigh = stbuf.nFileIndexHigh;
5196 idbuf.nlow = stbuf.nFileIndexLow;
5197 env->me_txns->mti_mutexid = mdb_hash(&idbuf, sizeof(idbuf));
5198 mdb_env_mname_init(env);
5199 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, MUTEXNAME(env, 'r'));
5200 if (!env->me_rmutex) goto fail_errno;
5201 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, MUTEXNAME(env, 'w'));
5202 if (!env->me_wmutex) goto fail_errno;
5203 #elif defined(MDB_USE_POSIX_SEM)
5210 #if defined(__NetBSD__)
5211 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
5213 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
5214 memset(&idbuf, 0, sizeof(idbuf));
5215 idbuf.dev = stbuf.st_dev;
5216 idbuf.ino = stbuf.st_ino;
5217 env->me_txns->mti_mutexid = mdb_hash(&idbuf, sizeof(idbuf))
5218 #ifdef MDB_SHORT_SEMNAMES
5219 /* Max 9 base85-digits. We truncate here instead of in
5220 * mdb_env_mname_init() to keep the latter portable.
5222 % ((mdb_hash_t)85*85*85*85*85*85*85*85*85)
5225 mdb_env_mname_init(env);
5226 /* Clean up after a previous run, if needed: Try to
5227 * remove both semaphores before doing anything else.
5229 sem_unlink(MUTEXNAME(env, 'r'));
5230 sem_unlink(MUTEXNAME(env, 'w'));
5231 env->me_rmutex = sem_open(MUTEXNAME(env, 'r'), O_CREAT|O_EXCL, mode, 1);
5232 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
5233 env->me_wmutex = sem_open(MUTEXNAME(env, 'w'), O_CREAT|O_EXCL, mode, 1);
5234 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
5235 #elif defined(MDB_USE_SYSV_SEM)
5236 unsigned short vals[2] = {1, 1};
5237 key_t key = ftok(fname->mn_val, 'M'); /* fname is lockfile path now */
5240 semid = semget(key, 2, (mode & 0777) | IPC_CREAT);
5244 if (semctl(semid, 0, SETALL, semu) < 0)
5246 env->me_txns->mti_semid = semid;
5247 env->me_txns->mti_rlocked = 0;
5248 env->me_txns->mti_wlocked = 0;
5249 #else /* MDB_USE_POSIX_MUTEX: */
5250 pthread_mutexattr_t mattr;
5252 /* Solaris needs this before initing a robust mutex. Otherwise
5253 * it may skip the init and return EBUSY "seems someone already
5254 * inited" or EINVAL "it was inited differently".
5256 memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
5257 memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
5259 if ((rc = pthread_mutexattr_init(&mattr)) != 0)
5261 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
5262 #ifdef MDB_ROBUST_SUPPORTED
5263 if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
5265 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
5266 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
5267 pthread_mutexattr_destroy(&mattr);
5270 #endif /* _WIN32 || ... */
5272 env->me_txns->mti_magic = MDB_MAGIC;
5273 env->me_txns->mti_format = MDB_LOCK_FORMAT;
5274 env->me_txns->mti_txnid = 0;
5275 env->me_txns->mti_numreaders = 0;
5278 #ifdef MDB_USE_SYSV_SEM
5279 struct semid_ds buf;
5281 if (env->me_txns->mti_magic != MDB_MAGIC) {
5282 DPUTS("lock region has invalid magic");
5286 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
5287 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
5288 env->me_txns->mti_format, MDB_LOCK_FORMAT));
5289 rc = MDB_VERSION_MISMATCH;
5293 if (rc && rc != EACCES && rc != EAGAIN) {
5297 mdb_env_mname_init(env);
5298 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, MUTEXNAME(env, 'r'));
5299 if (!env->me_rmutex) goto fail_errno;
5300 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, MUTEXNAME(env, 'w'));
5301 if (!env->me_wmutex) goto fail_errno;
5302 #elif defined(MDB_USE_POSIX_SEM)
5303 mdb_env_mname_init(env);
5304 env->me_rmutex = sem_open(MUTEXNAME(env, 'r'), 0);
5305 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
5306 env->me_wmutex = sem_open(MUTEXNAME(env, 'w'), 0);
5307 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
5308 #elif defined(MDB_USE_SYSV_SEM)
5309 semid = env->me_txns->mti_semid;
5311 /* check for read access */
5312 if (semctl(semid, 0, IPC_STAT, semu) < 0)
5314 /* check for write access */
5315 if (semctl(semid, 0, IPC_SET, semu) < 0)
5319 #ifdef MDB_USE_SYSV_SEM
5320 env->me_rmutex->semid = semid;
5321 env->me_wmutex->semid = semid;
5322 env->me_rmutex->semnum = 0;
5323 env->me_wmutex->semnum = 1;
5324 env->me_rmutex->locked = &env->me_txns->mti_rlocked;
5325 env->me_wmutex->locked = &env->me_txns->mti_wlocked;
5336 /** Only a subset of the @ref mdb_env flags can be changed
5337 * at runtime. Changing other flags requires closing the
5338 * environment and re-opening it with the new flags.
5340 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
5341 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
5342 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD|MDB_PREVMETA)
5344 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
5345 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
5349 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
5354 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
5358 if (flags & MDB_WRITEMAP) {
5359 /* silently ignore WRITEMAP in 32 bit mode */
5360 flags ^= MDB_WRITEMAP;
5362 if (flags & MDB_FIXEDMAP) {
5363 /* cannot support FIXEDMAP */
5367 flags |= env->me_flags;
5369 rc = mdb_fname_init(path, flags, &fname);
5375 env->me_rpmutex = CreateMutex(NULL, FALSE, NULL);
5376 if (!env->me_rpmutex) {
5381 rc = pthread_mutex_init(&env->me_rpmutex, NULL);
5386 flags |= MDB_ENV_ACTIVE; /* tell mdb_env_close0() to clean up */
5388 if (flags & MDB_RDONLY) {
5389 /* silently ignore WRITEMAP when we're only getting read access */
5390 flags &= ~MDB_WRITEMAP;
5392 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
5393 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
5397 env->me_flags = flags;
5403 env->me_rpages = malloc(MDB_ERPAGE_SIZE * sizeof(MDB_ID3));
5404 if (!env->me_rpages) {
5408 env->me_rpages[0].mid = 0;
5409 env->me_rpcheck = MDB_ERPAGE_SIZE/2;
5413 env->me_path = strdup(path);
5414 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
5415 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
5416 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
5417 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
5421 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
5423 /* For RDONLY, get lockfile after we know datafile exists */
5424 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
5425 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
5430 rc = mdb_fopen(env, &fname,
5431 (flags & MDB_RDONLY) ? MDB_O_RDONLY : MDB_O_RDWR,
5436 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
5437 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
5442 if ((rc = mdb_env_open2(env, flags & MDB_PREVMETA)) == MDB_SUCCESS) {
5443 if (!(flags & (MDB_RDONLY|MDB_WRITEMAP))) {
5444 /* Synchronous fd for meta writes. Needed even with
5445 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
5447 rc = mdb_fopen(env, &fname, MDB_O_META, mode, &env->me_mfd);
5451 DPRINTF(("opened dbenv %p", (void *) env));
5453 rc = mdb_env_share_locks(env, &excl);
5457 if (!(flags & MDB_RDONLY)) {
5459 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
5460 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
5461 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
5462 (txn = calloc(1, size)))
5464 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
5465 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
5466 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
5467 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
5470 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
5471 if (!txn->mt_rpages) {
5476 txn->mt_rpages[0].mid = 0;
5477 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
5479 txn->mt_dbxs = env->me_dbxs;
5480 txn->mt_flags = MDB_TXN_FINISHED;
5490 mdb_env_close0(env, excl);
5492 mdb_fname_destroy(fname);
5496 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
5498 mdb_env_close0(MDB_env *env, int excl)
5502 if (!(env->me_flags & MDB_ENV_ACTIVE))
5505 /* Doing this here since me_dbxs may not exist during mdb_env_close */
5507 for (i = env->me_maxdbs; --i >= CORE_DBS; )
5508 free(env->me_dbxs[i].md_name.mv_data);
5513 free(env->me_dbiseqs);
5514 free(env->me_dbflags);
5516 free(env->me_dirty_list);
5518 if (env->me_txn0 && env->me_txn0->mt_rpages)
5519 free(env->me_txn0->mt_rpages);
5520 if (env->me_rpages) {
5521 MDB_ID3L el = env->me_rpages;
5523 for (x=1; x<=el[0].mid; x++)
5524 munmap(el[x].mptr, el[x].mcnt * env->me_psize);
5529 mdb_midl_free(env->me_free_pgs);
5531 if (env->me_flags & MDB_ENV_TXKEY) {
5532 pthread_key_delete(env->me_txkey);
5534 /* Delete our key from the global list */
5535 for (i=0; i<mdb_tls_nkeys; i++)
5536 if (mdb_tls_keys[i] == env->me_txkey) {
5537 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
5546 munmap(env->me_map, NUM_METAS*env->me_psize);
5548 munmap(env->me_map, env->me_mapsize);
5551 if (env->me_mfd != INVALID_HANDLE_VALUE)
5552 (void) close(env->me_mfd);
5553 if (env->me_fd != INVALID_HANDLE_VALUE)
5554 (void) close(env->me_fd);
5556 MDB_PID_T pid = env->me_pid;
5557 /* Clearing readers is done in this function because
5558 * me_txkey with its destructor must be disabled first.
5560 * We skip the the reader mutex, so we touch only
5561 * data owned by this process (me_close_readers and
5562 * our readers), and clear each reader atomically.
5564 for (i = env->me_close_readers; --i >= 0; )
5565 if (env->me_txns->mti_readers[i].mr_pid == pid)
5566 env->me_txns->mti_readers[i].mr_pid = 0;
5568 if (env->me_rmutex) {
5569 CloseHandle(env->me_rmutex);
5570 if (env->me_wmutex) CloseHandle(env->me_wmutex);
5572 /* Windows automatically destroys the mutexes when
5573 * the last handle closes.
5575 #elif defined(MDB_USE_POSIX_SEM)
5576 if (env->me_rmutex != SEM_FAILED) {
5577 sem_close(env->me_rmutex);
5578 if (env->me_wmutex != SEM_FAILED)
5579 sem_close(env->me_wmutex);
5580 /* If we have the filelock: If we are the
5581 * only remaining user, clean up semaphores.
5584 mdb_env_excl_lock(env, &excl);
5586 sem_unlink(MUTEXNAME(env, 'r'));
5587 sem_unlink(MUTEXNAME(env, 'w'));
5590 #elif defined(MDB_USE_SYSV_SEM)
5591 if (env->me_rmutex->semid != -1) {
5592 /* If we have the filelock: If we are the
5593 * only remaining user, clean up semaphores.
5596 mdb_env_excl_lock(env, &excl);
5598 semctl(env->me_rmutex->semid, 0, IPC_RMID);
5601 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
5603 if (env->me_lfd != INVALID_HANDLE_VALUE) {
5606 /* Unlock the lockfile. Windows would have unlocked it
5607 * after closing anyway, but not necessarily at once.
5609 UnlockFile(env->me_lfd, 0, 0, 1, 0);
5612 (void) close(env->me_lfd);
5616 if (env->me_fmh) CloseHandle(env->me_fmh);
5617 if (env->me_rpmutex) CloseHandle(env->me_rpmutex);
5619 pthread_mutex_destroy(&env->me_rpmutex);
5623 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
5627 mdb_env_close(MDB_env *env)
5634 VGMEMP_DESTROY(env);
5635 while ((dp = env->me_dpages) != NULL) {
5636 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5637 env->me_dpages = dp->mp_next;
5641 mdb_env_close0(env, 0);
5645 /** Compare two items pointing at aligned #mdb_size_t's */
5647 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5649 return (*(mdb_size_t *)a->mv_data < *(mdb_size_t *)b->mv_data) ? -1 :
5650 *(mdb_size_t *)a->mv_data > *(mdb_size_t *)b->mv_data;
5653 /** Compare two items pointing at aligned unsigned int's.
5655 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5656 * but #mdb_cmp_clong() is called instead if the data type is #mdb_size_t.
5659 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5661 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5662 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5665 /** Compare two items pointing at unsigned ints of unknown alignment.
5666 * Nodes and keys are guaranteed to be 2-byte aligned.
5669 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5671 #if BYTE_ORDER == LITTLE_ENDIAN
5672 unsigned short *u, *c;
5675 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5676 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5679 } while(!x && u > (unsigned short *)a->mv_data);
5682 unsigned short *u, *c, *end;
5685 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5686 u = (unsigned short *)a->mv_data;
5687 c = (unsigned short *)b->mv_data;
5690 } while(!x && u < end);
5695 /** Compare two items lexically */
5697 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5704 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5710 diff = memcmp(a->mv_data, b->mv_data, len);
5711 return diff ? diff : len_diff<0 ? -1 : len_diff;
5714 /** Compare two items in reverse byte order */
5716 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5718 const unsigned char *p1, *p2, *p1_lim;
5722 p1_lim = (const unsigned char *)a->mv_data;
5723 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5724 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5726 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5732 while (p1 > p1_lim) {
5733 diff = *--p1 - *--p2;
5737 return len_diff<0 ? -1 : len_diff;
5740 /** Search for key within a page, using binary search.
5741 * Returns the smallest entry larger or equal to the key.
5742 * If exactp is non-null, stores whether the found entry was an exact match
5743 * in *exactp (1 or 0).
5744 * Updates the cursor index with the index of the found entry.
5745 * If no entry larger or equal to the key is found, returns NULL.
5748 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5750 unsigned int i = 0, nkeys;
5753 MDB_page *mp = mc->mc_pg[mc->mc_top];
5754 MDB_node *node = NULL;
5759 nkeys = NUMKEYS(mp);
5761 DPRINTF(("searching %u keys in %s %spage %"Yu,
5762 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5765 low = IS_LEAF(mp) ? 0 : 1;
5767 cmp = mc->mc_dbx->md_cmp;
5769 /* Branch pages have no data, so if using integer keys,
5770 * alignment is guaranteed. Use faster mdb_cmp_int.
5772 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5773 if (NODEPTR(mp, 1)->mn_ksize == sizeof(mdb_size_t))
5780 nodekey.mv_size = mc->mc_db->md_pad;
5781 node = NODEPTR(mp, 0); /* fake */
5782 while (low <= high) {
5783 i = (low + high) >> 1;
5784 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5785 rc = cmp(key, &nodekey);
5786 DPRINTF(("found leaf index %u [%s], rc = %i",
5787 i, DKEY(&nodekey), rc));
5796 while (low <= high) {
5797 i = (low + high) >> 1;
5799 node = NODEPTR(mp, i);
5800 nodekey.mv_size = NODEKSZ(node);
5801 nodekey.mv_data = NODEKEY(node);
5803 rc = cmp(key, &nodekey);
5806 DPRINTF(("found leaf index %u [%s], rc = %i",
5807 i, DKEY(&nodekey), rc));
5809 DPRINTF(("found branch index %u [%s -> %"Yu"], rc = %i",
5810 i, DKEY(&nodekey), NODEPGNO(node), rc));
5821 if (rc > 0) { /* Found entry is less than the key. */
5822 i++; /* Skip to get the smallest entry larger than key. */
5824 node = NODEPTR(mp, i);
5827 *exactp = (rc == 0 && nkeys > 0);
5828 /* store the key index */
5829 mc->mc_ki[mc->mc_top] = i;
5831 /* There is no entry larger or equal to the key. */
5834 /* nodeptr is fake for LEAF2 */
5840 mdb_cursor_adjust(MDB_cursor *mc, func)
5844 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5845 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5852 /** Pop a page off the top of the cursor's stack. */
5854 mdb_cursor_pop(MDB_cursor *mc)
5857 DPRINTF(("popping page %"Yu" off db %d cursor %p",
5858 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5864 mc->mc_flags &= ~C_INITIALIZED;
5869 /** Push a page onto the top of the cursor's stack.
5870 * Set #MDB_TXN_ERROR on failure.
5873 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5875 DPRINTF(("pushing page %"Yu" on db %d cursor %p", mp->mp_pgno,
5876 DDBI(mc), (void *) mc));
5878 if (mc->mc_snum >= CURSOR_STACK) {
5879 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5880 return MDB_CURSOR_FULL;
5883 mc->mc_top = mc->mc_snum++;
5884 mc->mc_pg[mc->mc_top] = mp;
5885 mc->mc_ki[mc->mc_top] = 0;
5891 /** Map a read-only page.
5892 * There are two levels of tracking in use, a per-txn list and a per-env list.
5893 * ref'ing and unref'ing the per-txn list is faster since it requires no
5894 * locking. Pages are cached in the per-env list for global reuse, and a lock
5895 * is required. Pages are not immediately unmapped when their refcnt goes to
5896 * zero; they hang around in case they will be reused again soon.
5898 * When the per-txn list gets full, all pages with refcnt=0 are purged from the
5899 * list and their refcnts in the per-env list are decremented.
5901 * When the per-env list gets full, all pages with refcnt=0 are purged from the
5902 * list and their pages are unmapped.
5904 * @note "full" means the list has reached its respective rpcheck threshold.
5905 * This threshold slowly raises if no pages could be purged on a given check,
5906 * and returns to its original value when enough pages were purged.
5908 * If purging doesn't free any slots, filling the per-txn list will return
5909 * MDB_TXN_FULL, and filling the per-env list returns MDB_MAP_FULL.
5911 * Reference tracking in a txn is imperfect, pages can linger with non-zero
5912 * refcnt even without active references. It was deemed to be too invasive
5913 * to add unrefs in every required location. However, all pages are unref'd
5914 * at the end of the transaction. This guarantees that no stale references
5915 * linger in the per-env list.
5917 * Usually we map chunks of 16 pages at a time, but if an overflow page begins
5918 * at the tail of the chunk we extend the chunk to include the entire overflow
5919 * page. Unfortunately, pages can be turned into overflow pages after their
5920 * chunk was already mapped. In that case we must remap the chunk if the
5921 * overflow page is referenced. If the chunk's refcnt is 0 we can just remap
5922 * it, otherwise we temporarily map a new chunk just for the overflow page.
5924 * @note this chunk handling means we cannot guarantee that a data item
5925 * returned from the DB will stay alive for the duration of the transaction:
5926 * We unref pages as soon as a cursor moves away from the page
5927 * A subsequent op may cause a purge, which may unmap any unref'd chunks
5928 * The caller must copy the data if it must be used later in the same txn.
5930 * Also - our reference counting revolves around cursors, but overflow pages
5931 * aren't pointed to by a cursor's page stack. We have to remember them
5932 * explicitly, in the added mc_ovpg field. A single cursor can only hold a
5933 * reference to one overflow page at a time.
5935 * @param[in] txn the transaction for this access.
5936 * @param[in] pgno the page number for the page to retrieve.
5937 * @param[out] ret address of a pointer where the page's address will be stored.
5938 * @return 0 on success, non-zero on failure.
5941 mdb_rpage_get(MDB_txn *txn, pgno_t pg0, MDB_page **ret)
5943 MDB_env *env = txn->mt_env;
5945 MDB_ID3L tl = txn->mt_rpages;
5946 MDB_ID3L el = env->me_rpages;
5950 int rc, retries = 1;
5954 #define SET_OFF(off,val) off.QuadPart = val
5955 #define MAP(rc,env,addr,len,off) \
5957 rc = NtMapViewOfSection(env->me_fmh, GetCurrentProcess(), &addr, 0, \
5958 len, &off, &len, ViewUnmap, (env->me_flags & MDB_RDONLY) ? 0 : MEM_RESERVE, PAGE_READONLY); \
5959 if (rc) rc = mdb_nt2win32(rc)
5963 #define SET_OFF(off,val) off = val
5964 #define MAP(rc,env,addr,len,off) \
5965 addr = mmap(NULL, len, PROT_READ, MAP_SHARED, env->me_fd, off); \
5966 rc = (addr == MAP_FAILED) ? errno : 0
5969 /* remember the offset of the actual page number, so we can
5970 * return the correct pointer at the end.
5972 rem = pg0 & (MDB_RPAGE_CHUNK-1);
5976 x = mdb_mid3l_search(tl, pgno);
5977 if (x <= tl[0].mid && tl[x].mid == pgno) {
5978 if (x != tl[0].mid && tl[x+1].mid == pg0)
5980 /* check for overflow size */
5981 p = (MDB_page *)((char *)tl[x].mptr + rem * env->me_psize);
5982 if (IS_OVERFLOW(p) && p->mp_pages + rem > tl[x].mcnt) {
5983 id3.mcnt = p->mp_pages + rem;
5984 len = id3.mcnt * env->me_psize;
5985 SET_OFF(off, pgno * env->me_psize);
5986 MAP(rc, env, id3.mptr, len, off);
5989 /* check for local-only page */
5991 mdb_tassert(txn, tl[x].mid != pg0);
5992 /* hope there's room to insert this locally.
5993 * setting mid here tells later code to just insert
5994 * this id3 instead of searching for a match.
5999 /* ignore the mapping we got from env, use new one */
6000 tl[x].mptr = id3.mptr;
6001 tl[x].mcnt = id3.mcnt;
6002 /* if no active ref, see if we can replace in env */
6005 pthread_mutex_lock(&env->me_rpmutex);
6006 i = mdb_mid3l_search(el, tl[x].mid);
6007 if (el[i].mref == 1) {
6008 /* just us, replace it */
6009 munmap(el[i].mptr, el[i].mcnt * env->me_psize);
6010 el[i].mptr = tl[x].mptr;
6011 el[i].mcnt = tl[x].mcnt;
6013 /* there are others, remove ourself */
6016 pthread_mutex_unlock(&env->me_rpmutex);
6020 id3.mptr = tl[x].mptr;
6021 id3.mcnt = tl[x].mcnt;
6027 if (tl[0].mid >= MDB_TRPAGE_MAX - txn->mt_rpcheck) {
6029 /* purge unref'd pages from our list and unref in env */
6030 pthread_mutex_lock(&env->me_rpmutex);
6033 for (i=1; i<=tl[0].mid; i++) {
6036 /* tmp overflow pages don't go to env */
6037 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
6038 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
6041 x = mdb_mid3l_search(el, tl[i].mid);
6045 pthread_mutex_unlock(&env->me_rpmutex);
6047 /* we didn't find any unref'd chunks.
6048 * if we're out of room, fail.
6050 if (tl[0].mid >= MDB_TRPAGE_MAX)
6051 return MDB_TXN_FULL;
6052 /* otherwise, raise threshold for next time around
6055 txn->mt_rpcheck /= 2;
6057 /* we found some unused; consolidate the list */
6058 for (i=y+1; i<= tl[0].mid; i++)
6062 /* decrease the check threshold toward its original value */
6063 if (!txn->mt_rpcheck)
6064 txn->mt_rpcheck = 1;
6065 while (txn->mt_rpcheck < tl[0].mid && txn->mt_rpcheck < MDB_TRPAGE_SIZE/2)
6066 txn->mt_rpcheck *= 2;
6069 if (tl[0].mid < MDB_TRPAGE_SIZE) {
6073 /* don't map past last written page in read-only envs */
6074 if ((env->me_flags & MDB_RDONLY) && pgno + MDB_RPAGE_CHUNK-1 > txn->mt_last_pgno)
6075 id3.mcnt = txn->mt_last_pgno + 1 - pgno;
6077 id3.mcnt = MDB_RPAGE_CHUNK;
6078 len = id3.mcnt * env->me_psize;
6081 /* search for page in env */
6082 pthread_mutex_lock(&env->me_rpmutex);
6083 x = mdb_mid3l_search(el, pgno);
6084 if (x <= el[0].mid && el[x].mid == pgno) {
6085 id3.mptr = el[x].mptr;
6086 id3.mcnt = el[x].mcnt;
6087 /* check for overflow size */
6088 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
6089 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
6090 id3.mcnt = p->mp_pages + rem;
6091 len = id3.mcnt * env->me_psize;
6092 SET_OFF(off, pgno * env->me_psize);
6093 MAP(rc, env, id3.mptr, len, off);
6097 munmap(el[x].mptr, env->me_psize * el[x].mcnt);
6098 el[x].mptr = id3.mptr;
6099 el[x].mcnt = id3.mcnt;
6102 pthread_mutex_unlock(&env->me_rpmutex);
6107 pthread_mutex_unlock(&env->me_rpmutex);
6110 if (el[0].mid >= MDB_ERPAGE_MAX - env->me_rpcheck) {
6111 /* purge unref'd pages */
6113 for (i=1; i<=el[0].mid; i++) {
6116 munmap(el[i].mptr, env->me_psize * el[i].mcnt);
6121 /* see if we can unref some local pages */
6126 if (el[0].mid >= MDB_ERPAGE_MAX) {
6127 pthread_mutex_unlock(&env->me_rpmutex);
6128 return MDB_MAP_FULL;
6130 env->me_rpcheck /= 2;
6132 for (i=y+1; i<= el[0].mid; i++)
6136 if (!env->me_rpcheck)
6137 env->me_rpcheck = 1;
6138 while (env->me_rpcheck < el[0].mid && env->me_rpcheck < MDB_ERPAGE_SIZE/2)
6139 env->me_rpcheck *= 2;
6142 SET_OFF(off, pgno * env->me_psize);
6143 MAP(rc, env, id3.mptr, len, off);
6146 pthread_mutex_unlock(&env->me_rpmutex);
6149 /* check for overflow size */
6150 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
6151 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
6152 id3.mcnt = p->mp_pages + rem;
6153 munmap(id3.mptr, len);
6154 len = id3.mcnt * env->me_psize;
6155 MAP(rc, env, id3.mptr, len, off);
6159 mdb_mid3l_insert(el, &id3);
6160 pthread_mutex_unlock(&env->me_rpmutex);
6162 mdb_mid3l_insert(tl, &id3);
6164 return MDB_TXN_FULL;
6167 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
6168 #if MDB_DEBUG /* we don't need this check any more */
6169 if (IS_OVERFLOW(p)) {
6170 mdb_tassert(txn, p->mp_pages + rem <= id3.mcnt);
6178 /** Find the address of the page corresponding to a given page number.
6179 * Set #MDB_TXN_ERROR on failure.
6180 * @param[in] mc the cursor accessing the page.
6181 * @param[in] pgno the page number for the page to retrieve.
6182 * @param[out] ret address of a pointer where the page's address will be stored.
6183 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
6184 * @return 0 on success, non-zero on failure.
6187 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
6189 MDB_txn *txn = mc->mc_txn;
6193 if (! (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP))) {
6197 MDB_ID2L dl = tx2->mt_u.dirty_list;
6199 /* Spilled pages were dirtied in this txn and flushed
6200 * because the dirty list got full. Bring this page
6201 * back in from the map (but don't unspill it here,
6202 * leave that unless page_touch happens again).
6204 if (tx2->mt_spill_pgs) {
6205 MDB_ID pn = pgno << 1;
6206 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
6207 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
6212 unsigned x = mdb_mid2l_search(dl, pgno);
6213 if (x <= dl[0].mid && dl[x].mid == pgno) {
6219 } while ((tx2 = tx2->mt_parent) != NULL);
6222 if (pgno >= txn->mt_next_pgno) {
6223 DPRINTF(("page %"Yu" not found", pgno));
6224 txn->mt_flags |= MDB_TXN_ERROR;
6225 return MDB_PAGE_NOTFOUND;
6233 int rc = mdb_rpage_get(txn, pgno, &p);
6235 txn->mt_flags |= MDB_TXN_ERROR;
6239 MDB_env *env = txn->mt_env;
6240 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
6251 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
6252 * The cursor is at the root page, set up the rest of it.
6255 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
6257 MDB_page *mp = mc->mc_pg[mc->mc_top];
6261 while (IS_BRANCH(mp)) {
6265 DPRINTF(("branch page %"Yu" has %u keys", mp->mp_pgno, NUMKEYS(mp)));
6266 /* Don't assert on branch pages in the FreeDB. We can get here
6267 * while in the process of rebalancing a FreeDB branch page; we must
6268 * let that proceed. ITS#8336
6270 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
6271 DPRINTF(("found index 0 to page %"Yu, NODEPGNO(NODEPTR(mp, 0))));
6273 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
6275 if (flags & MDB_PS_LAST) {
6276 i = NUMKEYS(mp) - 1;
6277 /* if already init'd, see if we're already in right place */
6278 if (mc->mc_flags & C_INITIALIZED) {
6279 if (mc->mc_ki[mc->mc_top] == i) {
6280 mc->mc_top = mc->mc_snum++;
6281 mp = mc->mc_pg[mc->mc_top];
6288 node = mdb_node_search(mc, key, &exact);
6290 i = NUMKEYS(mp) - 1;
6292 i = mc->mc_ki[mc->mc_top];
6294 mdb_cassert(mc, i > 0);
6298 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
6301 mdb_cassert(mc, i < NUMKEYS(mp));
6302 node = NODEPTR(mp, i);
6304 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6307 mc->mc_ki[mc->mc_top] = i;
6308 if ((rc = mdb_cursor_push(mc, mp)))
6312 if (flags & MDB_PS_MODIFY) {
6313 if ((rc = mdb_page_touch(mc)) != 0)
6315 mp = mc->mc_pg[mc->mc_top];
6320 DPRINTF(("internal error, index points to a %02X page!?",
6322 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6323 return MDB_CORRUPTED;
6326 DPRINTF(("found leaf page %"Yu" for key [%s]", mp->mp_pgno,
6327 key ? DKEY(key) : "null"));
6328 mc->mc_flags |= C_INITIALIZED;
6329 mc->mc_flags &= ~C_EOF;
6334 /** Search for the lowest key under the current branch page.
6335 * This just bypasses a NUMKEYS check in the current page
6336 * before calling mdb_page_search_root(), because the callers
6337 * are all in situations where the current page is known to
6341 mdb_page_search_lowest(MDB_cursor *mc)
6343 MDB_page *mp = mc->mc_pg[mc->mc_top];
6344 MDB_node *node = NODEPTR(mp, 0);
6347 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6350 mc->mc_ki[mc->mc_top] = 0;
6351 if ((rc = mdb_cursor_push(mc, mp)))
6353 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
6356 /** Search for the page a given key should be in.
6357 * Push it and its parent pages on the cursor stack.
6358 * @param[in,out] mc the cursor for this operation.
6359 * @param[in] key the key to search for, or NULL for first/last page.
6360 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
6361 * are touched (updated with new page numbers).
6362 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
6363 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
6364 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
6365 * @return 0 on success, non-zero on failure.
6368 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
6373 /* Make sure the txn is still viable, then find the root from
6374 * the txn's db table and set it as the root of the cursor's stack.
6376 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
6377 DPUTS("transaction may not be used now");
6380 /* Make sure we're using an up-to-date root */
6381 if (*mc->mc_dbflag & DB_STALE) {
6383 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6385 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
6386 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
6393 MDB_node *leaf = mdb_node_search(&mc2,
6394 &mc->mc_dbx->md_name, &exact);
6396 return MDB_NOTFOUND;
6397 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
6398 return MDB_INCOMPATIBLE; /* not a named DB */
6399 rc = mdb_node_read(&mc2, leaf, &data);
6402 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
6404 /* The txn may not know this DBI, or another process may
6405 * have dropped and recreated the DB with other flags.
6407 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
6408 return MDB_INCOMPATIBLE;
6409 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
6411 *mc->mc_dbflag &= ~DB_STALE;
6413 root = mc->mc_db->md_root;
6415 if (root == P_INVALID) { /* Tree is empty. */
6416 DPUTS("tree is empty");
6417 return MDB_NOTFOUND;
6421 mdb_cassert(mc, root > 1);
6422 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root) {
6425 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[0]);
6427 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
6434 for (i=1; i<mc->mc_snum; i++)
6435 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[i]);
6441 DPRINTF(("db %d root page %"Yu" has flags 0x%X",
6442 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
6444 if (flags & MDB_PS_MODIFY) {
6445 if ((rc = mdb_page_touch(mc)))
6449 if (flags & MDB_PS_ROOTONLY)
6452 return mdb_page_search_root(mc, key, flags);
6456 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
6458 MDB_txn *txn = mc->mc_txn;
6459 pgno_t pg = mp->mp_pgno;
6460 unsigned x = 0, ovpages = mp->mp_pages;
6461 MDB_env *env = txn->mt_env;
6462 MDB_IDL sl = txn->mt_spill_pgs;
6463 MDB_ID pn = pg << 1;
6466 DPRINTF(("free ov page %"Yu" (%d)", pg, ovpages));
6467 /* If the page is dirty or on the spill list we just acquired it,
6468 * so we should give it back to our current free list, if any.
6469 * Otherwise put it onto the list of pages we freed in this txn.
6471 * Won't create me_pghead: me_pglast must be inited along with it.
6472 * Unsupported in nested txns: They would need to hide the page
6473 * range in ancestor txns' dirty and spilled lists.
6475 if (env->me_pghead &&
6477 ((mp->mp_flags & P_DIRTY) ||
6478 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
6482 MDB_ID2 *dl, ix, iy;
6483 rc = mdb_midl_need(&env->me_pghead, ovpages);
6486 if (!(mp->mp_flags & P_DIRTY)) {
6487 /* This page is no longer spilled */
6494 /* Remove from dirty list */
6495 dl = txn->mt_u.dirty_list;
6497 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
6503 mdb_cassert(mc, x > 1);
6505 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
6506 txn->mt_flags |= MDB_TXN_ERROR;
6510 txn->mt_dirty_room++;
6511 if (!(env->me_flags & MDB_WRITEMAP))
6512 mdb_dpage_free(env, mp);
6514 /* Insert in me_pghead */
6515 mop = env->me_pghead;
6516 j = mop[0] + ovpages;
6517 for (i = mop[0]; i && mop[i] < pg; i--)
6523 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
6528 if (mc->mc_ovpg == mp)
6531 mc->mc_db->md_overflow_pages -= ovpages;
6535 /** Return the data associated with a given node.
6536 * @param[in] mc The cursor for this operation.
6537 * @param[in] leaf The node being read.
6538 * @param[out] data Updated to point to the node's data.
6539 * @return 0 on success, non-zero on failure.
6542 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
6544 MDB_page *omp; /* overflow page */
6549 MDB_PAGE_UNREF(mc->mc_txn, MC_OVPG(mc));
6550 MC_SET_OVPG(mc, NULL);
6552 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6553 data->mv_size = NODEDSZ(leaf);
6554 data->mv_data = NODEDATA(leaf);
6558 /* Read overflow data.
6560 data->mv_size = NODEDSZ(leaf);
6561 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
6562 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
6563 DPRINTF(("read overflow page %"Yu" failed", pgno));
6566 data->mv_data = METADATA(omp);
6567 MC_SET_OVPG(mc, omp);
6573 mdb_get(MDB_txn *txn, MDB_dbi dbi,
6574 MDB_val *key, MDB_val *data)
6581 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
6583 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
6586 if (txn->mt_flags & MDB_TXN_BLOCKED)
6589 mdb_cursor_init(&mc, txn, dbi, &mx);
6590 rc = mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
6591 /* unref all the pages when MDB_VL32 - caller must copy the data
6592 * before doing anything else
6594 MDB_CURSOR_UNREF(&mc, 1);
6598 /** Find a sibling for a page.
6599 * Replaces the page at the top of the cursor's stack with the
6600 * specified sibling, if one exists.
6601 * @param[in] mc The cursor for this operation.
6602 * @param[in] move_right Non-zero if the right sibling is requested,
6603 * otherwise the left sibling.
6604 * @return 0 on success, non-zero on failure.
6607 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
6616 if (mc->mc_snum < 2) {
6617 return MDB_NOTFOUND; /* root has no siblings */
6621 op = mc->mc_pg[mc->mc_top];
6624 DPRINTF(("parent page is page %"Yu", index %u",
6625 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
6627 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6628 : (mc->mc_ki[mc->mc_top] == 0)) {
6629 DPRINTF(("no more keys left, moving to %s sibling",
6630 move_right ? "right" : "left"));
6631 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
6632 /* undo cursor_pop before returning */
6639 mc->mc_ki[mc->mc_top]++;
6641 mc->mc_ki[mc->mc_top]--;
6642 DPRINTF(("just moving to %s index key %u",
6643 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
6645 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
6647 MDB_PAGE_UNREF(mc->mc_txn, op);
6649 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6650 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
6651 /* mc will be inconsistent if caller does mc_snum++ as above */
6652 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6656 mdb_cursor_push(mc, mp);
6658 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
6663 /** Move the cursor to the next data item. */
6665 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6671 if ((mc->mc_flags & C_DEL && op == MDB_NEXT_DUP))
6672 return MDB_NOTFOUND;
6674 if (!(mc->mc_flags & C_INITIALIZED))
6675 return mdb_cursor_first(mc, key, data);
6677 mp = mc->mc_pg[mc->mc_top];
6679 if (mc->mc_flags & C_EOF) {
6680 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mp)-1)
6681 return MDB_NOTFOUND;
6682 mc->mc_flags ^= C_EOF;
6685 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6686 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6687 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6688 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
6689 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
6690 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
6691 if (rc == MDB_SUCCESS)
6692 MDB_GET_KEY(leaf, key);
6697 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6700 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6701 if (op == MDB_NEXT_DUP)
6702 return MDB_NOTFOUND;
6706 DPRINTF(("cursor_next: top page is %"Yu" in cursor %p",
6707 mdb_dbg_pgno(mp), (void *) mc));
6708 if (mc->mc_flags & C_DEL) {
6709 mc->mc_flags ^= C_DEL;
6713 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
6714 DPUTS("=====> move to next sibling page");
6715 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6716 mc->mc_flags |= C_EOF;
6719 mp = mc->mc_pg[mc->mc_top];
6720 DPRINTF(("next page is %"Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6722 mc->mc_ki[mc->mc_top]++;
6725 DPRINTF(("==> cursor points to page %"Yu" with %u keys, key index %u",
6726 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6729 key->mv_size = mc->mc_db->md_pad;
6730 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6734 mdb_cassert(mc, IS_LEAF(mp));
6735 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6737 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6738 mdb_xcursor_init1(mc, leaf);
6741 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6744 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6745 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6746 if (rc != MDB_SUCCESS)
6751 MDB_GET_KEY(leaf, key);
6755 /** Move the cursor to the previous data item. */
6757 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6763 if (!(mc->mc_flags & C_INITIALIZED)) {
6764 rc = mdb_cursor_last(mc, key, data);
6767 mc->mc_ki[mc->mc_top]++;
6770 mp = mc->mc_pg[mc->mc_top];
6772 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6773 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6774 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6775 if (op == MDB_PREV || op == MDB_PREV_DUP) {
6776 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
6777 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
6778 if (rc == MDB_SUCCESS) {
6779 MDB_GET_KEY(leaf, key);
6780 mc->mc_flags &= ~C_EOF;
6786 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6789 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6790 if (op == MDB_PREV_DUP)
6791 return MDB_NOTFOUND;
6795 DPRINTF(("cursor_prev: top page is %"Yu" in cursor %p",
6796 mdb_dbg_pgno(mp), (void *) mc));
6798 mc->mc_flags &= ~(C_EOF|C_DEL);
6800 if (mc->mc_ki[mc->mc_top] == 0) {
6801 DPUTS("=====> move to prev sibling page");
6802 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
6805 mp = mc->mc_pg[mc->mc_top];
6806 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
6807 DPRINTF(("prev page is %"Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6809 mc->mc_ki[mc->mc_top]--;
6811 DPRINTF(("==> cursor points to page %"Yu" with %u keys, key index %u",
6812 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6815 key->mv_size = mc->mc_db->md_pad;
6816 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6820 mdb_cassert(mc, IS_LEAF(mp));
6821 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6823 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6824 mdb_xcursor_init1(mc, leaf);
6827 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6830 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6831 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6832 if (rc != MDB_SUCCESS)
6837 MDB_GET_KEY(leaf, key);
6841 /** Set the cursor on a specific data item. */
6843 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6844 MDB_cursor_op op, int *exactp)
6848 MDB_node *leaf = NULL;
6851 if (key->mv_size == 0)
6852 return MDB_BAD_VALSIZE;
6854 if (mc->mc_xcursor) {
6855 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6856 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6859 /* See if we're already on the right page */
6860 if (mc->mc_flags & C_INITIALIZED) {
6863 mp = mc->mc_pg[mc->mc_top];
6865 mc->mc_ki[mc->mc_top] = 0;
6866 return MDB_NOTFOUND;
6868 if (mp->mp_flags & P_LEAF2) {
6869 nodekey.mv_size = mc->mc_db->md_pad;
6870 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
6872 leaf = NODEPTR(mp, 0);
6873 MDB_GET_KEY2(leaf, nodekey);
6875 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6877 /* Probably happens rarely, but first node on the page
6878 * was the one we wanted.
6880 mc->mc_ki[mc->mc_top] = 0;
6887 unsigned int nkeys = NUMKEYS(mp);
6889 if (mp->mp_flags & P_LEAF2) {
6890 nodekey.mv_data = LEAF2KEY(mp,
6891 nkeys-1, nodekey.mv_size);
6893 leaf = NODEPTR(mp, nkeys-1);
6894 MDB_GET_KEY2(leaf, nodekey);
6896 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6898 /* last node was the one we wanted */
6899 mc->mc_ki[mc->mc_top] = nkeys-1;
6905 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
6906 /* This is definitely the right page, skip search_page */
6907 if (mp->mp_flags & P_LEAF2) {
6908 nodekey.mv_data = LEAF2KEY(mp,
6909 mc->mc_ki[mc->mc_top], nodekey.mv_size);
6911 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6912 MDB_GET_KEY2(leaf, nodekey);
6914 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6916 /* current node was the one we wanted */
6923 mc->mc_flags &= ~C_EOF;
6927 /* If any parents have right-sibs, search.
6928 * Otherwise, there's nothing further.
6930 for (i=0; i<mc->mc_top; i++)
6932 NUMKEYS(mc->mc_pg[i])-1)
6934 if (i == mc->mc_top) {
6935 /* There are no other pages */
6936 mc->mc_ki[mc->mc_top] = nkeys;
6937 return MDB_NOTFOUND;
6941 /* There are no other pages */
6942 mc->mc_ki[mc->mc_top] = 0;
6943 if (op == MDB_SET_RANGE && !exactp) {
6947 return MDB_NOTFOUND;
6953 rc = mdb_page_search(mc, key, 0);
6954 if (rc != MDB_SUCCESS)
6957 mp = mc->mc_pg[mc->mc_top];
6958 mdb_cassert(mc, IS_LEAF(mp));
6961 leaf = mdb_node_search(mc, key, exactp);
6962 if (exactp != NULL && !*exactp) {
6963 /* MDB_SET specified and not an exact match. */
6964 return MDB_NOTFOUND;
6968 DPUTS("===> inexact leaf not found, goto sibling");
6969 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6970 mc->mc_flags |= C_EOF;
6971 return rc; /* no entries matched */
6973 mp = mc->mc_pg[mc->mc_top];
6974 mdb_cassert(mc, IS_LEAF(mp));
6975 leaf = NODEPTR(mp, 0);
6979 mc->mc_flags |= C_INITIALIZED;
6980 mc->mc_flags &= ~C_EOF;
6983 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
6984 key->mv_size = mc->mc_db->md_pad;
6985 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6990 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6991 mdb_xcursor_init1(mc, leaf);
6994 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6995 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
6996 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6999 if (op == MDB_GET_BOTH) {
7005 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
7006 if (rc != MDB_SUCCESS)
7009 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
7012 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
7014 dcmp = mc->mc_dbx->md_dcmp;
7015 if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
7016 dcmp = mdb_cmp_clong;
7017 rc = dcmp(data, &olddata);
7019 if (op == MDB_GET_BOTH || rc > 0)
7020 return MDB_NOTFOUND;
7027 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
7028 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
7033 /* The key already matches in all other cases */
7034 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
7035 MDB_GET_KEY(leaf, key);
7036 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
7041 /** Move the cursor to the first item in the database. */
7043 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
7048 if (mc->mc_xcursor) {
7049 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
7050 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
7053 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
7054 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
7055 if (rc != MDB_SUCCESS)
7058 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
7060 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
7061 mc->mc_flags |= C_INITIALIZED;
7062 mc->mc_flags &= ~C_EOF;
7064 mc->mc_ki[mc->mc_top] = 0;
7066 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7067 key->mv_size = mc->mc_db->md_pad;
7068 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
7073 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7074 mdb_xcursor_init1(mc, leaf);
7075 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
7079 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
7083 MDB_GET_KEY(leaf, key);
7087 /** Move the cursor to the last item in the database. */
7089 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
7094 if (mc->mc_xcursor) {
7095 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
7096 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
7099 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
7100 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
7101 if (rc != MDB_SUCCESS)
7104 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
7106 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
7107 mc->mc_flags |= C_INITIALIZED|C_EOF;
7108 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7110 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7111 key->mv_size = mc->mc_db->md_pad;
7112 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
7117 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7118 mdb_xcursor_init1(mc, leaf);
7119 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
7123 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
7128 MDB_GET_KEY(leaf, key);
7133 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7138 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
7143 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
7147 case MDB_GET_CURRENT:
7148 if (!(mc->mc_flags & C_INITIALIZED)) {
7151 MDB_page *mp = mc->mc_pg[mc->mc_top];
7152 int nkeys = NUMKEYS(mp);
7153 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
7154 mc->mc_ki[mc->mc_top] = nkeys;
7160 key->mv_size = mc->mc_db->md_pad;
7161 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
7163 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7164 MDB_GET_KEY(leaf, key);
7166 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7167 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
7169 rc = mdb_node_read(mc, leaf, data);
7176 case MDB_GET_BOTH_RANGE:
7181 if (mc->mc_xcursor == NULL) {
7182 rc = MDB_INCOMPATIBLE;
7192 rc = mdb_cursor_set(mc, key, data, op,
7193 op == MDB_SET_RANGE ? NULL : &exact);
7196 case MDB_GET_MULTIPLE:
7197 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7201 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7202 rc = MDB_INCOMPATIBLE;
7206 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
7207 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
7210 case MDB_NEXT_MULTIPLE:
7215 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7216 rc = MDB_INCOMPATIBLE;
7219 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
7220 if (rc == MDB_SUCCESS) {
7221 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
7224 mx = &mc->mc_xcursor->mx_cursor;
7225 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
7227 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
7228 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
7234 case MDB_PREV_MULTIPLE:
7239 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7240 rc = MDB_INCOMPATIBLE;
7243 if (!(mc->mc_flags & C_INITIALIZED))
7244 rc = mdb_cursor_last(mc, key, data);
7247 if (rc == MDB_SUCCESS) {
7248 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
7249 if (mx->mc_flags & C_INITIALIZED) {
7250 rc = mdb_cursor_sibling(mx, 0);
7251 if (rc == MDB_SUCCESS)
7260 case MDB_NEXT_NODUP:
7261 rc = mdb_cursor_next(mc, key, data, op);
7265 case MDB_PREV_NODUP:
7266 rc = mdb_cursor_prev(mc, key, data, op);
7269 rc = mdb_cursor_first(mc, key, data);
7272 mfunc = mdb_cursor_first;
7274 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7278 if (mc->mc_xcursor == NULL) {
7279 rc = MDB_INCOMPATIBLE;
7282 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top])) {
7283 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7288 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7289 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7290 MDB_GET_KEY(leaf, key);
7291 rc = mdb_node_read(mc, leaf, data);
7295 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
7299 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
7302 rc = mdb_cursor_last(mc, key, data);
7305 mfunc = mdb_cursor_last;
7308 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
7313 if (mc->mc_flags & C_DEL)
7314 mc->mc_flags ^= C_DEL;
7319 /** Touch all the pages in the cursor stack. Set mc_top.
7320 * Makes sure all the pages are writable, before attempting a write operation.
7321 * @param[in] mc The cursor to operate on.
7324 mdb_cursor_touch(MDB_cursor *mc)
7326 int rc = MDB_SUCCESS;
7328 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & (DB_DIRTY|DB_DUPDATA))) {
7329 /* Touch DB record of named DB */
7332 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
7334 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
7335 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
7338 *mc->mc_dbflag |= DB_DIRTY;
7343 rc = mdb_page_touch(mc);
7344 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
7345 mc->mc_top = mc->mc_snum-1;
7350 /** Do not spill pages to disk if txn is getting full, may fail instead */
7351 #define MDB_NOSPILL 0x8000
7354 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7358 MDB_node *leaf = NULL;
7359 MDB_page *fp, *mp, *sub_root = NULL;
7361 MDB_val xdata, *rdata, dkey, olddata;
7363 int do_sub = 0, insert_key, insert_data;
7364 unsigned int mcount = 0, dcount = 0, nospill;
7367 unsigned int nflags;
7370 if (mc == NULL || key == NULL)
7373 env = mc->mc_txn->mt_env;
7375 /* Check this first so counter will always be zero on any
7378 if (flags & MDB_MULTIPLE) {
7379 dcount = data[1].mv_size;
7380 data[1].mv_size = 0;
7381 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
7382 return MDB_INCOMPATIBLE;
7385 nospill = flags & MDB_NOSPILL;
7386 flags &= ~MDB_NOSPILL;
7388 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7389 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7391 if (key->mv_size-1 >= ENV_MAXKEY(env))
7392 return MDB_BAD_VALSIZE;
7394 #if SIZE_MAX > MAXDATASIZE
7395 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
7396 return MDB_BAD_VALSIZE;
7398 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
7399 return MDB_BAD_VALSIZE;
7402 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
7403 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
7407 if (flags == MDB_CURRENT) {
7408 if (!(mc->mc_flags & C_INITIALIZED))
7411 } else if (mc->mc_db->md_root == P_INVALID) {
7412 /* new database, cursor has nothing to point to */
7415 mc->mc_flags &= ~C_INITIALIZED;
7420 if (flags & MDB_APPEND) {
7422 rc = mdb_cursor_last(mc, &k2, &d2);
7424 rc = mc->mc_dbx->md_cmp(key, &k2);
7427 mc->mc_ki[mc->mc_top]++;
7429 /* new key is <= last key */
7434 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
7436 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
7437 DPRINTF(("duplicate key [%s]", DKEY(key)));
7439 return MDB_KEYEXIST;
7441 if (rc && rc != MDB_NOTFOUND)
7445 if (mc->mc_flags & C_DEL)
7446 mc->mc_flags ^= C_DEL;
7448 /* Cursor is positioned, check for room in the dirty list */
7450 if (flags & MDB_MULTIPLE) {
7452 xdata.mv_size = data->mv_size * dcount;
7456 if ((rc2 = mdb_page_spill(mc, key, rdata)))
7460 if (rc == MDB_NO_ROOT) {
7462 /* new database, write a root leaf page */
7463 DPUTS("allocating new root leaf page");
7464 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
7467 mdb_cursor_push(mc, np);
7468 mc->mc_db->md_root = np->mp_pgno;
7469 mc->mc_db->md_depth++;
7470 *mc->mc_dbflag |= DB_DIRTY;
7471 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
7473 np->mp_flags |= P_LEAF2;
7474 mc->mc_flags |= C_INITIALIZED;
7476 /* make sure all cursor pages are writable */
7477 rc2 = mdb_cursor_touch(mc);
7482 insert_key = insert_data = rc;
7484 /* The key does not exist */
7485 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
7486 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
7487 LEAFSIZE(key, data) > env->me_nodemax)
7489 /* Too big for a node, insert in sub-DB. Set up an empty
7490 * "old sub-page" for prep_subDB to expand to a full page.
7492 fp_flags = P_LEAF|P_DIRTY;
7494 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
7495 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
7496 olddata.mv_size = PAGEHDRSZ;
7500 /* there's only a key anyway, so this is a no-op */
7501 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7503 unsigned int ksize = mc->mc_db->md_pad;
7504 if (key->mv_size != ksize)
7505 return MDB_BAD_VALSIZE;
7506 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
7507 memcpy(ptr, key->mv_data, ksize);
7509 /* if overwriting slot 0 of leaf, need to
7510 * update branch key if there is a parent page
7512 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7513 unsigned short dtop = 1;
7515 /* slot 0 is always an empty key, find real slot */
7516 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7520 if (mc->mc_ki[mc->mc_top])
7521 rc2 = mdb_update_key(mc, key);
7532 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7533 olddata.mv_size = NODEDSZ(leaf);
7534 olddata.mv_data = NODEDATA(leaf);
7537 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
7538 /* Prepare (sub-)page/sub-DB to accept the new item,
7539 * if needed. fp: old sub-page or a header faking
7540 * it. mp: new (sub-)page. offset: growth in page
7541 * size. xdata: node data with new page or DB.
7543 unsigned i, offset = 0;
7544 mp = fp = xdata.mv_data = env->me_pbuf;
7545 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
7547 /* Was a single item before, must convert now */
7548 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7550 /* Just overwrite the current item */
7551 if (flags == MDB_CURRENT)
7553 dcmp = mc->mc_dbx->md_dcmp;
7554 if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
7555 dcmp = mdb_cmp_clong;
7556 /* does data match? */
7557 if (!dcmp(data, &olddata)) {
7558 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
7559 return MDB_KEYEXIST;
7564 /* Back up original data item */
7565 dkey.mv_size = olddata.mv_size;
7566 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
7568 /* Make sub-page header for the dup items, with dummy body */
7569 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
7570 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
7571 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
7572 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7573 fp->mp_flags |= P_LEAF2;
7574 fp->mp_pad = data->mv_size;
7575 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
7577 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
7578 (dkey.mv_size & 1) + (data->mv_size & 1);
7580 fp->mp_upper = xdata.mv_size - PAGEBASE;
7581 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
7582 } else if (leaf->mn_flags & F_SUBDATA) {
7583 /* Data is on sub-DB, just store it */
7584 flags |= F_DUPDATA|F_SUBDATA;
7587 /* Data is on sub-page */
7588 fp = olddata.mv_data;
7591 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7592 offset = EVEN(NODESIZE + sizeof(indx_t) +
7596 offset = fp->mp_pad;
7597 if (SIZELEFT(fp) < offset) {
7598 offset *= 4; /* space for 4 more */
7601 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
7603 fp->mp_flags |= P_DIRTY;
7604 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
7605 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
7609 xdata.mv_size = olddata.mv_size + offset;
7612 fp_flags = fp->mp_flags;
7613 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
7614 /* Too big for a sub-page, convert to sub-DB */
7615 fp_flags &= ~P_SUBP;
7617 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7618 fp_flags |= P_LEAF2;
7619 dummy.md_pad = fp->mp_pad;
7620 dummy.md_flags = MDB_DUPFIXED;
7621 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7622 dummy.md_flags |= MDB_INTEGERKEY;
7628 dummy.md_branch_pages = 0;
7629 dummy.md_leaf_pages = 1;
7630 dummy.md_overflow_pages = 0;
7631 dummy.md_entries = NUMKEYS(fp);
7632 xdata.mv_size = sizeof(MDB_db);
7633 xdata.mv_data = &dummy;
7634 if ((rc = mdb_page_alloc(mc, 1, &mp)))
7636 offset = env->me_psize - olddata.mv_size;
7637 flags |= F_DUPDATA|F_SUBDATA;
7638 dummy.md_root = mp->mp_pgno;
7642 mp->mp_flags = fp_flags | P_DIRTY;
7643 mp->mp_pad = fp->mp_pad;
7644 mp->mp_lower = fp->mp_lower;
7645 mp->mp_upper = fp->mp_upper + offset;
7646 if (fp_flags & P_LEAF2) {
7647 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
7649 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
7650 olddata.mv_size - fp->mp_upper - PAGEBASE);
7651 for (i=0; i<NUMKEYS(fp); i++)
7652 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
7660 mdb_node_del(mc, 0);
7664 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
7665 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
7666 return MDB_INCOMPATIBLE;
7667 /* overflow page overwrites need special handling */
7668 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7671 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
7673 memcpy(&pg, olddata.mv_data, sizeof(pg));
7674 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
7676 ovpages = omp->mp_pages;
7678 /* Is the ov page large enough? */
7679 if (ovpages >= dpages) {
7680 if (!(omp->mp_flags & P_DIRTY) &&
7681 (level || (env->me_flags & MDB_WRITEMAP)))
7683 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
7686 level = 0; /* dirty in this txn or clean */
7689 if (omp->mp_flags & P_DIRTY) {
7690 /* yes, overwrite it. Note in this case we don't
7691 * bother to try shrinking the page if the new data
7692 * is smaller than the overflow threshold.
7695 /* It is writable only in a parent txn */
7696 size_t sz = (size_t) env->me_psize * ovpages, off;
7697 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
7703 /* Note - this page is already counted in parent's dirty_room */
7704 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
7705 mdb_cassert(mc, rc2 == 0);
7706 /* Currently we make the page look as with put() in the
7707 * parent txn, in case the user peeks at MDB_RESERVEd
7708 * or unused parts. Some users treat ovpages specially.
7710 if (!(flags & MDB_RESERVE)) {
7711 /* Skip the part where LMDB will put *data.
7712 * Copy end of page, adjusting alignment so
7713 * compiler may copy words instead of bytes.
7715 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
7716 memcpy((size_t *)((char *)np + off),
7717 (size_t *)((char *)omp + off), sz - off);
7720 memcpy(np, omp, sz); /* Copy beginning of page */
7723 SETDSZ(leaf, data->mv_size);
7724 if (F_ISSET(flags, MDB_RESERVE))
7725 data->mv_data = METADATA(omp);
7727 memcpy(METADATA(omp), data->mv_data, data->mv_size);
7731 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
7733 } else if (data->mv_size == olddata.mv_size) {
7734 /* same size, just replace it. Note that we could
7735 * also reuse this node if the new data is smaller,
7736 * but instead we opt to shrink the node in that case.
7738 if (F_ISSET(flags, MDB_RESERVE))
7739 data->mv_data = olddata.mv_data;
7740 else if (!(mc->mc_flags & C_SUB))
7741 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
7743 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
7748 mdb_node_del(mc, 0);
7754 nflags = flags & NODE_ADD_FLAGS;
7755 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
7756 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
7757 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
7758 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
7760 nflags |= MDB_SPLIT_REPLACE;
7761 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
7763 /* There is room already in this leaf page. */
7764 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
7766 /* Adjust other cursors pointing to mp */
7767 MDB_cursor *m2, *m3;
7768 MDB_dbi dbi = mc->mc_dbi;
7769 unsigned i = mc->mc_top;
7770 MDB_page *mp = mc->mc_pg[i];
7772 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7773 if (mc->mc_flags & C_SUB)
7774 m3 = &m2->mc_xcursor->mx_cursor;
7777 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
7778 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
7781 XCURSOR_REFRESH(m3, i, mp);
7786 if (rc == MDB_SUCCESS) {
7787 /* Now store the actual data in the child DB. Note that we're
7788 * storing the user data in the keys field, so there are strict
7789 * size limits on dupdata. The actual data fields of the child
7790 * DB are all zero size.
7793 int xflags, new_dupdata;
7798 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7799 if (flags & MDB_CURRENT) {
7800 xflags = MDB_CURRENT|MDB_NOSPILL;
7802 mdb_xcursor_init1(mc, leaf);
7803 xflags = (flags & MDB_NODUPDATA) ?
7804 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
7807 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
7808 new_dupdata = (int)dkey.mv_size;
7809 /* converted, write the original data first */
7811 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
7814 /* we've done our job */
7817 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
7818 /* Adjust other cursors pointing to mp */
7820 MDB_xcursor *mx = mc->mc_xcursor;
7821 unsigned i = mc->mc_top;
7822 MDB_page *mp = mc->mc_pg[i];
7824 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7825 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7826 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7827 if (m2->mc_pg[i] == mp) {
7828 if (m2->mc_ki[i] == mc->mc_ki[i]) {
7829 mdb_xcursor_init2(m2, mx, new_dupdata);
7830 } else if (!insert_key) {
7831 XCURSOR_REFRESH(m2, i, mp);
7836 ecount = mc->mc_xcursor->mx_db.md_entries;
7837 if (flags & MDB_APPENDDUP)
7838 xflags |= MDB_APPEND;
7839 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
7840 if (flags & F_SUBDATA) {
7841 void *db = NODEDATA(leaf);
7842 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7844 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
7846 /* Increment count unless we just replaced an existing item. */
7848 mc->mc_db->md_entries++;
7850 /* Invalidate txn if we created an empty sub-DB */
7853 /* If we succeeded and the key didn't exist before,
7854 * make sure the cursor is marked valid.
7856 mc->mc_flags |= C_INITIALIZED;
7858 if (flags & MDB_MULTIPLE) {
7861 /* let caller know how many succeeded, if any */
7862 data[1].mv_size = mcount;
7863 if (mcount < dcount) {
7864 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
7865 insert_key = insert_data = 0;
7872 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
7875 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7880 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
7886 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7887 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7889 if (!(mc->mc_flags & C_INITIALIZED))
7892 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
7893 return MDB_NOTFOUND;
7895 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
7898 rc = mdb_cursor_touch(mc);
7902 mp = mc->mc_pg[mc->mc_top];
7905 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7907 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7908 if (flags & MDB_NODUPDATA) {
7909 /* mdb_cursor_del0() will subtract the final entry */
7910 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
7911 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7913 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
7914 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7916 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
7919 /* If sub-DB still has entries, we're done */
7920 if (mc->mc_xcursor->mx_db.md_entries) {
7921 if (leaf->mn_flags & F_SUBDATA) {
7922 /* update subDB info */
7923 void *db = NODEDATA(leaf);
7924 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7927 /* shrink fake page */
7928 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
7929 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7930 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7931 /* fix other sub-DB cursors pointed at fake pages on this page */
7932 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7933 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7934 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7935 if (m2->mc_pg[mc->mc_top] == mp) {
7936 XCURSOR_REFRESH(m2, mc->mc_top, mp);
7940 mc->mc_db->md_entries--;
7943 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7945 /* otherwise fall thru and delete the sub-DB */
7948 if (leaf->mn_flags & F_SUBDATA) {
7949 /* add all the child DB's pages to the free list */
7950 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7955 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
7956 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
7957 rc = MDB_INCOMPATIBLE;
7961 /* add overflow pages to free list */
7962 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7966 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7967 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
7968 (rc = mdb_ovpage_free(mc, omp)))
7973 return mdb_cursor_del0(mc);
7976 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7980 /** Allocate and initialize new pages for a database.
7981 * Set #MDB_TXN_ERROR on failure.
7982 * @param[in] mc a cursor on the database being added to.
7983 * @param[in] flags flags defining what type of page is being allocated.
7984 * @param[in] num the number of pages to allocate. This is usually 1,
7985 * unless allocating overflow pages for a large record.
7986 * @param[out] mp Address of a page, or NULL on failure.
7987 * @return 0 on success, non-zero on failure.
7990 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
7995 if ((rc = mdb_page_alloc(mc, num, &np)))
7997 DPRINTF(("allocated new mpage %"Yu", page size %u",
7998 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
7999 np->mp_flags = flags | P_DIRTY;
8000 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
8001 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
8004 mc->mc_db->md_branch_pages++;
8005 else if (IS_LEAF(np))
8006 mc->mc_db->md_leaf_pages++;
8007 else if (IS_OVERFLOW(np)) {
8008 mc->mc_db->md_overflow_pages += num;
8016 /** Calculate the size of a leaf node.
8017 * The size depends on the environment's page size; if a data item
8018 * is too large it will be put onto an overflow page and the node
8019 * size will only include the key and not the data. Sizes are always
8020 * rounded up to an even number of bytes, to guarantee 2-byte alignment
8021 * of the #MDB_node headers.
8022 * @param[in] env The environment handle.
8023 * @param[in] key The key for the node.
8024 * @param[in] data The data for the node.
8025 * @return The number of bytes needed to store the node.
8028 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
8032 sz = LEAFSIZE(key, data);
8033 if (sz > env->me_nodemax) {
8034 /* put on overflow page */
8035 sz -= data->mv_size - sizeof(pgno_t);
8038 return EVEN(sz + sizeof(indx_t));
8041 /** Calculate the size of a branch node.
8042 * The size should depend on the environment's page size but since
8043 * we currently don't support spilling large keys onto overflow
8044 * pages, it's simply the size of the #MDB_node header plus the
8045 * size of the key. Sizes are always rounded up to an even number
8046 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
8047 * @param[in] env The environment handle.
8048 * @param[in] key The key for the node.
8049 * @return The number of bytes needed to store the node.
8052 mdb_branch_size(MDB_env *env, MDB_val *key)
8057 if (sz > env->me_nodemax) {
8058 /* put on overflow page */
8059 /* not implemented */
8060 /* sz -= key->size - sizeof(pgno_t); */
8063 return sz + sizeof(indx_t);
8066 /** Add a node to the page pointed to by the cursor.
8067 * Set #MDB_TXN_ERROR on failure.
8068 * @param[in] mc The cursor for this operation.
8069 * @param[in] indx The index on the page where the new node should be added.
8070 * @param[in] key The key for the new node.
8071 * @param[in] data The data for the new node, if any.
8072 * @param[in] pgno The page number, if adding a branch node.
8073 * @param[in] flags Flags for the node.
8074 * @return 0 on success, non-zero on failure. Possible errors are:
8076 * <li>ENOMEM - failed to allocate overflow pages for the node.
8077 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
8078 * should never happen since all callers already calculate the
8079 * page's free space before calling this function.
8083 mdb_node_add(MDB_cursor *mc, indx_t indx,
8084 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
8087 size_t node_size = NODESIZE;
8091 MDB_page *mp = mc->mc_pg[mc->mc_top];
8092 MDB_page *ofp = NULL; /* overflow page */
8096 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
8098 DPRINTF(("add to %s %spage %"Yu" index %i, data size %"Z"u key size %"Z"u [%s]",
8099 IS_LEAF(mp) ? "leaf" : "branch",
8100 IS_SUBP(mp) ? "sub-" : "",
8101 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
8102 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
8105 /* Move higher keys up one slot. */
8106 int ksize = mc->mc_db->md_pad, dif;
8107 char *ptr = LEAF2KEY(mp, indx, ksize);
8108 dif = NUMKEYS(mp) - indx;
8110 memmove(ptr+ksize, ptr, dif*ksize);
8111 /* insert new key */
8112 memcpy(ptr, key->mv_data, ksize);
8114 /* Just using these for counting */
8115 mp->mp_lower += sizeof(indx_t);
8116 mp->mp_upper -= ksize - sizeof(indx_t);
8120 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
8122 node_size += key->mv_size;
8124 mdb_cassert(mc, key && data);
8125 if (F_ISSET(flags, F_BIGDATA)) {
8126 /* Data already on overflow page. */
8127 node_size += sizeof(pgno_t);
8128 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
8129 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
8131 /* Put data on overflow page. */
8132 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
8133 data->mv_size, node_size+data->mv_size));
8134 node_size = EVEN(node_size + sizeof(pgno_t));
8135 if ((ssize_t)node_size > room)
8137 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
8139 DPRINTF(("allocated overflow page %"Yu, ofp->mp_pgno));
8143 node_size += data->mv_size;
8146 node_size = EVEN(node_size);
8147 if ((ssize_t)node_size > room)
8151 /* Move higher pointers up one slot. */
8152 for (i = NUMKEYS(mp); i > indx; i--)
8153 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
8155 /* Adjust free space offsets. */
8156 ofs = mp->mp_upper - node_size;
8157 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
8158 mp->mp_ptrs[indx] = ofs;
8160 mp->mp_lower += sizeof(indx_t);
8162 /* Write the node data. */
8163 node = NODEPTR(mp, indx);
8164 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
8165 node->mn_flags = flags;
8167 SETDSZ(node,data->mv_size);
8172 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8175 ndata = NODEDATA(node);
8177 if (F_ISSET(flags, F_BIGDATA))
8178 memcpy(ndata, data->mv_data, sizeof(pgno_t));
8179 else if (F_ISSET(flags, MDB_RESERVE))
8180 data->mv_data = ndata;
8182 memcpy(ndata, data->mv_data, data->mv_size);
8184 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
8185 ndata = METADATA(ofp);
8186 if (F_ISSET(flags, MDB_RESERVE))
8187 data->mv_data = ndata;
8189 memcpy(ndata, data->mv_data, data->mv_size);
8196 DPRINTF(("not enough room in page %"Yu", got %u ptrs",
8197 mdb_dbg_pgno(mp), NUMKEYS(mp)));
8198 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
8199 DPRINTF(("node size = %"Z"u", node_size));
8200 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8201 return MDB_PAGE_FULL;
8204 /** Delete the specified node from a page.
8205 * @param[in] mc Cursor pointing to the node to delete.
8206 * @param[in] ksize The size of a node. Only used if the page is
8207 * part of a #MDB_DUPFIXED database.
8210 mdb_node_del(MDB_cursor *mc, int ksize)
8212 MDB_page *mp = mc->mc_pg[mc->mc_top];
8213 indx_t indx = mc->mc_ki[mc->mc_top];
8215 indx_t i, j, numkeys, ptr;
8219 DPRINTF(("delete node %u on %s page %"Yu, indx,
8220 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
8221 numkeys = NUMKEYS(mp);
8222 mdb_cassert(mc, indx < numkeys);
8225 int x = numkeys - 1 - indx;
8226 base = LEAF2KEY(mp, indx, ksize);
8228 memmove(base, base + ksize, x * ksize);
8229 mp->mp_lower -= sizeof(indx_t);
8230 mp->mp_upper += ksize - sizeof(indx_t);
8234 node = NODEPTR(mp, indx);
8235 sz = NODESIZE + node->mn_ksize;
8237 if (F_ISSET(node->mn_flags, F_BIGDATA))
8238 sz += sizeof(pgno_t);
8240 sz += NODEDSZ(node);
8244 ptr = mp->mp_ptrs[indx];
8245 for (i = j = 0; i < numkeys; i++) {
8247 mp->mp_ptrs[j] = mp->mp_ptrs[i];
8248 if (mp->mp_ptrs[i] < ptr)
8249 mp->mp_ptrs[j] += sz;
8254 base = (char *)mp + mp->mp_upper + PAGEBASE;
8255 memmove(base + sz, base, ptr - mp->mp_upper);
8257 mp->mp_lower -= sizeof(indx_t);
8261 /** Compact the main page after deleting a node on a subpage.
8262 * @param[in] mp The main page to operate on.
8263 * @param[in] indx The index of the subpage on the main page.
8266 mdb_node_shrink(MDB_page *mp, indx_t indx)
8271 indx_t delta, nsize, len, ptr;
8274 node = NODEPTR(mp, indx);
8275 sp = (MDB_page *)NODEDATA(node);
8276 delta = SIZELEFT(sp);
8277 nsize = NODEDSZ(node) - delta;
8279 /* Prepare to shift upward, set len = length(subpage part to shift) */
8283 return; /* do not make the node uneven-sized */
8285 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
8286 for (i = NUMKEYS(sp); --i >= 0; )
8287 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
8290 sp->mp_upper = sp->mp_lower;
8291 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
8292 SETDSZ(node, nsize);
8294 /* Shift <lower nodes...initial part of subpage> upward */
8295 base = (char *)mp + mp->mp_upper + PAGEBASE;
8296 memmove(base + delta, base, (char *)sp + len - base);
8298 ptr = mp->mp_ptrs[indx];
8299 for (i = NUMKEYS(mp); --i >= 0; ) {
8300 if (mp->mp_ptrs[i] <= ptr)
8301 mp->mp_ptrs[i] += delta;
8303 mp->mp_upper += delta;
8306 /** Initial setup of a sorted-dups cursor.
8307 * Sorted duplicates are implemented as a sub-database for the given key.
8308 * The duplicate data items are actually keys of the sub-database.
8309 * Operations on the duplicate data items are performed using a sub-cursor
8310 * initialized when the sub-database is first accessed. This function does
8311 * the preliminary setup of the sub-cursor, filling in the fields that
8312 * depend only on the parent DB.
8313 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8316 mdb_xcursor_init0(MDB_cursor *mc)
8318 MDB_xcursor *mx = mc->mc_xcursor;
8320 mx->mx_cursor.mc_xcursor = NULL;
8321 mx->mx_cursor.mc_txn = mc->mc_txn;
8322 mx->mx_cursor.mc_db = &mx->mx_db;
8323 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
8324 mx->mx_cursor.mc_dbi = mc->mc_dbi;
8325 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
8326 mx->mx_cursor.mc_snum = 0;
8327 mx->mx_cursor.mc_top = 0;
8328 MC_SET_OVPG(&mx->mx_cursor, NULL);
8329 mx->mx_cursor.mc_flags = C_SUB | (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP));
8330 mx->mx_dbx.md_name.mv_size = 0;
8331 mx->mx_dbx.md_name.mv_data = NULL;
8332 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
8333 mx->mx_dbx.md_dcmp = NULL;
8334 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
8337 /** Final setup of a sorted-dups cursor.
8338 * Sets up the fields that depend on the data from the main cursor.
8339 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8340 * @param[in] node The data containing the #MDB_db record for the
8341 * sorted-dup database.
8344 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
8346 MDB_xcursor *mx = mc->mc_xcursor;
8348 mx->mx_cursor.mc_flags &= C_SUB|C_ORIG_RDONLY|C_WRITEMAP;
8349 if (node->mn_flags & F_SUBDATA) {
8350 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
8351 mx->mx_cursor.mc_pg[0] = 0;
8352 mx->mx_cursor.mc_snum = 0;
8353 mx->mx_cursor.mc_top = 0;
8355 MDB_page *fp = NODEDATA(node);
8356 mx->mx_db.md_pad = 0;
8357 mx->mx_db.md_flags = 0;
8358 mx->mx_db.md_depth = 1;
8359 mx->mx_db.md_branch_pages = 0;
8360 mx->mx_db.md_leaf_pages = 1;
8361 mx->mx_db.md_overflow_pages = 0;
8362 mx->mx_db.md_entries = NUMKEYS(fp);
8363 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
8364 mx->mx_cursor.mc_snum = 1;
8365 mx->mx_cursor.mc_top = 0;
8366 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8367 mx->mx_cursor.mc_pg[0] = fp;
8368 mx->mx_cursor.mc_ki[0] = 0;
8369 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
8370 mx->mx_db.md_flags = MDB_DUPFIXED;
8371 mx->mx_db.md_pad = fp->mp_pad;
8372 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
8373 mx->mx_db.md_flags |= MDB_INTEGERKEY;
8376 DPRINTF(("Sub-db -%u root page %"Yu, mx->mx_cursor.mc_dbi,
8377 mx->mx_db.md_root));
8378 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
8379 if (NEED_CMP_CLONG(mx->mx_dbx.md_cmp, mx->mx_db.md_pad))
8380 mx->mx_dbx.md_cmp = mdb_cmp_clong;
8384 /** Fixup a sorted-dups cursor due to underlying update.
8385 * Sets up some fields that depend on the data from the main cursor.
8386 * Almost the same as init1, but skips initialization steps if the
8387 * xcursor had already been used.
8388 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
8389 * @param[in] src_mx The xcursor of an up-to-date cursor.
8390 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
8393 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
8395 MDB_xcursor *mx = mc->mc_xcursor;
8398 mx->mx_cursor.mc_snum = 1;
8399 mx->mx_cursor.mc_top = 0;
8400 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8401 mx->mx_cursor.mc_ki[0] = 0;
8402 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
8403 #if UINT_MAX < MDB_SIZE_MAX /* matches mdb_xcursor_init1:NEED_CMP_CLONG() */
8404 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
8406 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
8409 mx->mx_db = src_mx->mx_db;
8410 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
8411 DPRINTF(("Sub-db -%u root page %"Yu, mx->mx_cursor.mc_dbi,
8412 mx->mx_db.md_root));
8415 /** Initialize a cursor for a given transaction and database. */
8417 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
8420 mc->mc_backup = NULL;
8423 mc->mc_db = &txn->mt_dbs[dbi];
8424 mc->mc_dbx = &txn->mt_dbxs[dbi];
8425 mc->mc_dbflag = &txn->mt_dbflags[dbi];
8430 MC_SET_OVPG(mc, NULL);
8431 mc->mc_flags = txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
8432 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
8433 mdb_tassert(txn, mx != NULL);
8434 mc->mc_xcursor = mx;
8435 mdb_xcursor_init0(mc);
8437 mc->mc_xcursor = NULL;
8439 if (*mc->mc_dbflag & DB_STALE) {
8440 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
8445 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
8448 size_t size = sizeof(MDB_cursor);
8450 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
8453 if (txn->mt_flags & MDB_TXN_BLOCKED)
8456 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8459 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
8460 size += sizeof(MDB_xcursor);
8462 if ((mc = malloc(size)) != NULL) {
8463 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
8464 if (txn->mt_cursors) {
8465 mc->mc_next = txn->mt_cursors[dbi];
8466 txn->mt_cursors[dbi] = mc;
8467 mc->mc_flags |= C_UNTRACK;
8479 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
8481 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
8484 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
8487 if (txn->mt_flags & MDB_TXN_BLOCKED)
8490 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
8494 /* Return the count of duplicate data items for the current key */
8496 mdb_cursor_count(MDB_cursor *mc, mdb_size_t *countp)
8500 if (mc == NULL || countp == NULL)
8503 if (mc->mc_xcursor == NULL)
8504 return MDB_INCOMPATIBLE;
8506 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
8509 if (!(mc->mc_flags & C_INITIALIZED))
8513 return MDB_NOTFOUND;
8515 if (mc->mc_flags & C_EOF) {
8516 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
8517 return MDB_NOTFOUND;
8518 mc->mc_flags ^= C_EOF;
8521 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8522 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
8525 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
8528 *countp = mc->mc_xcursor->mx_db.md_entries;
8534 mdb_cursor_close(MDB_cursor *mc)
8537 MDB_CURSOR_UNREF(mc, 0);
8539 if (mc && !mc->mc_backup) {
8540 /* Remove from txn, if tracked.
8541 * A read-only txn (!C_UNTRACK) may have been freed already,
8542 * so do not peek inside it. Only write txns track cursors.
8544 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
8545 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
8546 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
8548 *prev = mc->mc_next;
8555 mdb_cursor_txn(MDB_cursor *mc)
8557 if (!mc) return NULL;
8562 mdb_cursor_dbi(MDB_cursor *mc)
8567 /** Replace the key for a branch node with a new key.
8568 * Set #MDB_TXN_ERROR on failure.
8569 * @param[in] mc Cursor pointing to the node to operate on.
8570 * @param[in] key The new key to use.
8571 * @return 0 on success, non-zero on failure.
8574 mdb_update_key(MDB_cursor *mc, MDB_val *key)
8580 int delta, ksize, oksize;
8581 indx_t ptr, i, numkeys, indx;
8584 indx = mc->mc_ki[mc->mc_top];
8585 mp = mc->mc_pg[mc->mc_top];
8586 node = NODEPTR(mp, indx);
8587 ptr = mp->mp_ptrs[indx];
8591 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
8592 k2.mv_data = NODEKEY(node);
8593 k2.mv_size = node->mn_ksize;
8594 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Yu,
8596 mdb_dkey(&k2, kbuf2),
8602 /* Sizes must be 2-byte aligned. */
8603 ksize = EVEN(key->mv_size);
8604 oksize = EVEN(node->mn_ksize);
8605 delta = ksize - oksize;
8607 /* Shift node contents if EVEN(key length) changed. */
8609 if (delta > 0 && SIZELEFT(mp) < delta) {
8611 /* not enough space left, do a delete and split */
8612 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
8613 pgno = NODEPGNO(node);
8614 mdb_node_del(mc, 0);
8615 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
8618 numkeys = NUMKEYS(mp);
8619 for (i = 0; i < numkeys; i++) {
8620 if (mp->mp_ptrs[i] <= ptr)
8621 mp->mp_ptrs[i] -= delta;
8624 base = (char *)mp + mp->mp_upper + PAGEBASE;
8625 len = ptr - mp->mp_upper + NODESIZE;
8626 memmove(base - delta, base, len);
8627 mp->mp_upper -= delta;
8629 node = NODEPTR(mp, indx);
8632 /* But even if no shift was needed, update ksize */
8633 if (node->mn_ksize != key->mv_size)
8634 node->mn_ksize = key->mv_size;
8637 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8643 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
8645 /** Perform \b act while tracking temporary cursor \b mn */
8646 #define WITH_CURSOR_TRACKING(mn, act) do { \
8647 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
8648 if ((mn).mc_flags & C_SUB) { \
8649 dummy.mc_flags = C_INITIALIZED; \
8650 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
8655 tracked->mc_next = *tp; \
8658 *tp = tracked->mc_next; \
8661 /** Move a node from csrc to cdst.
8664 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
8671 unsigned short flags;
8675 /* Mark src and dst as dirty. */
8676 if ((rc = mdb_page_touch(csrc)) ||
8677 (rc = mdb_page_touch(cdst)))
8680 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8681 key.mv_size = csrc->mc_db->md_pad;
8682 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
8684 data.mv_data = NULL;
8688 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
8689 mdb_cassert(csrc, !((size_t)srcnode & 1));
8690 srcpg = NODEPGNO(srcnode);
8691 flags = srcnode->mn_flags;
8692 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8693 unsigned int snum = csrc->mc_snum;
8695 /* must find the lowest key below src */
8696 rc = mdb_page_search_lowest(csrc);
8699 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8700 key.mv_size = csrc->mc_db->md_pad;
8701 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8703 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8704 key.mv_size = NODEKSZ(s2);
8705 key.mv_data = NODEKEY(s2);
8707 csrc->mc_snum = snum--;
8708 csrc->mc_top = snum;
8710 key.mv_size = NODEKSZ(srcnode);
8711 key.mv_data = NODEKEY(srcnode);
8713 data.mv_size = NODEDSZ(srcnode);
8714 data.mv_data = NODEDATA(srcnode);
8716 mn.mc_xcursor = NULL;
8717 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
8718 unsigned int snum = cdst->mc_snum;
8721 /* must find the lowest key below dst */
8722 mdb_cursor_copy(cdst, &mn);
8723 rc = mdb_page_search_lowest(&mn);
8726 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8727 bkey.mv_size = mn.mc_db->md_pad;
8728 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
8730 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8731 bkey.mv_size = NODEKSZ(s2);
8732 bkey.mv_data = NODEKEY(s2);
8734 mn.mc_snum = snum--;
8737 rc = mdb_update_key(&mn, &bkey);
8742 DPRINTF(("moving %s node %u [%s] on page %"Yu" to node %u on page %"Yu,
8743 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
8744 csrc->mc_ki[csrc->mc_top],
8746 csrc->mc_pg[csrc->mc_top]->mp_pgno,
8747 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
8749 /* Add the node to the destination page.
8751 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
8752 if (rc != MDB_SUCCESS)
8755 /* Delete the node from the source page.
8757 mdb_node_del(csrc, key.mv_size);
8760 /* Adjust other cursors pointing to mp */
8761 MDB_cursor *m2, *m3;
8762 MDB_dbi dbi = csrc->mc_dbi;
8763 MDB_page *mpd, *mps;
8765 mps = csrc->mc_pg[csrc->mc_top];
8766 /* If we're adding on the left, bump others up */
8768 mpd = cdst->mc_pg[csrc->mc_top];
8769 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8770 if (csrc->mc_flags & C_SUB)
8771 m3 = &m2->mc_xcursor->mx_cursor;
8774 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8777 m3->mc_pg[csrc->mc_top] == mpd &&
8778 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
8779 m3->mc_ki[csrc->mc_top]++;
8782 m3->mc_pg[csrc->mc_top] == mps &&
8783 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
8784 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8785 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8786 m3->mc_ki[csrc->mc_top-1]++;
8789 XCURSOR_REFRESH(m3, csrc->mc_top, m3->mc_pg[csrc->mc_top]);
8792 /* Adding on the right, bump others down */
8794 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8795 if (csrc->mc_flags & C_SUB)
8796 m3 = &m2->mc_xcursor->mx_cursor;
8799 if (m3 == csrc) continue;
8800 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8802 if (m3->mc_pg[csrc->mc_top] == mps) {
8803 if (!m3->mc_ki[csrc->mc_top]) {
8804 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8805 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8806 m3->mc_ki[csrc->mc_top-1]--;
8808 m3->mc_ki[csrc->mc_top]--;
8811 XCURSOR_REFRESH(m3, csrc->mc_top, m3->mc_pg[csrc->mc_top]);
8817 /* Update the parent separators.
8819 if (csrc->mc_ki[csrc->mc_top] == 0) {
8820 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
8821 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8822 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8824 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8825 key.mv_size = NODEKSZ(srcnode);
8826 key.mv_data = NODEKEY(srcnode);
8828 DPRINTF(("update separator for source page %"Yu" to [%s]",
8829 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
8830 mdb_cursor_copy(csrc, &mn);
8833 /* We want mdb_rebalance to find mn when doing fixups */
8834 WITH_CURSOR_TRACKING(mn,
8835 rc = mdb_update_key(&mn, &key));
8839 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8841 indx_t ix = csrc->mc_ki[csrc->mc_top];
8842 nullkey.mv_size = 0;
8843 csrc->mc_ki[csrc->mc_top] = 0;
8844 rc = mdb_update_key(csrc, &nullkey);
8845 csrc->mc_ki[csrc->mc_top] = ix;
8846 mdb_cassert(csrc, rc == MDB_SUCCESS);
8850 if (cdst->mc_ki[cdst->mc_top] == 0) {
8851 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
8852 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8853 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
8855 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
8856 key.mv_size = NODEKSZ(srcnode);
8857 key.mv_data = NODEKEY(srcnode);
8859 DPRINTF(("update separator for destination page %"Yu" to [%s]",
8860 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
8861 mdb_cursor_copy(cdst, &mn);
8864 /* We want mdb_rebalance to find mn when doing fixups */
8865 WITH_CURSOR_TRACKING(mn,
8866 rc = mdb_update_key(&mn, &key));
8870 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
8872 indx_t ix = cdst->mc_ki[cdst->mc_top];
8873 nullkey.mv_size = 0;
8874 cdst->mc_ki[cdst->mc_top] = 0;
8875 rc = mdb_update_key(cdst, &nullkey);
8876 cdst->mc_ki[cdst->mc_top] = ix;
8877 mdb_cassert(cdst, rc == MDB_SUCCESS);
8884 /** Merge one page into another.
8885 * The nodes from the page pointed to by \b csrc will
8886 * be copied to the page pointed to by \b cdst and then
8887 * the \b csrc page will be freed.
8888 * @param[in] csrc Cursor pointing to the source page.
8889 * @param[in] cdst Cursor pointing to the destination page.
8890 * @return 0 on success, non-zero on failure.
8893 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
8895 MDB_page *psrc, *pdst;
8902 psrc = csrc->mc_pg[csrc->mc_top];
8903 pdst = cdst->mc_pg[cdst->mc_top];
8905 DPRINTF(("merging page %"Yu" into %"Yu, psrc->mp_pgno, pdst->mp_pgno));
8907 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
8908 mdb_cassert(csrc, cdst->mc_snum > 1);
8910 /* Mark dst as dirty. */
8911 if ((rc = mdb_page_touch(cdst)))
8914 /* get dst page again now that we've touched it. */
8915 pdst = cdst->mc_pg[cdst->mc_top];
8917 /* Move all nodes from src to dst.
8919 j = nkeys = NUMKEYS(pdst);
8920 if (IS_LEAF2(psrc)) {
8921 key.mv_size = csrc->mc_db->md_pad;
8922 key.mv_data = METADATA(psrc);
8923 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8924 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
8925 if (rc != MDB_SUCCESS)
8927 key.mv_data = (char *)key.mv_data + key.mv_size;
8930 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8931 srcnode = NODEPTR(psrc, i);
8932 if (i == 0 && IS_BRANCH(psrc)) {
8935 mdb_cursor_copy(csrc, &mn);
8936 mn.mc_xcursor = NULL;
8937 /* must find the lowest key below src */
8938 rc = mdb_page_search_lowest(&mn);
8941 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8942 key.mv_size = mn.mc_db->md_pad;
8943 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
8945 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8946 key.mv_size = NODEKSZ(s2);
8947 key.mv_data = NODEKEY(s2);
8950 key.mv_size = srcnode->mn_ksize;
8951 key.mv_data = NODEKEY(srcnode);
8954 data.mv_size = NODEDSZ(srcnode);
8955 data.mv_data = NODEDATA(srcnode);
8956 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
8957 if (rc != MDB_SUCCESS)
8962 DPRINTF(("dst page %"Yu" now has %u keys (%.1f%% filled)",
8963 pdst->mp_pgno, NUMKEYS(pdst),
8964 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
8966 /* Unlink the src page from parent and add to free list.
8969 mdb_node_del(csrc, 0);
8970 if (csrc->mc_ki[csrc->mc_top] == 0) {
8972 rc = mdb_update_key(csrc, &key);
8980 psrc = csrc->mc_pg[csrc->mc_top];
8981 /* If not operating on FreeDB, allow this page to be reused
8982 * in this txn. Otherwise just add to free list.
8984 rc = mdb_page_loose(csrc, psrc);
8988 csrc->mc_db->md_leaf_pages--;
8990 csrc->mc_db->md_branch_pages--;
8992 /* Adjust other cursors pointing to mp */
8993 MDB_cursor *m2, *m3;
8994 MDB_dbi dbi = csrc->mc_dbi;
8995 unsigned int top = csrc->mc_top;
8997 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8998 if (csrc->mc_flags & C_SUB)
8999 m3 = &m2->mc_xcursor->mx_cursor;
9002 if (m3 == csrc) continue;
9003 if (m3->mc_snum < csrc->mc_snum) continue;
9004 if (m3->mc_pg[top] == psrc) {
9005 m3->mc_pg[top] = pdst;
9006 m3->mc_ki[top] += nkeys;
9007 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
9008 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
9009 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
9013 XCURSOR_REFRESH(m3, top, m3->mc_pg[top]);
9017 unsigned int snum = cdst->mc_snum;
9018 uint16_t depth = cdst->mc_db->md_depth;
9019 mdb_cursor_pop(cdst);
9020 rc = mdb_rebalance(cdst);
9021 /* Did the tree height change? */
9022 if (depth != cdst->mc_db->md_depth)
9023 snum += cdst->mc_db->md_depth - depth;
9024 cdst->mc_snum = snum;
9025 cdst->mc_top = snum-1;
9030 /** Copy the contents of a cursor.
9031 * @param[in] csrc The cursor to copy from.
9032 * @param[out] cdst The cursor to copy to.
9035 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
9039 cdst->mc_txn = csrc->mc_txn;
9040 cdst->mc_dbi = csrc->mc_dbi;
9041 cdst->mc_db = csrc->mc_db;
9042 cdst->mc_dbx = csrc->mc_dbx;
9043 cdst->mc_snum = csrc->mc_snum;
9044 cdst->mc_top = csrc->mc_top;
9045 cdst->mc_flags = csrc->mc_flags;
9046 MC_SET_OVPG(cdst, MC_OVPG(csrc));
9048 for (i=0; i<csrc->mc_snum; i++) {
9049 cdst->mc_pg[i] = csrc->mc_pg[i];
9050 cdst->mc_ki[i] = csrc->mc_ki[i];
9054 /** Rebalance the tree after a delete operation.
9055 * @param[in] mc Cursor pointing to the page where rebalancing
9057 * @return 0 on success, non-zero on failure.
9060 mdb_rebalance(MDB_cursor *mc)
9064 unsigned int ptop, minkeys, thresh;
9068 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
9073 thresh = FILL_THRESHOLD;
9075 DPRINTF(("rebalancing %s page %"Yu" (has %u keys, %.1f%% full)",
9076 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
9077 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
9078 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
9080 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
9081 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
9082 DPRINTF(("no need to rebalance page %"Yu", above fill threshold",
9083 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
9087 if (mc->mc_snum < 2) {
9088 MDB_page *mp = mc->mc_pg[0];
9090 DPUTS("Can't rebalance a subpage, ignoring");
9093 if (NUMKEYS(mp) == 0) {
9094 DPUTS("tree is completely empty");
9095 mc->mc_db->md_root = P_INVALID;
9096 mc->mc_db->md_depth = 0;
9097 mc->mc_db->md_leaf_pages = 0;
9098 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
9101 /* Adjust cursors pointing to mp */
9104 mc->mc_flags &= ~C_INITIALIZED;
9106 MDB_cursor *m2, *m3;
9107 MDB_dbi dbi = mc->mc_dbi;
9109 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9110 if (mc->mc_flags & C_SUB)
9111 m3 = &m2->mc_xcursor->mx_cursor;
9114 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
9116 if (m3->mc_pg[0] == mp) {
9119 m3->mc_flags &= ~C_INITIALIZED;
9123 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
9125 DPUTS("collapsing root page!");
9126 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
9129 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
9130 rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
9133 mc->mc_db->md_depth--;
9134 mc->mc_db->md_branch_pages--;
9135 mc->mc_ki[0] = mc->mc_ki[1];
9136 for (i = 1; i<mc->mc_db->md_depth; i++) {
9137 mc->mc_pg[i] = mc->mc_pg[i+1];
9138 mc->mc_ki[i] = mc->mc_ki[i+1];
9141 /* Adjust other cursors pointing to mp */
9142 MDB_cursor *m2, *m3;
9143 MDB_dbi dbi = mc->mc_dbi;
9145 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9146 if (mc->mc_flags & C_SUB)
9147 m3 = &m2->mc_xcursor->mx_cursor;
9150 if (m3 == mc) continue;
9151 if (!(m3->mc_flags & C_INITIALIZED))
9153 if (m3->mc_pg[0] == mp) {
9154 for (i=0; i<mc->mc_db->md_depth; i++) {
9155 m3->mc_pg[i] = m3->mc_pg[i+1];
9156 m3->mc_ki[i] = m3->mc_ki[i+1];
9164 DPUTS("root page doesn't need rebalancing");
9168 /* The parent (branch page) must have at least 2 pointers,
9169 * otherwise the tree is invalid.
9171 ptop = mc->mc_top-1;
9172 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
9174 /* Leaf page fill factor is below the threshold.
9175 * Try to move keys from left or right neighbor, or
9176 * merge with a neighbor page.
9181 mdb_cursor_copy(mc, &mn);
9182 mn.mc_xcursor = NULL;
9184 oldki = mc->mc_ki[mc->mc_top];
9185 if (mc->mc_ki[ptop] == 0) {
9186 /* We're the leftmost leaf in our parent.
9188 DPUTS("reading right neighbor");
9190 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
9191 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
9194 mn.mc_ki[mn.mc_top] = 0;
9195 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
9198 /* There is at least one neighbor to the left.
9200 DPUTS("reading left neighbor");
9202 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
9203 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
9206 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
9207 mc->mc_ki[mc->mc_top] = 0;
9211 DPRINTF(("found neighbor page %"Yu" (%u keys, %.1f%% full)",
9212 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
9213 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
9215 /* If the neighbor page is above threshold and has enough keys,
9216 * move one key from it. Otherwise we should try to merge them.
9217 * (A branch page must never have less than 2 keys.)
9219 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
9220 rc = mdb_node_move(&mn, mc, fromleft);
9222 /* if we inserted on left, bump position up */
9227 rc = mdb_page_merge(&mn, mc);
9229 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
9230 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
9231 /* We want mdb_rebalance to find mn when doing fixups */
9232 WITH_CURSOR_TRACKING(mn,
9233 rc = mdb_page_merge(mc, &mn));
9234 mdb_cursor_copy(&mn, mc);
9236 mc->mc_flags &= ~C_EOF;
9238 mc->mc_ki[mc->mc_top] = oldki;
9242 /** Complete a delete operation started by #mdb_cursor_del(). */
9244 mdb_cursor_del0(MDB_cursor *mc)
9250 MDB_cursor *m2, *m3;
9251 MDB_dbi dbi = mc->mc_dbi;
9253 ki = mc->mc_ki[mc->mc_top];
9254 mp = mc->mc_pg[mc->mc_top];
9255 mdb_node_del(mc, mc->mc_db->md_pad);
9256 mc->mc_db->md_entries--;
9258 /* Adjust other cursors pointing to mp */
9259 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9260 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9261 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9263 if (m3 == mc || m3->mc_snum < mc->mc_snum)
9265 if (m3->mc_pg[mc->mc_top] == mp) {
9266 if (m3->mc_ki[mc->mc_top] == ki) {
9267 m3->mc_flags |= C_DEL;
9268 if (mc->mc_db->md_flags & MDB_DUPSORT) {
9269 /* Sub-cursor referred into dataset which is gone */
9270 m3->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
9273 } else if (m3->mc_ki[mc->mc_top] > ki) {
9274 m3->mc_ki[mc->mc_top]--;
9276 XCURSOR_REFRESH(m3, mc->mc_top, mp);
9280 rc = mdb_rebalance(mc);
9282 if (rc == MDB_SUCCESS) {
9283 /* DB is totally empty now, just bail out.
9284 * Other cursors adjustments were already done
9285 * by mdb_rebalance and aren't needed here.
9290 mp = mc->mc_pg[mc->mc_top];
9291 nkeys = NUMKEYS(mp);
9293 /* Adjust other cursors pointing to mp */
9294 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
9295 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9296 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9298 if (m3->mc_snum < mc->mc_snum)
9300 if (m3->mc_pg[mc->mc_top] == mp) {
9301 /* if m3 points past last node in page, find next sibling */
9302 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
9303 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9304 rc = mdb_cursor_sibling(m3, 1);
9305 if (rc == MDB_NOTFOUND) {
9306 m3->mc_flags |= C_EOF;
9311 if (mc->mc_db->md_flags & MDB_DUPSORT) {
9312 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
9313 /* If this node has dupdata, it may need to be reinited
9314 * because its data has moved.
9315 * If the xcursor was not initd it must be reinited.
9316 * Else if node points to a subDB, nothing is needed.
9317 * Else (xcursor was initd, not a subDB) needs mc_pg[0] reset.
9319 if (node->mn_flags & F_DUPDATA) {
9320 if (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
9321 if (!(node->mn_flags & F_SUBDATA))
9322 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
9324 mdb_xcursor_init1(m3, node);
9325 m3->mc_xcursor->mx_cursor.mc_flags |= C_DEL;
9332 mc->mc_flags |= C_DEL;
9336 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9341 mdb_del(MDB_txn *txn, MDB_dbi dbi,
9342 MDB_val *key, MDB_val *data)
9344 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9347 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9348 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9350 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
9351 /* must ignore any data */
9355 return mdb_del0(txn, dbi, key, data, 0);
9359 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
9360 MDB_val *key, MDB_val *data, unsigned flags)
9365 MDB_val rdata, *xdata;
9369 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
9371 mdb_cursor_init(&mc, txn, dbi, &mx);
9380 flags |= MDB_NODUPDATA;
9382 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
9384 /* let mdb_page_split know about this cursor if needed:
9385 * delete will trigger a rebalance; if it needs to move
9386 * a node from one page to another, it will have to
9387 * update the parent's separator key(s). If the new sepkey
9388 * is larger than the current one, the parent page may
9389 * run out of space, triggering a split. We need this
9390 * cursor to be consistent until the end of the rebalance.
9392 mc.mc_next = txn->mt_cursors[dbi];
9393 txn->mt_cursors[dbi] = &mc;
9394 rc = mdb_cursor_del(&mc, flags);
9395 txn->mt_cursors[dbi] = mc.mc_next;
9400 /** Split a page and insert a new node.
9401 * Set #MDB_TXN_ERROR on failure.
9402 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
9403 * The cursor will be updated to point to the actual page and index where
9404 * the node got inserted after the split.
9405 * @param[in] newkey The key for the newly inserted node.
9406 * @param[in] newdata The data for the newly inserted node.
9407 * @param[in] newpgno The page number, if the new node is a branch node.
9408 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
9409 * @return 0 on success, non-zero on failure.
9412 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
9413 unsigned int nflags)
9416 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
9419 int i, j, split_indx, nkeys, pmax;
9420 MDB_env *env = mc->mc_txn->mt_env;
9422 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
9423 MDB_page *copy = NULL;
9424 MDB_page *mp, *rp, *pp;
9429 mp = mc->mc_pg[mc->mc_top];
9430 newindx = mc->mc_ki[mc->mc_top];
9431 nkeys = NUMKEYS(mp);
9433 DPRINTF(("-----> splitting %s page %"Yu" and adding [%s] at index %i/%i",
9434 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
9435 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
9437 /* Create a right sibling. */
9438 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
9440 rp->mp_pad = mp->mp_pad;
9441 DPRINTF(("new right sibling: page %"Yu, rp->mp_pgno));
9443 /* Usually when splitting the root page, the cursor
9444 * height is 1. But when called from mdb_update_key,
9445 * the cursor height may be greater because it walks
9446 * up the stack while finding the branch slot to update.
9448 if (mc->mc_top < 1) {
9449 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
9451 /* shift current top to make room for new parent */
9452 for (i=mc->mc_snum; i>0; i--) {
9453 mc->mc_pg[i] = mc->mc_pg[i-1];
9454 mc->mc_ki[i] = mc->mc_ki[i-1];
9458 mc->mc_db->md_root = pp->mp_pgno;
9459 DPRINTF(("root split! new root = %"Yu, pp->mp_pgno));
9460 new_root = mc->mc_db->md_depth++;
9462 /* Add left (implicit) pointer. */
9463 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
9464 /* undo the pre-push */
9465 mc->mc_pg[0] = mc->mc_pg[1];
9466 mc->mc_ki[0] = mc->mc_ki[1];
9467 mc->mc_db->md_root = mp->mp_pgno;
9468 mc->mc_db->md_depth--;
9475 ptop = mc->mc_top-1;
9476 DPRINTF(("parent branch page is %"Yu, mc->mc_pg[ptop]->mp_pgno));
9479 mdb_cursor_copy(mc, &mn);
9480 mn.mc_xcursor = NULL;
9481 mn.mc_pg[mn.mc_top] = rp;
9482 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
9484 if (nflags & MDB_APPEND) {
9485 mn.mc_ki[mn.mc_top] = 0;
9487 split_indx = newindx;
9491 split_indx = (nkeys+1) / 2;
9496 unsigned int lsize, rsize, ksize;
9497 /* Move half of the keys to the right sibling */
9498 x = mc->mc_ki[mc->mc_top] - split_indx;
9499 ksize = mc->mc_db->md_pad;
9500 split = LEAF2KEY(mp, split_indx, ksize);
9501 rsize = (nkeys - split_indx) * ksize;
9502 lsize = (nkeys - split_indx) * sizeof(indx_t);
9503 mp->mp_lower -= lsize;
9504 rp->mp_lower += lsize;
9505 mp->mp_upper += rsize - lsize;
9506 rp->mp_upper -= rsize - lsize;
9507 sepkey.mv_size = ksize;
9508 if (newindx == split_indx) {
9509 sepkey.mv_data = newkey->mv_data;
9511 sepkey.mv_data = split;
9514 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
9515 memcpy(rp->mp_ptrs, split, rsize);
9516 sepkey.mv_data = rp->mp_ptrs;
9517 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
9518 memcpy(ins, newkey->mv_data, ksize);
9519 mp->mp_lower += sizeof(indx_t);
9520 mp->mp_upper -= ksize - sizeof(indx_t);
9523 memcpy(rp->mp_ptrs, split, x * ksize);
9524 ins = LEAF2KEY(rp, x, ksize);
9525 memcpy(ins, newkey->mv_data, ksize);
9526 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
9527 rp->mp_lower += sizeof(indx_t);
9528 rp->mp_upper -= ksize - sizeof(indx_t);
9529 mc->mc_ki[mc->mc_top] = x;
9532 int psize, nsize, k;
9533 /* Maximum free space in an empty page */
9534 pmax = env->me_psize - PAGEHDRSZ;
9536 nsize = mdb_leaf_size(env, newkey, newdata);
9538 nsize = mdb_branch_size(env, newkey);
9539 nsize = EVEN(nsize);
9541 /* grab a page to hold a temporary copy */
9542 copy = mdb_page_malloc(mc->mc_txn, 1);
9547 copy->mp_pgno = mp->mp_pgno;
9548 copy->mp_flags = mp->mp_flags;
9549 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
9550 copy->mp_upper = env->me_psize - PAGEBASE;
9552 /* prepare to insert */
9553 for (i=0, j=0; i<nkeys; i++) {
9555 copy->mp_ptrs[j++] = 0;
9557 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
9560 /* When items are relatively large the split point needs
9561 * to be checked, because being off-by-one will make the
9562 * difference between success or failure in mdb_node_add.
9564 * It's also relevant if a page happens to be laid out
9565 * such that one half of its nodes are all "small" and
9566 * the other half of its nodes are "large." If the new
9567 * item is also "large" and falls on the half with
9568 * "large" nodes, it also may not fit.
9570 * As a final tweak, if the new item goes on the last
9571 * spot on the page (and thus, onto the new page), bias
9572 * the split so the new page is emptier than the old page.
9573 * This yields better packing during sequential inserts.
9575 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
9576 /* Find split point */
9578 if (newindx <= split_indx || newindx >= nkeys) {
9580 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
9585 for (; i!=k; i+=j) {
9590 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9591 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
9593 if (F_ISSET(node->mn_flags, F_BIGDATA))
9594 psize += sizeof(pgno_t);
9596 psize += NODEDSZ(node);
9598 psize = EVEN(psize);
9600 if (psize > pmax || i == k-j) {
9601 split_indx = i + (j<0);
9606 if (split_indx == newindx) {
9607 sepkey.mv_size = newkey->mv_size;
9608 sepkey.mv_data = newkey->mv_data;
9610 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
9611 sepkey.mv_size = node->mn_ksize;
9612 sepkey.mv_data = NODEKEY(node);
9617 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
9619 /* Copy separator key to the parent.
9621 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
9622 int snum = mc->mc_snum;
9626 /* We want other splits to find mn when doing fixups */
9627 WITH_CURSOR_TRACKING(mn,
9628 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
9633 if (mc->mc_snum > snum) {
9636 /* Right page might now have changed parent.
9637 * Check if left page also changed parent.
9639 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9640 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9641 for (i=0; i<ptop; i++) {
9642 mc->mc_pg[i] = mn.mc_pg[i];
9643 mc->mc_ki[i] = mn.mc_ki[i];
9645 mc->mc_pg[ptop] = mn.mc_pg[ptop];
9646 if (mn.mc_ki[ptop]) {
9647 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
9649 /* find right page's left sibling */
9650 mc->mc_ki[ptop] = mn.mc_ki[ptop];
9651 rc = mdb_cursor_sibling(mc, 0);
9656 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
9659 if (rc != MDB_SUCCESS) {
9660 if (rc == MDB_NOTFOUND) /* improper mdb_cursor_sibling() result */
9664 if (nflags & MDB_APPEND) {
9665 mc->mc_pg[mc->mc_top] = rp;
9666 mc->mc_ki[mc->mc_top] = 0;
9667 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
9670 for (i=0; i<mc->mc_top; i++)
9671 mc->mc_ki[i] = mn.mc_ki[i];
9672 } else if (!IS_LEAF2(mp)) {
9674 mc->mc_pg[mc->mc_top] = rp;
9679 rkey.mv_data = newkey->mv_data;
9680 rkey.mv_size = newkey->mv_size;
9686 /* Update index for the new key. */
9687 mc->mc_ki[mc->mc_top] = j;
9689 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9690 rkey.mv_data = NODEKEY(node);
9691 rkey.mv_size = node->mn_ksize;
9693 xdata.mv_data = NODEDATA(node);
9694 xdata.mv_size = NODEDSZ(node);
9697 pgno = NODEPGNO(node);
9698 flags = node->mn_flags;
9701 if (!IS_LEAF(mp) && j == 0) {
9702 /* First branch index doesn't need key data. */
9706 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
9712 mc->mc_pg[mc->mc_top] = copy;
9717 } while (i != split_indx);
9719 nkeys = NUMKEYS(copy);
9720 for (i=0; i<nkeys; i++)
9721 mp->mp_ptrs[i] = copy->mp_ptrs[i];
9722 mp->mp_lower = copy->mp_lower;
9723 mp->mp_upper = copy->mp_upper;
9724 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
9725 env->me_psize - copy->mp_upper - PAGEBASE);
9727 /* reset back to original page */
9728 if (newindx < split_indx) {
9729 mc->mc_pg[mc->mc_top] = mp;
9731 mc->mc_pg[mc->mc_top] = rp;
9733 /* Make sure mc_ki is still valid.
9735 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9736 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9737 for (i=0; i<=ptop; i++) {
9738 mc->mc_pg[i] = mn.mc_pg[i];
9739 mc->mc_ki[i] = mn.mc_ki[i];
9743 if (nflags & MDB_RESERVE) {
9744 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
9745 if (!(node->mn_flags & F_BIGDATA))
9746 newdata->mv_data = NODEDATA(node);
9749 if (newindx >= split_indx) {
9750 mc->mc_pg[mc->mc_top] = rp;
9752 /* Make sure mc_ki is still valid.
9754 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9755 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9756 for (i=0; i<=ptop; i++) {
9757 mc->mc_pg[i] = mn.mc_pg[i];
9758 mc->mc_ki[i] = mn.mc_ki[i];
9765 /* Adjust other cursors pointing to mp */
9766 MDB_cursor *m2, *m3;
9767 MDB_dbi dbi = mc->mc_dbi;
9768 nkeys = NUMKEYS(mp);
9770 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9771 if (mc->mc_flags & C_SUB)
9772 m3 = &m2->mc_xcursor->mx_cursor;
9777 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9781 /* sub cursors may be on different DB */
9782 if (m3->mc_pg[0] != mp)
9785 for (k=new_root; k>=0; k--) {
9786 m3->mc_ki[k+1] = m3->mc_ki[k];
9787 m3->mc_pg[k+1] = m3->mc_pg[k];
9789 if (m3->mc_ki[0] >= nkeys) {
9794 m3->mc_pg[0] = mc->mc_pg[0];
9798 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
9799 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
9800 m3->mc_ki[mc->mc_top]++;
9801 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9802 m3->mc_pg[mc->mc_top] = rp;
9803 m3->mc_ki[mc->mc_top] -= nkeys;
9804 for (i=0; i<mc->mc_top; i++) {
9805 m3->mc_ki[i] = mn.mc_ki[i];
9806 m3->mc_pg[i] = mn.mc_pg[i];
9809 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
9810 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
9814 XCURSOR_REFRESH(m3, mc->mc_top, m3->mc_pg[mc->mc_top]);
9817 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
9820 if (copy) /* tmp page */
9821 mdb_page_free(env, copy);
9823 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9828 mdb_put(MDB_txn *txn, MDB_dbi dbi,
9829 MDB_val *key, MDB_val *data, unsigned int flags)
9835 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9838 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
9841 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9842 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9844 mdb_cursor_init(&mc, txn, dbi, &mx);
9845 mc.mc_next = txn->mt_cursors[dbi];
9846 txn->mt_cursors[dbi] = &mc;
9847 rc = mdb_cursor_put(&mc, key, data, flags);
9848 txn->mt_cursors[dbi] = mc.mc_next;
9853 #define MDB_WBUF (1024*1024)
9855 #define MDB_EOF 0x10 /**< #mdb_env_copyfd1() is done reading */
9857 /** State needed for a double-buffering compacting copy. */
9858 typedef struct mdb_copy {
9861 pthread_mutex_t mc_mutex;
9862 pthread_cond_t mc_cond; /**< Condition variable for #mc_new */
9867 pgno_t mc_next_pgno;
9869 int mc_toggle; /**< Buffer number in provider */
9870 int mc_new; /**< (0-2 buffers to write) | (#MDB_EOF at end) */
9871 /** Error code. Never cleared if set. Both threads can set nonzero
9872 * to fail the copy. Not mutex-protected, LMDB expects atomic int.
9874 volatile int mc_error;
9877 /** Dedicated writer thread for compacting copy. */
9878 static THREAD_RET ESECT CALL_CONV
9879 mdb_env_copythr(void *arg)
9883 int toggle = 0, wsize, rc;
9886 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9889 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9893 sigaddset(&set, SIGPIPE);
9894 if ((rc = pthread_sigmask(SIG_BLOCK, &set, NULL)) != 0)
9899 pthread_mutex_lock(&my->mc_mutex);
9902 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9903 if (my->mc_new == 0 + MDB_EOF) /* 0 buffers, just EOF */
9905 wsize = my->mc_wlen[toggle];
9906 ptr = my->mc_wbuf[toggle];
9909 while (wsize > 0 && !my->mc_error) {
9910 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
9913 #if defined(SIGPIPE) && !defined(_WIN32)
9915 /* Collect the pending SIGPIPE, otherwise at least OS X
9916 * gives it to the process on thread-exit (ITS#8504).
9919 sigwait(&set, &tmp);
9923 } else if (len > 0) {
9936 /* If there's an overflow page tail, write it too */
9937 if (my->mc_olen[toggle]) {
9938 wsize = my->mc_olen[toggle];
9939 ptr = my->mc_over[toggle];
9940 my->mc_olen[toggle] = 0;
9943 my->mc_wlen[toggle] = 0;
9945 /* Return the empty buffer to provider */
9947 pthread_cond_signal(&my->mc_cond);
9949 pthread_mutex_unlock(&my->mc_mutex);
9950 return (THREAD_RET)0;
9954 /** Give buffer and/or #MDB_EOF to writer thread, await unused buffer.
9956 * @param[in] my control structure.
9957 * @param[in] adjust (1 to hand off 1 buffer) | (MDB_EOF when ending).
9960 mdb_env_cthr_toggle(mdb_copy *my, int adjust)
9962 pthread_mutex_lock(&my->mc_mutex);
9963 my->mc_new += adjust;
9964 pthread_cond_signal(&my->mc_cond);
9965 while (my->mc_new & 2) /* both buffers in use */
9966 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9967 pthread_mutex_unlock(&my->mc_mutex);
9969 my->mc_toggle ^= (adjust & 1);
9970 /* Both threads reset mc_wlen, to be safe from threading errors */
9971 my->mc_wlen[my->mc_toggle] = 0;
9972 return my->mc_error;
9975 /** Depth-first tree traversal for compacting copy.
9976 * @param[in] my control structure.
9977 * @param[in,out] pg database root.
9978 * @param[in] flags includes #F_DUPDATA if it is a sorted-duplicate sub-DB.
9981 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
9983 MDB_cursor mc = {0};
9985 MDB_page *mo, *mp, *leaf;
9990 /* Empty DB, nothing to do */
9991 if (*pg == P_INVALID)
9995 mc.mc_txn = my->mc_txn;
9996 mc.mc_flags = my->mc_txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
9998 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
10001 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
10005 /* Make cursor pages writable */
10006 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
10010 for (i=0; i<mc.mc_top; i++) {
10011 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
10012 mc.mc_pg[i] = (MDB_page *)ptr;
10013 ptr += my->mc_env->me_psize;
10016 /* This is writable space for a leaf page. Usually not needed. */
10017 leaf = (MDB_page *)ptr;
10019 toggle = my->mc_toggle;
10020 while (mc.mc_snum > 0) {
10022 mp = mc.mc_pg[mc.mc_top];
10026 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
10027 for (i=0; i<n; i++) {
10028 ni = NODEPTR(mp, i);
10029 if (ni->mn_flags & F_BIGDATA) {
10033 /* Need writable leaf */
10035 mc.mc_pg[mc.mc_top] = leaf;
10036 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
10038 ni = NODEPTR(mp, i);
10041 memcpy(&pg, NODEDATA(ni), sizeof(pg));
10042 memcpy(NODEDATA(ni), &my->mc_next_pgno, sizeof(pgno_t));
10043 rc = mdb_page_get(&mc, pg, &omp, NULL);
10046 if (my->mc_wlen[toggle] >= MDB_WBUF) {
10047 rc = mdb_env_cthr_toggle(my, 1);
10050 toggle = my->mc_toggle;
10052 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
10053 memcpy(mo, omp, my->mc_env->me_psize);
10054 mo->mp_pgno = my->mc_next_pgno;
10055 my->mc_next_pgno += omp->mp_pages;
10056 my->mc_wlen[toggle] += my->mc_env->me_psize;
10057 if (omp->mp_pages > 1) {
10058 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
10059 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
10060 rc = mdb_env_cthr_toggle(my, 1);
10063 toggle = my->mc_toggle;
10065 } else if (ni->mn_flags & F_SUBDATA) {
10068 /* Need writable leaf */
10070 mc.mc_pg[mc.mc_top] = leaf;
10071 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
10073 ni = NODEPTR(mp, i);
10076 memcpy(&db, NODEDATA(ni), sizeof(db));
10077 my->mc_toggle = toggle;
10078 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
10081 toggle = my->mc_toggle;
10082 memcpy(NODEDATA(ni), &db, sizeof(db));
10087 mc.mc_ki[mc.mc_top]++;
10088 if (mc.mc_ki[mc.mc_top] < n) {
10091 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
10093 rc = mdb_page_get(&mc, pg, &mp, NULL);
10098 mc.mc_ki[mc.mc_top] = 0;
10099 if (IS_BRANCH(mp)) {
10100 /* Whenever we advance to a sibling branch page,
10101 * we must proceed all the way down to its first leaf.
10103 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
10106 mc.mc_pg[mc.mc_top] = mp;
10110 if (my->mc_wlen[toggle] >= MDB_WBUF) {
10111 rc = mdb_env_cthr_toggle(my, 1);
10114 toggle = my->mc_toggle;
10116 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
10117 mdb_page_copy(mo, mp, my->mc_env->me_psize);
10118 mo->mp_pgno = my->mc_next_pgno++;
10119 my->mc_wlen[toggle] += my->mc_env->me_psize;
10121 /* Update parent if there is one */
10122 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
10123 SETPGNO(ni, mo->mp_pgno);
10124 mdb_cursor_pop(&mc);
10126 /* Otherwise we're done */
10136 /** Copy environment with compaction. */
10138 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
10143 MDB_txn *txn = NULL;
10145 pgno_t root, new_root;
10146 int rc = MDB_SUCCESS;
10149 if (!(my.mc_mutex = CreateMutex(NULL, FALSE, NULL)) ||
10150 !(my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL))) {
10154 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
10155 if (my.mc_wbuf[0] == NULL) {
10156 /* _aligned_malloc() sets errno, but we use Windows error codes */
10157 rc = ERROR_NOT_ENOUGH_MEMORY;
10161 if ((rc = pthread_mutex_init(&my.mc_mutex, NULL)) != 0)
10163 if ((rc = pthread_cond_init(&my.mc_cond, NULL)) != 0)
10165 #ifdef HAVE_MEMALIGN
10166 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
10167 if (my.mc_wbuf[0] == NULL) {
10174 if ((rc = posix_memalign(&p, env->me_os_psize, MDB_WBUF*2)) != 0)
10180 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
10181 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
10182 my.mc_next_pgno = NUM_METAS;
10185 rc = THREAD_CREATE(thr, mdb_env_copythr, &my);
10189 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10193 mp = (MDB_page *)my.mc_wbuf[0];
10194 memset(mp, 0, NUM_METAS * env->me_psize);
10196 mp->mp_flags = P_META;
10197 mm = (MDB_meta *)METADATA(mp);
10198 mdb_env_init_meta0(env, mm);
10199 mm->mm_address = env->me_metas[0]->mm_address;
10201 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
10203 mp->mp_flags = P_META;
10204 *(MDB_meta *)METADATA(mp) = *mm;
10205 mm = (MDB_meta *)METADATA(mp);
10207 /* Set metapage 1 with current main DB */
10208 root = new_root = txn->mt_dbs[MAIN_DBI].md_root;
10209 if (root != P_INVALID) {
10210 /* Count free pages + freeDB pages. Subtract from last_pg
10211 * to find the new last_pg, which also becomes the new root.
10213 MDB_ID freecount = 0;
10216 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
10217 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
10218 freecount += *(MDB_ID *)data.mv_data;
10219 if (rc != MDB_NOTFOUND)
10221 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
10222 txn->mt_dbs[FREE_DBI].md_leaf_pages +
10223 txn->mt_dbs[FREE_DBI].md_overflow_pages;
10225 new_root = txn->mt_next_pgno - 1 - freecount;
10226 mm->mm_last_pg = new_root;
10227 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
10228 mm->mm_dbs[MAIN_DBI].md_root = new_root;
10230 /* When the DB is empty, handle it specially to
10231 * fix any breakage like page leaks from ITS#8174.
10233 mm->mm_dbs[MAIN_DBI].md_flags = txn->mt_dbs[MAIN_DBI].md_flags;
10235 if (root != P_INVALID || mm->mm_dbs[MAIN_DBI].md_flags) {
10236 mm->mm_txnid = 1; /* use metapage 1 */
10239 my.mc_wlen[0] = env->me_psize * NUM_METAS;
10241 rc = mdb_env_cwalk(&my, &root, 0);
10242 if (rc == MDB_SUCCESS && root != new_root) {
10243 rc = MDB_INCOMPATIBLE; /* page leak or corrupt DB */
10249 mdb_env_cthr_toggle(&my, 1 | MDB_EOF);
10250 rc = THREAD_FINISH(thr);
10251 mdb_txn_abort(txn);
10255 if (my.mc_wbuf[0]) _aligned_free(my.mc_wbuf[0]);
10256 if (my.mc_cond) CloseHandle(my.mc_cond);
10257 if (my.mc_mutex) CloseHandle(my.mc_mutex);
10259 free(my.mc_wbuf[0]);
10260 pthread_cond_destroy(&my.mc_cond);
10262 pthread_mutex_destroy(&my.mc_mutex);
10264 return rc ? rc : my.mc_error;
10267 /** Copy environment as-is. */
10269 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
10271 MDB_txn *txn = NULL;
10272 mdb_mutexref_t wmutex = NULL;
10274 mdb_size_t wsize, w3;
10278 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
10282 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
10285 /* Do the lock/unlock of the reader mutex before starting the
10286 * write txn. Otherwise other read txns could block writers.
10288 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10292 if (env->me_txns) {
10293 /* We must start the actual read txn after blocking writers */
10294 mdb_txn_end(txn, MDB_END_RESET_TMP);
10296 /* Temporarily block writers until we snapshot the meta pages */
10297 wmutex = env->me_wmutex;
10298 if (LOCK_MUTEX(rc, env, wmutex))
10301 rc = mdb_txn_renew0(txn);
10303 UNLOCK_MUTEX(wmutex);
10308 wsize = env->me_psize * NUM_METAS;
10312 DO_WRITE(rc, fd, ptr, w2, len);
10316 } else if (len > 0) {
10322 /* Non-blocking or async handles are not supported */
10328 UNLOCK_MUTEX(wmutex);
10333 w3 = txn->mt_next_pgno * env->me_psize;
10335 mdb_size_t fsize = 0;
10336 if ((rc = mdb_fsize(env->me_fd, &fsize)))
10341 wsize = w3 - wsize;
10342 while (wsize > 0) {
10343 if (wsize > MAX_WRITE)
10347 DO_WRITE(rc, fd, ptr, w2, len);
10351 } else if (len > 0) {
10363 mdb_txn_abort(txn);
10368 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
10370 if (flags & MDB_CP_COMPACT)
10371 return mdb_env_copyfd1(env, fd);
10373 return mdb_env_copyfd0(env, fd);
10377 mdb_env_copyfd(MDB_env *env, HANDLE fd)
10379 return mdb_env_copyfd2(env, fd, 0);
10383 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
10387 HANDLE newfd = INVALID_HANDLE_VALUE;
10389 rc = mdb_fname_init(path, env->me_flags | MDB_NOLOCK, &fname);
10390 if (rc == MDB_SUCCESS) {
10391 rc = mdb_fopen(env, &fname, MDB_O_COPY, 0666, &newfd);
10392 mdb_fname_destroy(fname);
10394 if (rc == MDB_SUCCESS) {
10395 rc = mdb_env_copyfd2(env, newfd, flags);
10396 if (close(newfd) < 0 && rc == MDB_SUCCESS)
10403 mdb_env_copy(MDB_env *env, const char *path)
10405 return mdb_env_copy2(env, path, 0);
10409 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
10411 if (flag & ~CHANGEABLE)
10414 env->me_flags |= flag;
10416 env->me_flags &= ~flag;
10417 return MDB_SUCCESS;
10421 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
10426 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
10427 return MDB_SUCCESS;
10431 mdb_env_set_userctx(MDB_env *env, void *ctx)
10435 env->me_userctx = ctx;
10436 return MDB_SUCCESS;
10440 mdb_env_get_userctx(MDB_env *env)
10442 return env ? env->me_userctx : NULL;
10446 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
10451 env->me_assert_func = func;
10453 return MDB_SUCCESS;
10457 mdb_env_get_path(MDB_env *env, const char **arg)
10462 *arg = env->me_path;
10463 return MDB_SUCCESS;
10467 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
10473 return MDB_SUCCESS;
10476 /** Common code for #mdb_stat() and #mdb_env_stat().
10477 * @param[in] env the environment to operate in.
10478 * @param[in] db the #MDB_db record containing the stats to return.
10479 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
10480 * @return 0, this function always succeeds.
10483 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
10485 arg->ms_psize = env->me_psize;
10486 arg->ms_depth = db->md_depth;
10487 arg->ms_branch_pages = db->md_branch_pages;
10488 arg->ms_leaf_pages = db->md_leaf_pages;
10489 arg->ms_overflow_pages = db->md_overflow_pages;
10490 arg->ms_entries = db->md_entries;
10492 return MDB_SUCCESS;
10496 mdb_env_stat(MDB_env *env, MDB_stat *arg)
10500 if (env == NULL || arg == NULL)
10503 meta = mdb_env_pick_meta(env);
10505 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
10509 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
10513 if (env == NULL || arg == NULL)
10516 meta = mdb_env_pick_meta(env);
10517 arg->me_mapaddr = meta->mm_address;
10518 arg->me_last_pgno = meta->mm_last_pg;
10519 arg->me_last_txnid = meta->mm_txnid;
10521 arg->me_mapsize = env->me_mapsize;
10522 arg->me_maxreaders = env->me_maxreaders;
10523 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
10524 return MDB_SUCCESS;
10527 /** Set the default comparison functions for a database.
10528 * Called immediately after a database is opened to set the defaults.
10529 * The user can then override them with #mdb_set_compare() or
10530 * #mdb_set_dupsort().
10531 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
10532 * @param[in] dbi A database handle returned by #mdb_dbi_open()
10535 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
10537 uint16_t f = txn->mt_dbs[dbi].md_flags;
10539 txn->mt_dbxs[dbi].md_cmp =
10540 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
10541 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
10543 txn->mt_dbxs[dbi].md_dcmp =
10544 !(f & MDB_DUPSORT) ? 0 :
10545 ((f & MDB_INTEGERDUP)
10546 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
10547 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
10550 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
10556 int rc, dbflag, exact;
10557 unsigned int unused = 0, seq;
10561 if (flags & ~VALID_FLAGS)
10563 if (txn->mt_flags & MDB_TXN_BLOCKED)
10564 return MDB_BAD_TXN;
10569 if (flags & PERSISTENT_FLAGS) {
10570 uint16_t f2 = flags & PERSISTENT_FLAGS;
10571 /* make sure flag changes get committed */
10572 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
10573 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
10574 txn->mt_flags |= MDB_TXN_DIRTY;
10577 mdb_default_cmp(txn, MAIN_DBI);
10578 return MDB_SUCCESS;
10581 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
10582 mdb_default_cmp(txn, MAIN_DBI);
10585 /* Is the DB already open? */
10586 len = strlen(name);
10587 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
10588 if (!txn->mt_dbxs[i].md_name.mv_size) {
10589 /* Remember this free slot */
10590 if (!unused) unused = i;
10593 if (len == txn->mt_dbxs[i].md_name.mv_size &&
10594 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
10596 return MDB_SUCCESS;
10600 /* If no free slot and max hit, fail */
10601 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
10602 return MDB_DBS_FULL;
10604 /* Cannot mix named databases with some mainDB flags */
10605 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
10606 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
10608 /* Find the DB info */
10609 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
10612 key.mv_data = (void *)name;
10613 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
10614 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
10615 if (rc == MDB_SUCCESS) {
10616 /* make sure this is actually a DB */
10617 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
10618 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
10619 return MDB_INCOMPATIBLE;
10620 } else if (! (rc == MDB_NOTFOUND && (flags & MDB_CREATE))) {
10624 /* Done here so we cannot fail after creating a new DB */
10625 if ((namedup = strdup(name)) == NULL)
10629 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
10630 data.mv_size = sizeof(MDB_db);
10631 data.mv_data = &dummy;
10632 memset(&dummy, 0, sizeof(dummy));
10633 dummy.md_root = P_INVALID;
10634 dummy.md_flags = flags & PERSISTENT_FLAGS;
10635 WITH_CURSOR_TRACKING(mc,
10636 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA));
10637 dbflag |= DB_DIRTY;
10643 /* Got info, register DBI in this txn */
10644 unsigned int slot = unused ? unused : txn->mt_numdbs;
10645 txn->mt_dbxs[slot].md_name.mv_data = namedup;
10646 txn->mt_dbxs[slot].md_name.mv_size = len;
10647 txn->mt_dbxs[slot].md_rel = NULL;
10648 txn->mt_dbflags[slot] = dbflag;
10649 /* txn-> and env-> are the same in read txns, use
10650 * tmp variable to avoid undefined assignment
10652 seq = ++txn->mt_env->me_dbiseqs[slot];
10653 txn->mt_dbiseqs[slot] = seq;
10655 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
10657 mdb_default_cmp(txn, slot);
10667 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
10669 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
10672 if (txn->mt_flags & MDB_TXN_BLOCKED)
10673 return MDB_BAD_TXN;
10675 if (txn->mt_dbflags[dbi] & DB_STALE) {
10678 /* Stale, must read the DB's root. cursor_init does it for us. */
10679 mdb_cursor_init(&mc, txn, dbi, &mx);
10681 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
10684 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
10687 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
10689 ptr = env->me_dbxs[dbi].md_name.mv_data;
10690 /* If there was no name, this was already closed */
10692 env->me_dbxs[dbi].md_name.mv_data = NULL;
10693 env->me_dbxs[dbi].md_name.mv_size = 0;
10694 env->me_dbflags[dbi] = 0;
10695 env->me_dbiseqs[dbi]++;
10700 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
10702 /* We could return the flags for the FREE_DBI too but what's the point? */
10703 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10705 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
10706 return MDB_SUCCESS;
10709 /** Add all the DB's pages to the free list.
10710 * @param[in] mc Cursor on the DB to free.
10711 * @param[in] subs non-Zero to check for sub-DBs in this DB.
10712 * @return 0 on success, non-zero on failure.
10715 mdb_drop0(MDB_cursor *mc, int subs)
10719 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
10720 if (rc == MDB_SUCCESS) {
10721 MDB_txn *txn = mc->mc_txn;
10726 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
10727 * This also avoids any P_LEAF2 pages, which have no nodes.
10728 * Also if the DB doesn't have sub-DBs and has no overflow
10729 * pages, omit scanning leaves.
10731 if ((mc->mc_flags & C_SUB) ||
10732 (!subs && !mc->mc_db->md_overflow_pages))
10733 mdb_cursor_pop(mc);
10735 mdb_cursor_copy(mc, &mx);
10737 /* bump refcount for mx's pages */
10738 for (i=0; i<mc->mc_snum; i++)
10739 mdb_page_get(&mx, mc->mc_pg[i]->mp_pgno, &mx.mc_pg[i], NULL);
10741 while (mc->mc_snum > 0) {
10742 MDB_page *mp = mc->mc_pg[mc->mc_top];
10743 unsigned n = NUMKEYS(mp);
10745 for (i=0; i<n; i++) {
10746 ni = NODEPTR(mp, i);
10747 if (ni->mn_flags & F_BIGDATA) {
10750 memcpy(&pg, NODEDATA(ni), sizeof(pg));
10751 rc = mdb_page_get(mc, pg, &omp, NULL);
10754 mdb_cassert(mc, IS_OVERFLOW(omp));
10755 rc = mdb_midl_append_range(&txn->mt_free_pgs,
10756 pg, omp->mp_pages);
10759 mc->mc_db->md_overflow_pages -= omp->mp_pages;
10760 if (!mc->mc_db->md_overflow_pages && !subs)
10762 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
10763 mdb_xcursor_init1(mc, ni);
10764 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
10769 if (!subs && !mc->mc_db->md_overflow_pages)
10772 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
10774 for (i=0; i<n; i++) {
10776 ni = NODEPTR(mp, i);
10779 mdb_midl_xappend(txn->mt_free_pgs, pg);
10784 mc->mc_ki[mc->mc_top] = i;
10785 rc = mdb_cursor_sibling(mc, 1);
10787 if (rc != MDB_NOTFOUND)
10789 /* no more siblings, go back to beginning
10790 * of previous level.
10793 mdb_cursor_pop(mc);
10795 for (i=1; i<mc->mc_snum; i++) {
10797 mc->mc_pg[i] = mx.mc_pg[i];
10802 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
10805 txn->mt_flags |= MDB_TXN_ERROR;
10806 /* drop refcount for mx's pages */
10807 MDB_CURSOR_UNREF(&mx, 0);
10808 } else if (rc == MDB_NOTFOUND) {
10811 mc->mc_flags &= ~C_INITIALIZED;
10815 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
10817 MDB_cursor *mc, *m2;
10820 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10823 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
10826 if (TXN_DBI_CHANGED(txn, dbi))
10827 return MDB_BAD_DBI;
10829 rc = mdb_cursor_open(txn, dbi, &mc);
10833 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
10834 /* Invalidate the dropped DB's cursors */
10835 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
10836 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
10840 /* Can't delete the main DB */
10841 if (del && dbi >= CORE_DBS) {
10842 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
10844 txn->mt_dbflags[dbi] = DB_STALE;
10845 mdb_dbi_close(txn->mt_env, dbi);
10847 txn->mt_flags |= MDB_TXN_ERROR;
10850 /* reset the DB record, mark it dirty */
10851 txn->mt_dbflags[dbi] |= DB_DIRTY;
10852 txn->mt_dbs[dbi].md_depth = 0;
10853 txn->mt_dbs[dbi].md_branch_pages = 0;
10854 txn->mt_dbs[dbi].md_leaf_pages = 0;
10855 txn->mt_dbs[dbi].md_overflow_pages = 0;
10856 txn->mt_dbs[dbi].md_entries = 0;
10857 txn->mt_dbs[dbi].md_root = P_INVALID;
10859 txn->mt_flags |= MDB_TXN_DIRTY;
10862 mdb_cursor_close(mc);
10866 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10868 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10871 txn->mt_dbxs[dbi].md_cmp = cmp;
10872 return MDB_SUCCESS;
10875 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10877 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10880 txn->mt_dbxs[dbi].md_dcmp = cmp;
10881 return MDB_SUCCESS;
10884 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
10886 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10889 txn->mt_dbxs[dbi].md_rel = rel;
10890 return MDB_SUCCESS;
10893 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
10895 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10898 txn->mt_dbxs[dbi].md_relctx = ctx;
10899 return MDB_SUCCESS;
10903 mdb_env_get_maxkeysize(MDB_env *env)
10905 return ENV_MAXKEY(env);
10909 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
10911 unsigned int i, rdrs;
10914 int rc = 0, first = 1;
10918 if (!env->me_txns) {
10919 return func("(no reader locks)\n", ctx);
10921 rdrs = env->me_txns->mti_numreaders;
10922 mr = env->me_txns->mti_readers;
10923 for (i=0; i<rdrs; i++) {
10924 if (mr[i].mr_pid) {
10925 txnid_t txnid = mr[i].mr_txnid;
10926 sprintf(buf, txnid == (txnid_t)-1 ?
10927 "%10d %"Z"x -\n" : "%10d %"Z"x %"Yu"\n",
10928 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
10931 rc = func(" pid thread txnid\n", ctx);
10935 rc = func(buf, ctx);
10941 rc = func("(no active readers)\n", ctx);
10946 /** Insert pid into list if not already present.
10947 * return -1 if already present.
10950 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
10952 /* binary search of pid in list */
10954 unsigned cursor = 1;
10956 unsigned n = ids[0];
10959 unsigned pivot = n >> 1;
10960 cursor = base + pivot + 1;
10961 val = pid - ids[cursor];
10966 } else if ( val > 0 ) {
10971 /* found, so it's a duplicate */
10980 for (n = ids[0]; n > cursor; n--)
10987 mdb_reader_check(MDB_env *env, int *dead)
10993 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
10996 /** As #mdb_reader_check(). \b rlocked is set if caller locked #me_rmutex. */
10998 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
11000 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
11001 unsigned int i, j, rdrs;
11003 MDB_PID_T *pids, pid;
11004 int rc = MDB_SUCCESS, count = 0;
11006 rdrs = env->me_txns->mti_numreaders;
11007 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
11011 mr = env->me_txns->mti_readers;
11012 for (i=0; i<rdrs; i++) {
11013 pid = mr[i].mr_pid;
11014 if (pid && pid != env->me_pid) {
11015 if (mdb_pid_insert(pids, pid) == 0) {
11016 if (!mdb_reader_pid(env, Pidcheck, pid)) {
11017 /* Stale reader found */
11020 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
11021 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
11023 rdrs = 0; /* the above checked all readers */
11025 /* Recheck, a new process may have reused pid */
11026 if (mdb_reader_pid(env, Pidcheck, pid))
11030 for (; j<rdrs; j++)
11031 if (mr[j].mr_pid == pid) {
11032 DPRINTF(("clear stale reader pid %u txn %"Yd,
11033 (unsigned) pid, mr[j].mr_txnid));
11038 UNLOCK_MUTEX(rmutex);
11049 #ifdef MDB_ROBUST_SUPPORTED
11050 /** Handle #LOCK_MUTEX0() failure.
11051 * Try to repair the lock file if the mutex owner died.
11052 * @param[in] env the environment handle
11053 * @param[in] mutex LOCK_MUTEX0() mutex
11054 * @param[in] rc LOCK_MUTEX0() error (nonzero)
11055 * @return 0 on success with the mutex locked, or an error code on failure.
11058 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
11063 if (rc == MDB_OWNERDEAD) {
11064 /* We own the mutex. Clean up after dead previous owner. */
11066 rlocked = (mutex == env->me_rmutex);
11068 /* Keep mti_txnid updated, otherwise next writer can
11069 * overwrite data which latest meta page refers to.
11071 meta = mdb_env_pick_meta(env);
11072 env->me_txns->mti_txnid = meta->mm_txnid;
11073 /* env is hosed if the dead thread was ours */
11075 env->me_flags |= MDB_FATAL_ERROR;
11076 env->me_txn = NULL;
11080 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
11081 (rc ? "this process' env is hosed" : "recovering")));
11082 rc2 = mdb_reader_check0(env, rlocked, NULL);
11084 rc2 = mdb_mutex_consistent(mutex);
11085 if (rc || (rc = rc2)) {
11086 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
11087 UNLOCK_MUTEX(mutex);
11093 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
11098 #endif /* MDB_ROBUST_SUPPORTED */
11100 #if defined(_WIN32)
11101 /** Convert \b src to new wchar_t[] string with room for \b xtra extra chars */
11103 utf8_to_utf16(const char *src, MDB_name *dst, int xtra)
11106 wchar_t *result = NULL;
11107 for (;;) { /* malloc result, then fill it in */
11108 need = MultiByteToWideChar(CP_UTF8, 0, src, -1, result, need);
11115 result = malloc(sizeof(wchar_t) * (need + xtra));
11120 dst->mn_alloced = 1;
11121 dst->mn_len = need - 1;
11122 dst->mn_val = result;
11123 return MDB_SUCCESS;
11126 #endif /* defined(_WIN32) */