2 * @brief Lightning memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2017 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
38 #if defined(MDB_VL32) || defined(__WIN64__)
39 #define _FILE_OFFSET_BITS 64
44 #include <wchar.h> /* get wcscpy() */
46 /* We use native NT APIs to setup the memory map, so that we can
47 * let the DB file grow incrementally instead of always preallocating
48 * the full size. These APIs are defined in <wdm.h> and <ntifs.h>
49 * but those headers are meant for driver-level development and
50 * conflict with the regular user-level headers, so we explicitly
51 * declare them here. Using these APIs also means we must link to
52 * ntdll.dll, which is not linked by default in user code.
55 NtCreateSection(OUT PHANDLE sh, IN ACCESS_MASK acc,
56 IN void * oa OPTIONAL,
57 IN PLARGE_INTEGER ms OPTIONAL,
58 IN ULONG pp, IN ULONG aa, IN HANDLE fh OPTIONAL);
60 typedef enum _SECTION_INHERIT {
66 NtMapViewOfSection(IN PHANDLE sh, IN HANDLE ph,
67 IN OUT PVOID *addr, IN ULONG_PTR zbits,
68 IN SIZE_T cs, IN OUT PLARGE_INTEGER off OPTIONAL,
69 IN OUT PSIZE_T vs, IN SECTION_INHERIT ih,
70 IN ULONG at, IN ULONG pp);
75 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
76 * as int64 which is wrong. MSVC doesn't define it at all, so just
80 #define MDB_THR_T DWORD
81 #include <sys/types.h>
84 # include <sys/param.h>
86 # define LITTLE_ENDIAN 1234
87 # define BIG_ENDIAN 4321
88 # define BYTE_ORDER LITTLE_ENDIAN
90 # define SSIZE_MAX INT_MAX
94 #include <sys/types.h>
96 #define MDB_PID_T pid_t
97 #define MDB_THR_T pthread_t
98 #include <sys/param.h>
100 #include <sys/mman.h>
101 #ifdef HAVE_SYS_FILE_H
102 #include <sys/file.h>
107 #if defined(__mips) && defined(__linux)
108 /* MIPS has cache coherency issues, requires explicit cache control */
109 #include <asm/cachectl.h>
110 extern int cacheflush(char *addr, int nbytes, int cache);
111 #define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
113 #define CACHEFLUSH(addr, bytes, cache)
116 #if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
117 /** fdatasync is broken on ext3/ext4fs on older kernels, see
118 * description in #mdb_env_open2 comments. You can safely
119 * define MDB_FDATASYNC_WORKS if this code will only be run
120 * on kernels 3.6 and newer.
122 #define BROKEN_FDATASYNC
128 #include <inttypes.h>
136 typedef SSIZE_T ssize_t;
141 #if defined(__sun) || defined(ANDROID)
142 /* Most platforms have posix_memalign, older may only have memalign */
143 #define HAVE_MEMALIGN 1
147 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
148 #include <netinet/in.h>
149 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
152 #if defined(__APPLE__) || defined (BSD) || defined(__FreeBSD_kernel__)
153 # if !(defined(MDB_USE_POSIX_MUTEX) || defined(MDB_USE_POSIX_SEM))
154 # define MDB_USE_SYSV_SEM 1
156 # define MDB_FDATASYNC fsync
157 #elif defined(ANDROID)
158 # define MDB_FDATASYNC fsync
164 #ifdef MDB_USE_POSIX_SEM
165 # define MDB_USE_HASH 1
166 #include <semaphore.h>
167 #elif defined(MDB_USE_SYSV_SEM)
170 #ifdef _SEM_SEMUN_UNDEFINED
173 struct semid_ds *buf;
174 unsigned short *array;
176 #endif /* _SEM_SEMUN_UNDEFINED */
178 #define MDB_USE_POSIX_MUTEX 1
179 #endif /* MDB_USE_POSIX_SEM */
182 #if defined(_WIN32) + defined(MDB_USE_POSIX_SEM) + defined(MDB_USE_SYSV_SEM) \
183 + defined(MDB_USE_POSIX_MUTEX) != 1
184 # error "Ambiguous shared-lock implementation"
188 #include <valgrind/memcheck.h>
189 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
190 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
191 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
192 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
193 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
195 #define VGMEMP_CREATE(h,r,z)
196 #define VGMEMP_ALLOC(h,a,s)
197 #define VGMEMP_FREE(h,a)
198 #define VGMEMP_DESTROY(h)
199 #define VGMEMP_DEFINED(a,s)
203 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
204 /* Solaris just defines one or the other */
205 # define LITTLE_ENDIAN 1234
206 # define BIG_ENDIAN 4321
207 # ifdef _LITTLE_ENDIAN
208 # define BYTE_ORDER LITTLE_ENDIAN
210 # define BYTE_ORDER BIG_ENDIAN
213 # define BYTE_ORDER __BYTE_ORDER
217 #ifndef LITTLE_ENDIAN
218 #define LITTLE_ENDIAN __LITTLE_ENDIAN
221 #define BIG_ENDIAN __BIG_ENDIAN
224 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
225 #define MISALIGNED_OK 1
231 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
232 # error "Unknown or unsupported endianness (BYTE_ORDER)"
233 #elif (-6 & 5) || CHAR_BIT!=8 || UINT_MAX!=0xffffffff || MDB_SIZE_MAX%UINT_MAX
234 # error "Two's complement, reasonably sized integer types, please"
238 /** Put infrequently used env functions in separate section */
240 # define ESECT __attribute__ ((section("__TEXT,text_env")))
242 # define ESECT __attribute__ ((section("text_env")))
249 #define CALL_CONV WINAPI
254 /** @defgroup internal LMDB Internals
257 /** @defgroup compat Compatibility Macros
258 * A bunch of macros to minimize the amount of platform-specific ifdefs
259 * needed throughout the rest of the code. When the features this library
260 * needs are similar enough to POSIX to be hidden in a one-or-two line
261 * replacement, this macro approach is used.
265 /** Features under development */
270 /** Wrapper around __func__, which is a C99 feature */
271 #if __STDC_VERSION__ >= 199901L
272 # define mdb_func_ __func__
273 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
274 # define mdb_func_ __FUNCTION__
276 /* If a debug message says <mdb_unknown>(), update the #if statements above */
277 # define mdb_func_ "<mdb_unknown>"
280 /* Internal error codes, not exposed outside liblmdb */
281 #define MDB_NO_ROOT (MDB_LAST_ERRCODE + 10)
283 #define MDB_OWNERDEAD ((int) WAIT_ABANDONED)
284 #elif defined MDB_USE_SYSV_SEM
285 #define MDB_OWNERDEAD (MDB_LAST_ERRCODE + 11)
286 #elif defined(MDB_USE_POSIX_MUTEX) && defined(EOWNERDEAD)
287 #define MDB_OWNERDEAD EOWNERDEAD /**< #LOCK_MUTEX0() result if dead owner */
291 #define GLIBC_VER ((__GLIBC__ << 16 )| __GLIBC_MINOR__)
293 /** Some platforms define the EOWNERDEAD error code
294 * even though they don't support Robust Mutexes.
295 * Compile with -DMDB_USE_ROBUST=0, or use some other
296 * mechanism like -DMDB_USE_SYSV_SEM instead of
297 * -DMDB_USE_POSIX_MUTEX. (SysV semaphores are
298 * also Robust, but some systems don't support them
301 #ifndef MDB_USE_ROBUST
302 /* Android currently lacks Robust Mutex support. So does glibc < 2.4. */
303 # if defined(MDB_USE_POSIX_MUTEX) && (defined(ANDROID) || \
304 (defined(__GLIBC__) && GLIBC_VER < 0x020004))
305 # define MDB_USE_ROBUST 0
307 # define MDB_USE_ROBUST 1
309 #endif /* !MDB_USE_ROBUST */
311 #if defined(MDB_USE_POSIX_MUTEX) && (MDB_USE_ROBUST)
312 /* glibc < 2.12 only provided _np API */
313 # if (defined(__GLIBC__) && GLIBC_VER < 0x02000c) || \
314 (defined(PTHREAD_MUTEX_ROBUST_NP) && !defined(PTHREAD_MUTEX_ROBUST))
315 # define PTHREAD_MUTEX_ROBUST PTHREAD_MUTEX_ROBUST_NP
316 # define pthread_mutexattr_setrobust(attr, flag) pthread_mutexattr_setrobust_np(attr, flag)
317 # define pthread_mutex_consistent(mutex) pthread_mutex_consistent_np(mutex)
319 #endif /* MDB_USE_POSIX_MUTEX && MDB_USE_ROBUST */
321 #if defined(MDB_OWNERDEAD) && (MDB_USE_ROBUST)
322 #define MDB_ROBUST_SUPPORTED 1
326 #define MDB_USE_HASH 1
327 #define MDB_PIDLOCK 0
328 #define THREAD_RET DWORD
329 #define pthread_t HANDLE
330 #define pthread_mutex_t HANDLE
331 #define pthread_cond_t HANDLE
332 typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
333 #define pthread_key_t DWORD
334 #define pthread_self() GetCurrentThreadId()
335 #define pthread_key_create(x,y) \
336 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
337 #define pthread_key_delete(x) TlsFree(x)
338 #define pthread_getspecific(x) TlsGetValue(x)
339 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
340 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
341 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
342 #define pthread_cond_signal(x) SetEvent(*x)
343 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
344 #define THREAD_CREATE(thr,start,arg) \
345 (((thr) = CreateThread(NULL, 0, start, arg, 0, NULL)) ? 0 : ErrCode())
346 #define THREAD_FINISH(thr) \
347 (WaitForSingleObject(thr, INFINITE) ? ErrCode() : 0)
348 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
349 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
350 #define mdb_mutex_consistent(mutex) 0
351 #define getpid() GetCurrentProcessId()
352 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
353 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
354 #define ErrCode() GetLastError()
355 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
356 #define close(fd) (CloseHandle(fd) ? 0 : -1)
357 #define munmap(ptr,len) UnmapViewOfFile(ptr)
358 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
359 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
361 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
364 #define THREAD_RET void *
365 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
366 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
368 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
369 #define MDB_PIDLOCK 1
371 #ifdef MDB_USE_POSIX_SEM
373 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
374 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
375 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
378 mdb_sem_wait(sem_t *sem)
381 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
385 #elif defined MDB_USE_SYSV_SEM
387 typedef struct mdb_mutex {
391 } mdb_mutex_t[1], *mdb_mutexref_t;
393 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
394 #define UNLOCK_MUTEX(mutex) do { \
395 struct sembuf sb = { 0, 1, SEM_UNDO }; \
396 sb.sem_num = (mutex)->semnum; \
397 *(mutex)->locked = 0; \
398 semop((mutex)->semid, &sb, 1); \
402 mdb_sem_wait(mdb_mutexref_t sem)
404 int rc, *locked = sem->locked;
405 struct sembuf sb = { 0, -1, SEM_UNDO };
406 sb.sem_num = sem->semnum;
408 if (!semop(sem->semid, &sb, 1)) {
409 rc = *locked ? MDB_OWNERDEAD : MDB_SUCCESS;
413 } while ((rc = errno) == EINTR);
417 #define mdb_mutex_consistent(mutex) 0
419 #else /* MDB_USE_POSIX_MUTEX: */
420 /** Shared mutex/semaphore as the original is stored.
422 * Not for copies. Instead it can be assigned to an #mdb_mutexref_t.
423 * When mdb_mutexref_t is a pointer and mdb_mutex_t is not, then it
424 * is array[size 1] so it can be assigned to the pointer.
426 typedef pthread_mutex_t mdb_mutex_t[1];
427 /** Reference to an #mdb_mutex_t */
428 typedef pthread_mutex_t *mdb_mutexref_t;
429 /** Lock the reader or writer mutex.
430 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
432 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
433 /** Unlock the reader or writer mutex.
435 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
436 /** Mark mutex-protected data as repaired, after death of previous owner.
438 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
439 #endif /* MDB_USE_POSIX_SEM || MDB_USE_SYSV_SEM */
441 /** Get the error code for the last failed system function.
443 #define ErrCode() errno
445 /** An abstraction for a file handle.
446 * On POSIX systems file handles are small integers. On Windows
447 * they're opaque pointers.
451 /** A value for an invalid file handle.
452 * Mainly used to initialize file variables and signify that they are
455 #define INVALID_HANDLE_VALUE (-1)
457 /** Get the size of a memory page for the system.
458 * This is the basic size that the platform's memory manager uses, and is
459 * fundamental to the use of memory-mapped files.
461 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
464 #define Z MDB_FMT_Z /**< printf/scanf format modifier for size_t */
465 #define Yu MDB_PRIy(u) /**< printf format for #mdb_size_t */
466 #define Yd MDB_PRIy(d) /**< printf format for 'signed #mdb_size_t' */
468 #ifdef MDB_USE_SYSV_SEM
469 #define MNAME_LEN (sizeof(int))
471 #define MNAME_LEN (sizeof(pthread_mutex_t))
474 /** Initial part of #MDB_env.me_mutexname[].
475 * Changes to this code must be reflected in #MDB_LOCK_FORMAT.
478 #define MUTEXNAME_PREFIX "Global\\MDB"
479 #elif defined MDB_USE_POSIX_SEM
480 #define MUTEXNAME_PREFIX "/MDB"
483 #ifdef MDB_USE_SYSV_SEM
484 #define SYSV_SEM_FLAG 1 /**< SysV sems in lockfile format */
486 #define SYSV_SEM_FLAG 0
491 #ifdef MDB_ROBUST_SUPPORTED
492 /** Lock mutex, handle any error, set rc = result.
493 * Return 0 on success, nonzero (not rc) on error.
495 #define LOCK_MUTEX(rc, env, mutex) \
496 (((rc) = LOCK_MUTEX0(mutex)) && \
497 ((rc) = mdb_mutex_failed(env, mutex, rc)))
498 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
500 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
501 #define mdb_mutex_failed(env, mutex, rc) (rc)
505 /** A flag for opening a file and requesting synchronous data writes.
506 * This is only used when writing a meta page. It's not strictly needed;
507 * we could just do a normal write and then immediately perform a flush.
508 * But if this flag is available it saves us an extra system call.
510 * @note If O_DSYNC is undefined but exists in /usr/include,
511 * preferably set some compiler flag to get the definition.
515 # define MDB_DSYNC O_DSYNC
517 # define MDB_DSYNC O_SYNC
522 /** Function for flushing the data of a file. Define this to fsync
523 * if fdatasync() is not supported.
525 #ifndef MDB_FDATASYNC
526 # define MDB_FDATASYNC fdatasync
530 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
541 /** A page number in the database.
542 * Note that 64 bit page numbers are overkill, since pages themselves
543 * already represent 12-13 bits of addressable memory, and the OS will
544 * always limit applications to a maximum of 63 bits of address space.
546 * @note In the #MDB_node structure, we only store 48 bits of this value,
547 * which thus limits us to only 60 bits of addressable data.
549 typedef MDB_ID pgno_t;
551 /** A transaction ID.
552 * See struct MDB_txn.mt_txnid for details.
554 typedef MDB_ID txnid_t;
556 /** @defgroup debug Debug Macros
560 /** Enable debug output. Needs variable argument macros (a C99 feature).
561 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
562 * read from and written to the database (used for free space management).
568 static int mdb_debug;
569 static txnid_t mdb_debug_start;
571 /** Print a debug message with printf formatting.
572 * Requires double parenthesis around 2 or more args.
574 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
575 # define DPRINTF0(fmt, ...) \
576 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
578 # define DPRINTF(args) ((void) 0)
580 /** Print a debug string.
581 * The string is printed literally, with no format processing.
583 #define DPUTS(arg) DPRINTF(("%s", arg))
584 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
586 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
589 /** @brief The maximum size of a database page.
591 * It is 32k or 64k, since value-PAGEBASE must fit in
592 * #MDB_page.%mp_upper.
594 * LMDB will use database pages < OS pages if needed.
595 * That causes more I/O in write transactions: The OS must
596 * know (read) the whole page before writing a partial page.
598 * Note that we don't currently support Huge pages. On Linux,
599 * regular data files cannot use Huge pages, and in general
600 * Huge pages aren't actually pageable. We rely on the OS
601 * demand-pager to read our data and page it out when memory
602 * pressure from other processes is high. So until OSs have
603 * actual paging support for Huge pages, they're not viable.
605 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
607 /** The minimum number of keys required in a database page.
608 * Setting this to a larger value will place a smaller bound on the
609 * maximum size of a data item. Data items larger than this size will
610 * be pushed into overflow pages instead of being stored directly in
611 * the B-tree node. This value used to default to 4. With a page size
612 * of 4096 bytes that meant that any item larger than 1024 bytes would
613 * go into an overflow page. That also meant that on average 2-3KB of
614 * each overflow page was wasted space. The value cannot be lower than
615 * 2 because then there would no longer be a tree structure. With this
616 * value, items larger than 2KB will go into overflow pages, and on
617 * average only 1KB will be wasted.
619 #define MDB_MINKEYS 2
621 /** A stamp that identifies a file as an LMDB file.
622 * There's nothing special about this value other than that it is easily
623 * recognizable, and it will reflect any byte order mismatches.
625 #define MDB_MAGIC 0xBEEFC0DE
627 /** The version number for a database's datafile format. */
628 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
629 /** The version number for a database's lockfile format. */
630 #define MDB_LOCK_VERSION ((MDB_DEVEL) ? 999 : 2)
632 /** @brief The max size of a key we can write, or 0 for computed max.
634 * This macro should normally be left alone or set to 0.
635 * Note that a database with big keys or dupsort data cannot be
636 * reliably modified by a liblmdb which uses a smaller max.
637 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
639 * Other values are allowed, for backwards compat. However:
640 * A value bigger than the computed max can break if you do not
641 * know what you are doing, and liblmdb <= 0.9.10 can break when
642 * modifying a DB with keys/dupsort data bigger than its max.
644 * Data items in an #MDB_DUPSORT database are also limited to
645 * this size, since they're actually keys of a sub-DB. Keys and
646 * #MDB_DUPSORT data items must fit on a node in a regular page.
648 #ifndef MDB_MAXKEYSIZE
649 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
652 /** The maximum size of a key we can write to the environment. */
654 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
656 #define ENV_MAXKEY(env) ((env)->me_maxkey)
659 /** @brief The maximum size of a data item.
661 * We only store a 32 bit value for node sizes.
663 #define MAXDATASIZE 0xffffffffUL
666 /** Key size which fits in a #DKBUF.
669 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
672 * This is used for printing a hex dump of a key's contents.
674 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
675 /** Display a key in hex.
677 * Invoke a function to display a key in hex.
679 #define DKEY(x) mdb_dkey(x, kbuf)
685 /** An invalid page number.
686 * Mainly used to denote an empty tree.
688 #define P_INVALID (~(pgno_t)0)
690 /** Test if the flags \b f are set in a flag word \b w. */
691 #define F_ISSET(w, f) (((w) & (f)) == (f))
693 /** Round \b n up to an even number. */
694 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
696 /** Used for offsets within a single page.
697 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
700 typedef uint16_t indx_t;
702 typedef unsigned long long mdb_hash_t;
704 /** Default size of memory map.
705 * This is certainly too small for any actual applications. Apps should always set
706 * the size explicitly using #mdb_env_set_mapsize().
708 #define DEFAULT_MAPSIZE 1048576
710 /** @defgroup readers Reader Lock Table
711 * Readers don't acquire any locks for their data access. Instead, they
712 * simply record their transaction ID in the reader table. The reader
713 * mutex is needed just to find an empty slot in the reader table. The
714 * slot's address is saved in thread-specific data so that subsequent read
715 * transactions started by the same thread need no further locking to proceed.
717 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
719 * No reader table is used if the database is on a read-only filesystem, or
720 * if #MDB_NOLOCK is set.
722 * Since the database uses multi-version concurrency control, readers don't
723 * actually need any locking. This table is used to keep track of which
724 * readers are using data from which old transactions, so that we'll know
725 * when a particular old transaction is no longer in use. Old transactions
726 * that have discarded any data pages can then have those pages reclaimed
727 * for use by a later write transaction.
729 * The lock table is constructed such that reader slots are aligned with the
730 * processor's cache line size. Any slot is only ever used by one thread.
731 * This alignment guarantees that there will be no contention or cache
732 * thrashing as threads update their own slot info, and also eliminates
733 * any need for locking when accessing a slot.
735 * A writer thread will scan every slot in the table to determine the oldest
736 * outstanding reader transaction. Any freed pages older than this will be
737 * reclaimed by the writer. The writer doesn't use any locks when scanning
738 * this table. This means that there's no guarantee that the writer will
739 * see the most up-to-date reader info, but that's not required for correct
740 * operation - all we need is to know the upper bound on the oldest reader,
741 * we don't care at all about the newest reader. So the only consequence of
742 * reading stale information here is that old pages might hang around a
743 * while longer before being reclaimed. That's actually good anyway, because
744 * the longer we delay reclaiming old pages, the more likely it is that a
745 * string of contiguous pages can be found after coalescing old pages from
746 * many old transactions together.
749 /** Number of slots in the reader table.
750 * This value was chosen somewhat arbitrarily. 126 readers plus a
751 * couple mutexes fit exactly into 8KB on my development machine.
752 * Applications should set the table size using #mdb_env_set_maxreaders().
754 #define DEFAULT_READERS 126
756 /** The size of a CPU cache line in bytes. We want our lock structures
757 * aligned to this size to avoid false cache line sharing in the
759 * This value works for most CPUs. For Itanium this should be 128.
765 /** The information we store in a single slot of the reader table.
766 * In addition to a transaction ID, we also record the process and
767 * thread ID that owns a slot, so that we can detect stale information,
768 * e.g. threads or processes that went away without cleaning up.
769 * @note We currently don't check for stale records. We simply re-init
770 * the table when we know that we're the only process opening the
773 typedef struct MDB_rxbody {
774 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
775 * Multiple readers that start at the same time will probably have the
776 * same ID here. Again, it's not important to exclude them from
777 * anything; all we need to know is which version of the DB they
778 * started from so we can avoid overwriting any data used in that
779 * particular version.
781 volatile txnid_t mrb_txnid;
782 /** The process ID of the process owning this reader txn. */
783 volatile MDB_PID_T mrb_pid;
784 /** The thread ID of the thread owning this txn. */
785 volatile MDB_THR_T mrb_tid;
788 /** The actual reader record, with cacheline padding. */
789 typedef struct MDB_reader {
792 /** shorthand for mrb_txnid */
793 #define mr_txnid mru.mrx.mrb_txnid
794 #define mr_pid mru.mrx.mrb_pid
795 #define mr_tid mru.mrx.mrb_tid
796 /** cache line alignment */
797 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
801 /** The header for the reader table.
802 * The table resides in a memory-mapped file. (This is a different file
803 * than is used for the main database.)
805 * For POSIX the actual mutexes reside in the shared memory of this
806 * mapped file. On Windows, mutexes are named objects allocated by the
807 * kernel; we store the mutex names in this mapped file so that other
808 * processes can grab them. This same approach is also used on
809 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
810 * process-shared POSIX mutexes. For these cases where a named object
811 * is used, the object name is derived from a 64 bit FNV hash of the
812 * environment pathname. As such, naming collisions are extremely
813 * unlikely. If a collision occurs, the results are unpredictable.
815 typedef struct MDB_txbody {
816 /** Stamp identifying this as an LMDB file. It must be set
819 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
821 /** The ID of the last transaction committed to the database.
822 * This is recorded here only for convenience; the value can always
823 * be determined by reading the main database meta pages.
825 volatile txnid_t mtb_txnid;
826 /** The number of slots that have been used in the reader table.
827 * This always records the maximum count, it is not decremented
828 * when readers release their slots.
830 volatile unsigned mtb_numreaders;
831 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
832 /** Binary form of names of the reader/writer locks */
833 mdb_hash_t mtb_mutexid;
834 #elif defined(MDB_USE_SYSV_SEM)
838 /** Mutex protecting access to this table.
839 * This is the reader table lock used with LOCK_MUTEX().
841 mdb_mutex_t mtb_rmutex;
845 /** The actual reader table definition. */
846 typedef struct MDB_txninfo {
849 #define mti_magic mt1.mtb.mtb_magic
850 #define mti_format mt1.mtb.mtb_format
851 #define mti_rmutex mt1.mtb.mtb_rmutex
852 #define mti_rmname mt1.mtb.mtb_rmname
853 #define mti_txnid mt1.mtb.mtb_txnid
854 #define mti_numreaders mt1.mtb.mtb_numreaders
855 #define mti_mutexid mt1.mtb.mtb_mutexid
856 #ifdef MDB_USE_SYSV_SEM
857 #define mti_semid mt1.mtb.mtb_semid
858 #define mti_rlocked mt1.mtb.mtb_rlocked
860 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
862 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM))
864 #ifdef MDB_USE_SYSV_SEM
866 #define mti_wlocked mt2.mt2_wlocked
868 mdb_mutex_t mt2_wmutex;
869 #define mti_wmutex mt2.mt2_wmutex
871 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
874 MDB_reader mti_readers[1];
877 /** Lockfile format signature: version, features and field layout */
878 #define MDB_LOCK_FORMAT \
880 ((MDB_LOCK_VERSION) \
881 /* Flags which describe functionality */ \
882 + (SYSV_SEM_FLAG << 18) \
883 + (((MDB_PIDLOCK) != 0) << 16)))
886 /** Common header for all page types. The page type depends on #mp_flags.
888 * #P_BRANCH and #P_LEAF pages have unsorted '#MDB_node's at the end, with
889 * sorted #mp_ptrs[] entries referring to them. Exception: #P_LEAF2 pages
890 * omit mp_ptrs and pack sorted #MDB_DUPFIXED values after the page header.
892 * #P_OVERFLOW records occupy one or more contiguous pages where only the
893 * first has a page header. They hold the real data of #F_BIGDATA nodes.
895 * #P_SUBP sub-pages are small leaf "pages" with duplicate data.
896 * A node with flag #F_DUPDATA but not #F_SUBDATA contains a sub-page.
897 * (Duplicate data can also go in sub-databases, which use normal pages.)
899 * #P_META pages contain #MDB_meta, the start point of an LMDB snapshot.
901 * Each non-metapage up to #MDB_meta.%mm_last_pg is reachable exactly once
902 * in the snapshot: Either used by a database or listed in a freeDB record.
904 typedef struct MDB_page {
905 #define mp_pgno mp_p.p_pgno
906 #define mp_next mp_p.p_next
908 pgno_t p_pgno; /**< page number */
909 struct MDB_page *p_next; /**< for in-memory list of freed pages */
911 uint16_t mp_pad; /**< key size if this is a LEAF2 page */
912 /** @defgroup mdb_page Page Flags
914 * Flags for the page headers.
917 #define P_BRANCH 0x01 /**< branch page */
918 #define P_LEAF 0x02 /**< leaf page */
919 #define P_OVERFLOW 0x04 /**< overflow page */
920 #define P_META 0x08 /**< meta page */
921 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
922 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
923 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
924 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
925 #define P_KEEP 0x8000 /**< leave this page alone during spill */
927 uint16_t mp_flags; /**< @ref mdb_page */
928 #define mp_lower mp_pb.pb.pb_lower
929 #define mp_upper mp_pb.pb.pb_upper
930 #define mp_pages mp_pb.pb_pages
933 indx_t pb_lower; /**< lower bound of free space */
934 indx_t pb_upper; /**< upper bound of free space */
936 uint32_t pb_pages; /**< number of overflow pages */
938 indx_t mp_ptrs[1]; /**< dynamic size */
941 /** Size of the page header, excluding dynamic data at the end */
942 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
944 /** Address of first usable data byte in a page, after the header */
945 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
947 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
948 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
950 /** Number of nodes on a page */
951 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
953 /** The amount of space remaining in the page */
954 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
956 /** The percentage of space used in the page, in tenths of a percent. */
957 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
958 ((env)->me_psize - PAGEHDRSZ))
959 /** The minimum page fill factor, in tenths of a percent.
960 * Pages emptier than this are candidates for merging.
962 #define FILL_THRESHOLD 250
964 /** Test if a page is a leaf page */
965 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
966 /** Test if a page is a LEAF2 page */
967 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
968 /** Test if a page is a branch page */
969 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
970 /** Test if a page is an overflow page */
971 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
972 /** Test if a page is a sub page */
973 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
975 /** The number of overflow pages needed to store the given size. */
976 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
978 /** Link in #MDB_txn.%mt_loose_pgs list.
979 * Kept outside the page header, which is needed when reusing the page.
981 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
983 /** Header for a single key/data pair within a page.
984 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
985 * We guarantee 2-byte alignment for 'MDB_node's.
987 * #mn_lo and #mn_hi are used for data size on leaf nodes, and for child
988 * pgno on branch nodes. On 64 bit platforms, #mn_flags is also used
989 * for pgno. (Branch nodes have no flags). Lo and hi are in host byte
990 * order in case some accesses can be optimized to 32-bit word access.
992 * Leaf node flags describe node contents. #F_BIGDATA says the node's
993 * data part is the page number of an overflow page with actual data.
994 * #F_DUPDATA and #F_SUBDATA can be combined giving duplicate data in
995 * a sub-page/sub-database, and named databases (just #F_SUBDATA).
997 typedef struct MDB_node {
998 /** part of data size or pgno
1000 #if BYTE_ORDER == LITTLE_ENDIAN
1001 unsigned short mn_lo, mn_hi;
1003 unsigned short mn_hi, mn_lo;
1006 /** @defgroup mdb_node Node Flags
1008 * Flags for node headers.
1011 #define F_BIGDATA 0x01 /**< data put on overflow page */
1012 #define F_SUBDATA 0x02 /**< data is a sub-database */
1013 #define F_DUPDATA 0x04 /**< data has duplicates */
1015 /** valid flags for #mdb_node_add() */
1016 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
1019 unsigned short mn_flags; /**< @ref mdb_node */
1020 unsigned short mn_ksize; /**< key size */
1021 char mn_data[1]; /**< key and data are appended here */
1024 /** Size of the node header, excluding dynamic data at the end */
1025 #define NODESIZE offsetof(MDB_node, mn_data)
1027 /** Bit position of top word in page number, for shifting mn_flags */
1028 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
1030 /** Size of a node in a branch page with a given key.
1031 * This is just the node header plus the key, there is no data.
1033 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
1035 /** Size of a node in a leaf page with a given key and data.
1036 * This is node header plus key plus data size.
1038 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
1040 /** Address of node \b i in page \b p */
1041 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
1043 /** Address of the key for the node */
1044 #define NODEKEY(node) (void *)((node)->mn_data)
1046 /** Address of the data for a node */
1047 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
1049 /** Get the page number pointed to by a branch node */
1050 #define NODEPGNO(node) \
1051 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
1052 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
1053 /** Set the page number in a branch node */
1054 #define SETPGNO(node,pgno) do { \
1055 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
1056 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
1058 /** Get the size of the data in a leaf node */
1059 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
1060 /** Set the size of the data for a leaf node */
1061 #define SETDSZ(node,size) do { \
1062 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
1063 /** The size of a key in a node */
1064 #define NODEKSZ(node) ((node)->mn_ksize)
1066 /** Copy a page number from src to dst */
1067 #ifdef MISALIGNED_OK
1068 #define COPY_PGNO(dst,src) dst = src
1070 #if MDB_SIZE_MAX > 0xffffffffU
1071 #define COPY_PGNO(dst,src) do { \
1072 unsigned short *s, *d; \
1073 s = (unsigned short *)&(src); \
1074 d = (unsigned short *)&(dst); \
1081 #define COPY_PGNO(dst,src) do { \
1082 unsigned short *s, *d; \
1083 s = (unsigned short *)&(src); \
1084 d = (unsigned short *)&(dst); \
1090 /** The address of a key in a LEAF2 page.
1091 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
1092 * There are no node headers, keys are stored contiguously.
1094 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
1096 /** Set the \b node's key into \b keyptr, if requested. */
1097 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
1098 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
1100 /** Set the \b node's key into \b key. */
1101 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
1103 /** Information about a single database in the environment. */
1104 typedef struct MDB_db {
1105 uint32_t md_pad; /**< also ksize for LEAF2 pages */
1106 uint16_t md_flags; /**< @ref mdb_dbi_open */
1107 uint16_t md_depth; /**< depth of this tree */
1108 pgno_t md_branch_pages; /**< number of internal pages */
1109 pgno_t md_leaf_pages; /**< number of leaf pages */
1110 pgno_t md_overflow_pages; /**< number of overflow pages */
1111 mdb_size_t md_entries; /**< number of data items */
1112 pgno_t md_root; /**< the root page of this tree */
1115 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
1116 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
1117 /** #mdb_dbi_open() flags */
1118 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
1119 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
1121 /** Handle for the DB used to track free pages. */
1123 /** Handle for the default DB. */
1125 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
1128 /** Number of meta pages - also hardcoded elsewhere */
1131 /** Meta page content.
1132 * A meta page is the start point for accessing a database snapshot.
1133 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
1135 typedef struct MDB_meta {
1136 /** Stamp identifying this as an LMDB file. It must be set
1139 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
1140 uint32_t mm_version;
1142 union { /* always zero since we don't support fixed mapping in MDB_VL32 */
1146 #define mm_address mm_un.mmun_address
1148 void *mm_address; /**< address for fixed mapping */
1150 mdb_size_t mm_mapsize; /**< size of mmap region */
1151 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
1152 /** The size of pages used in this DB */
1153 #define mm_psize mm_dbs[FREE_DBI].md_pad
1154 /** Any persistent environment flags. @ref mdb_env */
1155 #define mm_flags mm_dbs[FREE_DBI].md_flags
1156 /** Last used page in the datafile.
1157 * Actually the file may be shorter if the freeDB lists the final pages.
1160 volatile txnid_t mm_txnid; /**< txnid that committed this page */
1163 /** Buffer for a stack-allocated meta page.
1164 * The members define size and alignment, and silence type
1165 * aliasing warnings. They are not used directly; that could
1166 * mean incorrectly using several union members in parallel.
1168 typedef union MDB_metabuf {
1171 char mm_pad[PAGEHDRSZ];
1176 /** Auxiliary DB info.
1177 * The information here is mostly static/read-only. There is
1178 * only a single copy of this record in the environment.
1180 typedef struct MDB_dbx {
1181 MDB_val md_name; /**< name of the database */
1182 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1183 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1184 MDB_rel_func *md_rel; /**< user relocate function */
1185 void *md_relctx; /**< user-provided context for md_rel */
1188 /** A database transaction.
1189 * Every operation requires a transaction handle.
1192 MDB_txn *mt_parent; /**< parent of a nested txn */
1193 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1195 pgno_t mt_next_pgno; /**< next unallocated page */
1197 pgno_t mt_last_pgno; /**< last written page */
1199 /** The ID of this transaction. IDs are integers incrementing from 1.
1200 * Only committed write transactions increment the ID. If a transaction
1201 * aborts, the ID may be re-used by the next writer.
1204 MDB_env *mt_env; /**< the DB environment */
1205 /** The list of pages that became unused during this transaction.
1207 MDB_IDL mt_free_pgs;
1208 /** The list of loose pages that became unused and may be reused
1209 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1211 MDB_page *mt_loose_pgs;
1212 /** Number of loose pages (#mt_loose_pgs) */
1214 /** The sorted list of dirty pages we temporarily wrote to disk
1215 * because the dirty list was full. page numbers in here are
1216 * shifted left by 1, deleted slots have the LSB set.
1218 MDB_IDL mt_spill_pgs;
1220 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1221 MDB_ID2L dirty_list;
1222 /** For read txns: This thread/txn's reader table slot, or NULL. */
1225 /** Array of records for each DB known in the environment. */
1227 /** Array of MDB_db records for each known DB */
1229 /** Array of sequence numbers for each DB handle */
1230 unsigned int *mt_dbiseqs;
1231 /** @defgroup mt_dbflag Transaction DB Flags
1235 #define DB_DIRTY 0x01 /**< DB was written in this txn */
1236 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1237 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1238 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1239 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1240 #define DB_DUPDATA 0x20 /**< DB is #MDB_DUPSORT data */
1242 /** In write txns, array of cursors for each DB */
1243 MDB_cursor **mt_cursors;
1244 /** Array of flags for each DB */
1245 unsigned char *mt_dbflags;
1247 /** List of read-only pages (actually chunks) */
1249 /** We map chunks of 16 pages. Even though Windows uses 4KB pages, all
1250 * mappings must begin on 64KB boundaries. So we round off all pgnos to
1251 * a chunk boundary. We do the same on Linux for symmetry, and also to
1252 * reduce the frequency of mmap/munmap calls.
1254 #define MDB_RPAGE_CHUNK 16
1255 #define MDB_TRPAGE_SIZE 4096 /**< size of #mt_rpages array of chunks */
1256 #define MDB_TRPAGE_MAX (MDB_TRPAGE_SIZE-1) /**< maximum chunk index */
1257 unsigned int mt_rpcheck; /**< threshold for reclaiming unref'd chunks */
1259 /** Number of DB records in use, or 0 when the txn is finished.
1260 * This number only ever increments until the txn finishes; we
1261 * don't decrement it when individual DB handles are closed.
1265 /** @defgroup mdb_txn Transaction Flags
1269 /** #mdb_txn_begin() flags */
1270 #define MDB_TXN_BEGIN_FLAGS (MDB_NOMETASYNC|MDB_NOSYNC|MDB_RDONLY)
1271 #define MDB_TXN_NOMETASYNC MDB_NOMETASYNC /**< don't sync meta for this txn on commit */
1272 #define MDB_TXN_NOSYNC MDB_NOSYNC /**< don't sync this txn on commit */
1273 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1274 /* internal txn flags */
1275 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1276 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1277 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1278 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1279 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1280 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1281 /** most operations on the txn are currently illegal */
1282 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1284 unsigned int mt_flags; /**< @ref mdb_txn */
1285 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1286 * Includes ancestor txns' dirty pages not hidden by other txns'
1287 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1288 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1290 unsigned int mt_dirty_room;
1293 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1294 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1295 * raise this on a 64 bit machine.
1297 #define CURSOR_STACK 32
1301 /** Cursors are used for all DB operations.
1302 * A cursor holds a path of (page pointer, key index) from the DB
1303 * root to a position in the DB, plus other state. #MDB_DUPSORT
1304 * cursors include an xcursor to the current data item. Write txns
1305 * track their cursors and keep them up to date when data moves.
1306 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1307 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1310 /** Next cursor on this DB in this txn */
1311 MDB_cursor *mc_next;
1312 /** Backup of the original cursor if this cursor is a shadow */
1313 MDB_cursor *mc_backup;
1314 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1315 struct MDB_xcursor *mc_xcursor;
1316 /** The transaction that owns this cursor */
1318 /** The database handle this cursor operates on */
1320 /** The database record for this cursor */
1322 /** The database auxiliary record for this cursor */
1324 /** The @ref mt_dbflag for this database */
1325 unsigned char *mc_dbflag;
1326 unsigned short mc_snum; /**< number of pushed pages */
1327 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1328 /** @defgroup mdb_cursor Cursor Flags
1330 * Cursor state flags.
1333 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1334 #define C_EOF 0x02 /**< No more data */
1335 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1336 #define C_DEL 0x08 /**< last op was a cursor_del */
1337 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1338 #define C_WRITEMAP MDB_TXN_WRITEMAP /**< Copy of txn flag */
1339 /** Read-only cursor into the txn's original snapshot in the map.
1340 * Set for read-only txns, and in #mdb_page_alloc() for #FREE_DBI when
1341 * #MDB_DEVEL & 2. Only implements code which is necessary for this.
1343 #define C_ORIG_RDONLY MDB_TXN_RDONLY
1345 unsigned int mc_flags; /**< @ref mdb_cursor */
1346 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1347 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1349 MDB_page *mc_ovpg; /**< a referenced overflow page */
1350 # define MC_OVPG(mc) ((mc)->mc_ovpg)
1351 # define MC_SET_OVPG(mc, pg) ((mc)->mc_ovpg = (pg))
1353 # define MC_OVPG(mc) ((MDB_page *)0)
1354 # define MC_SET_OVPG(mc, pg) ((void)0)
1358 /** Context for sorted-dup records.
1359 * We could have gone to a fully recursive design, with arbitrarily
1360 * deep nesting of sub-databases. But for now we only handle these
1361 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1363 typedef struct MDB_xcursor {
1364 /** A sub-cursor for traversing the Dup DB */
1365 MDB_cursor mx_cursor;
1366 /** The database record for this Dup DB */
1368 /** The auxiliary DB record for this Dup DB */
1370 /** The @ref mt_dbflag for this Dup DB */
1371 unsigned char mx_dbflag;
1374 /** Check if there is an inited xcursor, so #XCURSOR_REFRESH() is proper */
1375 #define XCURSOR_INITED(mc) \
1376 ((mc)->mc_xcursor && ((mc)->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
1378 /** Update sub-page pointer, if any, in \b mc->mc_xcursor. Needed
1379 * when the node which contains the sub-page may have moved. Called
1380 * with \b mp = mc->mc_pg[mc->mc_top], \b ki = mc->mc_ki[mc->mc_top].
1382 #define XCURSOR_REFRESH(mc, mp, ki) do { \
1383 MDB_page *xr_pg = (mp); \
1384 MDB_node *xr_node = NODEPTR(xr_pg, ki); \
1385 if ((xr_node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) \
1386 (mc)->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(xr_node); \
1389 /** State of FreeDB old pages, stored in the MDB_env */
1390 typedef struct MDB_pgstate {
1391 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1392 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1395 /** The database environment. */
1397 HANDLE me_fd; /**< The main data file */
1398 HANDLE me_lfd; /**< The lock file */
1399 HANDLE me_mfd; /**< For writing and syncing the meta pages */
1400 #if defined(MDB_VL32) && defined(_WIN32)
1401 HANDLE me_fmh; /**< File Mapping handle */
1403 /** Failed to update the meta page. Probably an I/O error. */
1404 #define MDB_FATAL_ERROR 0x80000000U
1405 /** Some fields are initialized. */
1406 #define MDB_ENV_ACTIVE 0x20000000U
1407 /** me_txkey is set */
1408 #define MDB_ENV_TXKEY 0x10000000U
1409 /** fdatasync is unreliable */
1410 #define MDB_FSYNCONLY 0x08000000U
1411 uint32_t me_flags; /**< @ref mdb_env */
1412 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1413 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1414 unsigned int me_maxreaders; /**< size of the reader table */
1415 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1416 volatile int me_close_readers;
1417 MDB_dbi me_numdbs; /**< number of DBs opened */
1418 MDB_dbi me_maxdbs; /**< size of the DB table */
1419 MDB_PID_T me_pid; /**< process ID of this env */
1420 char *me_path; /**< path to the DB files */
1421 char *me_map; /**< the memory map of the data file */
1422 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1423 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1424 void *me_pbuf; /**< scratch area for DUPSORT put() */
1425 MDB_txn *me_txn; /**< current write transaction */
1426 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1427 mdb_size_t me_mapsize; /**< size of the data memory map */
1428 off_t me_size; /**< current file size */
1429 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1430 MDB_dbx *me_dbxs; /**< array of static DB info */
1431 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1432 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1433 pthread_key_t me_txkey; /**< thread-key for readers */
1434 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1435 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1436 # define me_pglast me_pgstate.mf_pglast
1437 # define me_pghead me_pgstate.mf_pghead
1438 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1439 /** IDL of pages that became unused in a write txn */
1440 MDB_IDL me_free_pgs;
1441 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1442 MDB_ID2L me_dirty_list;
1443 /** Max number of freelist items that can fit in a single overflow page */
1445 /** Max size of a node on a page */
1446 unsigned int me_nodemax;
1447 #if !(MDB_MAXKEYSIZE)
1448 unsigned int me_maxkey; /**< max size of a key */
1450 int me_live_reader; /**< have liveness lock in reader table */
1452 int me_pidquery; /**< Used in OpenProcess */
1454 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1455 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1456 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1458 mdb_mutex_t me_rmutex;
1459 mdb_mutex_t me_wmutex;
1460 # if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
1461 /** Half-initialized name of mutexes, to be completed by #MUTEXNAME() */
1462 char me_mutexname[sizeof(MUTEXNAME_PREFIX) + 11];
1466 MDB_ID3L me_rpages; /**< like #mt_rpages, but global to env */
1467 pthread_mutex_t me_rpmutex; /**< control access to #me_rpages */
1468 #define MDB_ERPAGE_SIZE 16384
1469 #define MDB_ERPAGE_MAX (MDB_ERPAGE_SIZE-1)
1470 unsigned int me_rpcheck;
1472 void *me_userctx; /**< User-settable context */
1473 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1476 /** Nested transaction */
1477 typedef struct MDB_ntxn {
1478 MDB_txn mnt_txn; /**< the transaction */
1479 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1482 /** max number of pages to commit in one writev() call */
1483 #define MDB_COMMIT_PAGES 64
1484 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1485 #undef MDB_COMMIT_PAGES
1486 #define MDB_COMMIT_PAGES IOV_MAX
1489 /** max bytes to write in one call */
1490 #define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
1492 /** Check \b txn and \b dbi arguments to a function */
1493 #define TXN_DBI_EXIST(txn, dbi, validity) \
1494 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1496 /** Check for misused \b dbi handles */
1497 #define TXN_DBI_CHANGED(txn, dbi) \
1498 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1500 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1501 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1502 static int mdb_page_touch(MDB_cursor *mc);
1504 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1505 "reset-tmp", "fail-begin", "fail-beginchild"}
1507 /* mdb_txn_end operation number, for logging */
1508 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1509 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1511 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1512 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1513 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1514 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1515 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1517 static int mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
1518 static int mdb_page_search_root(MDB_cursor *mc,
1519 MDB_val *key, int modify);
1520 #define MDB_PS_MODIFY 1
1521 #define MDB_PS_ROOTONLY 2
1522 #define MDB_PS_FIRST 4
1523 #define MDB_PS_LAST 8
1524 static int mdb_page_search(MDB_cursor *mc,
1525 MDB_val *key, int flags);
1526 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1528 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1529 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1530 pgno_t newpgno, unsigned int nflags);
1532 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1533 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1534 static int mdb_env_write_meta(MDB_txn *txn);
1535 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1536 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1538 static void mdb_env_close0(MDB_env *env, int excl);
1540 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1541 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1542 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1543 static void mdb_node_del(MDB_cursor *mc, int ksize);
1544 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1545 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1546 static int mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
1547 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1548 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1550 static int mdb_rebalance(MDB_cursor *mc);
1551 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1553 static void mdb_cursor_pop(MDB_cursor *mc);
1554 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1556 static int mdb_cursor_del0(MDB_cursor *mc);
1557 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1558 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1559 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1560 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1561 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1563 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1564 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1566 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1567 static void mdb_xcursor_init0(MDB_cursor *mc);
1568 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1569 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1571 static int mdb_drop0(MDB_cursor *mc, int subs);
1572 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1573 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1576 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1579 /** Compare two items pointing at '#mdb_size_t's of unknown alignment. */
1580 #ifdef MISALIGNED_OK
1581 # define mdb_cmp_clong mdb_cmp_long
1583 # define mdb_cmp_clong mdb_cmp_cint
1586 /** True if we need #mdb_cmp_clong() instead of \b cmp for #MDB_INTEGERDUP */
1587 #define NEED_CMP_CLONG(cmp, ksize) \
1588 (UINT_MAX < MDB_SIZE_MAX && \
1589 (cmp) == mdb_cmp_int && (ksize) == sizeof(mdb_size_t))
1592 static SECURITY_DESCRIPTOR mdb_null_sd;
1593 static SECURITY_ATTRIBUTES mdb_all_sa;
1594 static int mdb_sec_inited;
1597 static int utf8_to_utf16(const char *src, struct MDB_name *dst, int xtra);
1600 /** Return the library version info. */
1602 mdb_version(int *major, int *minor, int *patch)
1604 if (major) *major = MDB_VERSION_MAJOR;
1605 if (minor) *minor = MDB_VERSION_MINOR;
1606 if (patch) *patch = MDB_VERSION_PATCH;
1607 return MDB_VERSION_STRING;
1610 /** Table of descriptions for LMDB @ref errors */
1611 static char *const mdb_errstr[] = {
1612 "MDB_KEYEXIST: Key/data pair already exists",
1613 "MDB_NOTFOUND: No matching key/data pair found",
1614 "MDB_PAGE_NOTFOUND: Requested page not found",
1615 "MDB_CORRUPTED: Located page was wrong type",
1616 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1617 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1618 "MDB_INVALID: File is not an LMDB file",
1619 "MDB_MAP_FULL: Environment mapsize limit reached",
1620 "MDB_DBS_FULL: Environment maxdbs limit reached",
1621 "MDB_READERS_FULL: Environment maxreaders limit reached",
1622 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1623 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1624 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1625 "MDB_PAGE_FULL: Internal error - page has no more space",
1626 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1627 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1628 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1629 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1630 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1631 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1632 "MDB_PROBLEM: Unexpected problem - txn should abort",
1636 mdb_strerror(int err)
1639 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1640 * This works as long as no function between the call to mdb_strerror
1641 * and the actual use of the message uses more than 4K of stack.
1643 #define MSGSIZE 1024
1644 #define PADSIZE 4096
1645 char buf[MSGSIZE+PADSIZE], *ptr = buf;
1649 return ("Successful return: 0");
1651 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1652 i = err - MDB_KEYEXIST;
1653 return mdb_errstr[i];
1657 /* These are the C-runtime error codes we use. The comment indicates
1658 * their numeric value, and the Win32 error they would correspond to
1659 * if the error actually came from a Win32 API. A major mess, we should
1660 * have used LMDB-specific error codes for everything.
1663 case ENOENT: /* 2, FILE_NOT_FOUND */
1664 case EIO: /* 5, ACCESS_DENIED */
1665 case ENOMEM: /* 12, INVALID_ACCESS */
1666 case EACCES: /* 13, INVALID_DATA */
1667 case EBUSY: /* 16, CURRENT_DIRECTORY */
1668 case EINVAL: /* 22, BAD_COMMAND */
1669 case ENOSPC: /* 28, OUT_OF_PAPER */
1670 return strerror(err);
1675 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1676 FORMAT_MESSAGE_IGNORE_INSERTS,
1677 NULL, err, 0, ptr, MSGSIZE, (va_list *)buf+MSGSIZE);
1680 return strerror(err);
1684 /** assert(3) variant in cursor context */
1685 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1686 /** assert(3) variant in transaction context */
1687 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1688 /** assert(3) variant in environment context */
1689 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1692 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1693 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1696 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1697 const char *func, const char *file, int line)
1700 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1701 file, line, expr_txt, func);
1702 if (env->me_assert_func)
1703 env->me_assert_func(env, buf);
1704 fprintf(stderr, "%s\n", buf);
1708 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1712 /** Return the page number of \b mp which may be sub-page, for debug output */
1714 mdb_dbg_pgno(MDB_page *mp)
1717 COPY_PGNO(ret, mp->mp_pgno);
1721 /** Display a key in hexadecimal and return the address of the result.
1722 * @param[in] key the key to display
1723 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1724 * @return The key in hexadecimal form.
1727 mdb_dkey(MDB_val *key, char *buf)
1730 unsigned char *c = key->mv_data;
1736 if (key->mv_size > DKBUF_MAXKEYSIZE)
1737 return "MDB_MAXKEYSIZE";
1738 /* may want to make this a dynamic check: if the key is mostly
1739 * printable characters, print it as-is instead of converting to hex.
1743 for (i=0; i<key->mv_size; i++)
1744 ptr += sprintf(ptr, "%02x", *c++);
1746 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1752 mdb_leafnode_type(MDB_node *n)
1754 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1755 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1756 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1759 /** Display all the keys in the page. */
1761 mdb_page_list(MDB_page *mp)
1763 pgno_t pgno = mdb_dbg_pgno(mp);
1764 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1766 unsigned int i, nkeys, nsize, total = 0;
1770 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1771 case P_BRANCH: type = "Branch page"; break;
1772 case P_LEAF: type = "Leaf page"; break;
1773 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1774 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1775 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1777 fprintf(stderr, "Overflow page %"Yu" pages %u%s\n",
1778 pgno, mp->mp_pages, state);
1781 fprintf(stderr, "Meta-page %"Yu" txnid %"Yu"\n",
1782 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1785 fprintf(stderr, "Bad page %"Yu" flags 0x%X\n", pgno, mp->mp_flags);
1789 nkeys = NUMKEYS(mp);
1790 fprintf(stderr, "%s %"Yu" numkeys %d%s\n", type, pgno, nkeys, state);
1792 for (i=0; i<nkeys; i++) {
1793 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1794 key.mv_size = nsize = mp->mp_pad;
1795 key.mv_data = LEAF2KEY(mp, i, nsize);
1797 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1800 node = NODEPTR(mp, i);
1801 key.mv_size = node->mn_ksize;
1802 key.mv_data = node->mn_data;
1803 nsize = NODESIZE + key.mv_size;
1804 if (IS_BRANCH(mp)) {
1805 fprintf(stderr, "key %d: page %"Yu", %s\n", i, NODEPGNO(node),
1809 if (F_ISSET(node->mn_flags, F_BIGDATA))
1810 nsize += sizeof(pgno_t);
1812 nsize += NODEDSZ(node);
1814 nsize += sizeof(indx_t);
1815 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1816 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1818 total = EVEN(total);
1820 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1821 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1825 mdb_cursor_chk(MDB_cursor *mc)
1831 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1832 for (i=0; i<mc->mc_top; i++) {
1834 node = NODEPTR(mp, mc->mc_ki[i]);
1835 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1838 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1840 if (XCURSOR_INITED(mc)) {
1841 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1842 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1843 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1851 /** Count all the pages in each DB and in the freelist
1852 * and make sure it matches the actual number of pages
1854 * All named DBs must be open for a correct count.
1856 static void mdb_audit(MDB_txn *txn)
1860 MDB_ID freecount, count;
1865 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1866 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1867 freecount += *(MDB_ID *)data.mv_data;
1868 mdb_tassert(txn, rc == MDB_NOTFOUND);
1871 for (i = 0; i<txn->mt_numdbs; i++) {
1873 if (!(txn->mt_dbflags[i] & DB_VALID))
1875 mdb_cursor_init(&mc, txn, i, &mx);
1876 if (txn->mt_dbs[i].md_root == P_INVALID)
1878 count += txn->mt_dbs[i].md_branch_pages +
1879 txn->mt_dbs[i].md_leaf_pages +
1880 txn->mt_dbs[i].md_overflow_pages;
1881 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1882 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1883 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1886 mp = mc.mc_pg[mc.mc_top];
1887 for (j=0; j<NUMKEYS(mp); j++) {
1888 MDB_node *leaf = NODEPTR(mp, j);
1889 if (leaf->mn_flags & F_SUBDATA) {
1891 memcpy(&db, NODEDATA(leaf), sizeof(db));
1892 count += db.md_branch_pages + db.md_leaf_pages +
1893 db.md_overflow_pages;
1897 mdb_tassert(txn, rc == MDB_NOTFOUND);
1900 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1901 fprintf(stderr, "audit: %"Yu" freecount: %"Yu" count: %"Yu" total: %"Yu" next_pgno: %"Yu"\n",
1902 txn->mt_txnid, freecount, count+NUM_METAS,
1903 freecount+count+NUM_METAS, txn->mt_next_pgno);
1909 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1911 return txn->mt_dbxs[dbi].md_cmp(a, b);
1915 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1917 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1918 if (NEED_CMP_CLONG(dcmp, a->mv_size))
1919 dcmp = mdb_cmp_clong;
1923 /** Allocate memory for a page.
1924 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1925 * Set #MDB_TXN_ERROR on failure.
1928 mdb_page_malloc(MDB_txn *txn, unsigned num)
1930 MDB_env *env = txn->mt_env;
1931 MDB_page *ret = env->me_dpages;
1932 size_t psize = env->me_psize, sz = psize, off;
1933 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1934 * For a single page alloc, we init everything after the page header.
1935 * For multi-page, we init the final page; if the caller needed that
1936 * many pages they will be filling in at least up to the last page.
1940 VGMEMP_ALLOC(env, ret, sz);
1941 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1942 env->me_dpages = ret->mp_next;
1945 psize -= off = PAGEHDRSZ;
1950 if ((ret = malloc(sz)) != NULL) {
1951 VGMEMP_ALLOC(env, ret, sz);
1952 if (!(env->me_flags & MDB_NOMEMINIT)) {
1953 memset((char *)ret + off, 0, psize);
1957 txn->mt_flags |= MDB_TXN_ERROR;
1961 /** Free a single page.
1962 * Saves single pages to a list, for future reuse.
1963 * (This is not used for multi-page overflow pages.)
1966 mdb_page_free(MDB_env *env, MDB_page *mp)
1968 mp->mp_next = env->me_dpages;
1969 VGMEMP_FREE(env, mp);
1970 env->me_dpages = mp;
1973 /** Free a dirty page */
1975 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1977 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1978 mdb_page_free(env, dp);
1980 /* large pages just get freed directly */
1981 VGMEMP_FREE(env, dp);
1986 /** Return all dirty pages to dpage list */
1988 mdb_dlist_free(MDB_txn *txn)
1990 MDB_env *env = txn->mt_env;
1991 MDB_ID2L dl = txn->mt_u.dirty_list;
1992 unsigned i, n = dl[0].mid;
1994 for (i = 1; i <= n; i++) {
1995 mdb_dpage_free(env, dl[i].mptr);
2002 mdb_page_unref(MDB_txn *txn, MDB_page *mp)
2005 MDB_ID3L tl = txn->mt_rpages;
2007 if (mp->mp_flags & (P_SUBP|P_DIRTY))
2009 rem = mp->mp_pgno & (MDB_RPAGE_CHUNK-1);
2010 pgno = mp->mp_pgno ^ rem;
2011 x = mdb_mid3l_search(tl, pgno);
2012 if (x != tl[0].mid && tl[x+1].mid == mp->mp_pgno)
2017 #define MDB_PAGE_UNREF(txn, mp) mdb_page_unref(txn, mp)
2020 mdb_cursor_unref(MDB_cursor *mc)
2023 if (mc->mc_txn->mt_rpages[0].mid) {
2024 if (!mc->mc_snum || !mc->mc_pg[0] || IS_SUBP(mc->mc_pg[0]))
2026 for (i=0; i<mc->mc_snum; i++)
2027 mdb_page_unref(mc->mc_txn, mc->mc_pg[i]);
2029 mdb_page_unref(mc->mc_txn, mc->mc_ovpg);
2033 mc->mc_snum = mc->mc_top = 0;
2034 mc->mc_pg[0] = NULL;
2035 mc->mc_flags &= ~C_INITIALIZED;
2037 #define MDB_CURSOR_UNREF(mc, force) \
2038 (((force) || ((mc)->mc_flags & C_INITIALIZED)) \
2039 ? mdb_cursor_unref(mc) \
2043 #define MDB_PAGE_UNREF(txn, mp)
2044 #define MDB_CURSOR_UNREF(mc, force) ((void)0)
2045 #endif /* MDB_VL32 */
2047 /** Loosen or free a single page.
2048 * Saves single pages to a list for future reuse
2049 * in this same txn. It has been pulled from the freeDB
2050 * and already resides on the dirty list, but has been
2051 * deleted. Use these pages first before pulling again
2054 * If the page wasn't dirtied in this txn, just add it
2055 * to this txn's free list.
2058 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
2061 pgno_t pgno = mp->mp_pgno;
2062 MDB_txn *txn = mc->mc_txn;
2064 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
2065 if (txn->mt_parent) {
2066 MDB_ID2 *dl = txn->mt_u.dirty_list;
2067 /* If txn has a parent, make sure the page is in our
2071 unsigned x = mdb_mid2l_search(dl, pgno);
2072 if (x <= dl[0].mid && dl[x].mid == pgno) {
2073 if (mp != dl[x].mptr) { /* bad cursor? */
2074 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2075 txn->mt_flags |= MDB_TXN_ERROR;
2083 /* no parent txn, so it's just ours */
2088 DPRINTF(("loosen db %d page %"Yu, DDBI(mc), mp->mp_pgno));
2089 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
2090 txn->mt_loose_pgs = mp;
2091 txn->mt_loose_count++;
2092 mp->mp_flags |= P_LOOSE;
2094 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
2102 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
2103 * @param[in] mc A cursor handle for the current operation.
2104 * @param[in] pflags Flags of the pages to update:
2105 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
2106 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
2107 * @return 0 on success, non-zero on failure.
2110 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
2112 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
2113 MDB_txn *txn = mc->mc_txn;
2114 MDB_cursor *m3, *m0 = mc;
2119 int rc = MDB_SUCCESS, level;
2121 /* Mark pages seen by cursors: First m0, then tracked cursors */
2122 for (i = txn->mt_numdbs;; ) {
2123 if (mc->mc_flags & C_INITIALIZED) {
2124 for (m3 = mc;; m3 = &mx->mx_cursor) {
2126 for (j=0; j<m3->mc_snum; j++) {
2128 if ((mp->mp_flags & Mask) == pflags)
2129 mp->mp_flags ^= P_KEEP;
2131 mx = m3->mc_xcursor;
2132 /* Proceed to mx if it is at a sub-database */
2133 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
2135 if (! (mp && (mp->mp_flags & P_LEAF)))
2137 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
2138 if (!(leaf->mn_flags & F_SUBDATA))
2143 for (; !mc || mc == m0; mc = txn->mt_cursors[--i])
2150 /* Mark dirty root pages */
2151 for (i=0; i<txn->mt_numdbs; i++) {
2152 if (txn->mt_dbflags[i] & DB_DIRTY) {
2153 pgno_t pgno = txn->mt_dbs[i].md_root;
2154 if (pgno == P_INVALID)
2156 if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
2158 if ((dp->mp_flags & Mask) == pflags && level <= 1)
2159 dp->mp_flags ^= P_KEEP;
2167 static int mdb_page_flush(MDB_txn *txn, int keep);
2169 /** Spill pages from the dirty list back to disk.
2170 * This is intended to prevent running into #MDB_TXN_FULL situations,
2171 * but note that they may still occur in a few cases:
2172 * 1) our estimate of the txn size could be too small. Currently this
2173 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
2174 * 2) child txns may run out of space if their parents dirtied a
2175 * lot of pages and never spilled them. TODO: we probably should do
2176 * a preemptive spill during #mdb_txn_begin() of a child txn, if
2177 * the parent's dirty_room is below a given threshold.
2179 * Otherwise, if not using nested txns, it is expected that apps will
2180 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
2181 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
2182 * If the txn never references them again, they can be left alone.
2183 * If the txn only reads them, they can be used without any fuss.
2184 * If the txn writes them again, they can be dirtied immediately without
2185 * going thru all of the work of #mdb_page_touch(). Such references are
2186 * handled by #mdb_page_unspill().
2188 * Also note, we never spill DB root pages, nor pages of active cursors,
2189 * because we'll need these back again soon anyway. And in nested txns,
2190 * we can't spill a page in a child txn if it was already spilled in a
2191 * parent txn. That would alter the parent txns' data even though
2192 * the child hasn't committed yet, and we'd have no way to undo it if
2193 * the child aborted.
2195 * @param[in] m0 cursor A cursor handle identifying the transaction and
2196 * database for which we are checking space.
2197 * @param[in] key For a put operation, the key being stored.
2198 * @param[in] data For a put operation, the data being stored.
2199 * @return 0 on success, non-zero on failure.
2202 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
2204 MDB_txn *txn = m0->mc_txn;
2206 MDB_ID2L dl = txn->mt_u.dirty_list;
2207 unsigned int i, j, need;
2210 if (m0->mc_flags & C_SUB)
2213 /* Estimate how much space this op will take */
2214 i = m0->mc_db->md_depth;
2215 /* Named DBs also dirty the main DB */
2216 if (m0->mc_dbi >= CORE_DBS)
2217 i += txn->mt_dbs[MAIN_DBI].md_depth;
2218 /* For puts, roughly factor in the key+data size */
2220 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
2221 i += i; /* double it for good measure */
2224 if (txn->mt_dirty_room > i)
2227 if (!txn->mt_spill_pgs) {
2228 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
2229 if (!txn->mt_spill_pgs)
2232 /* purge deleted slots */
2233 MDB_IDL sl = txn->mt_spill_pgs;
2234 unsigned int num = sl[0];
2236 for (i=1; i<=num; i++) {
2243 /* Preserve pages which may soon be dirtied again */
2244 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2247 /* Less aggressive spill - we originally spilled the entire dirty list,
2248 * with a few exceptions for cursor pages and DB root pages. But this
2249 * turns out to be a lot of wasted effort because in a large txn many
2250 * of those pages will need to be used again. So now we spill only 1/8th
2251 * of the dirty pages. Testing revealed this to be a good tradeoff,
2252 * better than 1/2, 1/4, or 1/10.
2254 if (need < MDB_IDL_UM_MAX / 8)
2255 need = MDB_IDL_UM_MAX / 8;
2257 /* Save the page IDs of all the pages we're flushing */
2258 /* flush from the tail forward, this saves a lot of shifting later on. */
2259 for (i=dl[0].mid; i && need; i--) {
2260 MDB_ID pn = dl[i].mid << 1;
2262 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2264 /* Can't spill twice, make sure it's not already in a parent's
2267 if (txn->mt_parent) {
2269 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2270 if (tx2->mt_spill_pgs) {
2271 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2272 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2273 dp->mp_flags |= P_KEEP;
2281 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2285 mdb_midl_sort(txn->mt_spill_pgs);
2287 /* Flush the spilled part of dirty list */
2288 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2291 /* Reset any dirty pages we kept that page_flush didn't see */
2292 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2295 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2299 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2301 mdb_find_oldest(MDB_txn *txn)
2304 txnid_t mr, oldest = txn->mt_txnid - 1;
2305 if (txn->mt_env->me_txns) {
2306 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2307 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2318 /** Add a page to the txn's dirty list */
2320 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2323 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2325 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2326 insert = mdb_mid2l_append;
2328 insert = mdb_mid2l_insert;
2330 mid.mid = mp->mp_pgno;
2332 rc = insert(txn->mt_u.dirty_list, &mid);
2333 mdb_tassert(txn, rc == 0);
2334 txn->mt_dirty_room--;
2337 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2338 * me_pghead and mt_next_pgno. Set #MDB_TXN_ERROR on failure.
2340 * If there are free pages available from older transactions, they
2341 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2342 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2343 * and move me_pglast to say which records were consumed. Only this
2344 * function can create me_pghead and move me_pglast/mt_next_pgno.
2345 * When #MDB_DEVEL & 2, it is not affected by #mdb_freelist_save(): it
2346 * then uses the transaction's original snapshot of the freeDB.
2347 * @param[in] mc cursor A cursor handle identifying the transaction and
2348 * database for which we are allocating.
2349 * @param[in] num the number of pages to allocate.
2350 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2351 * will always be satisfied by a single contiguous chunk of memory.
2352 * @return 0 on success, non-zero on failure.
2355 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2357 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2358 /* Get at most <Max_retries> more freeDB records once me_pghead
2359 * has enough pages. If not enough, use new pages from the map.
2360 * If <Paranoid> and mc is updating the freeDB, only get new
2361 * records if me_pghead is empty. Then the freelist cannot play
2362 * catch-up with itself by growing while trying to save it.
2364 enum { Paranoid = 1, Max_retries = 500 };
2366 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2368 int rc, retry = num * 60;
2369 MDB_txn *txn = mc->mc_txn;
2370 MDB_env *env = txn->mt_env;
2371 pgno_t pgno, *mop = env->me_pghead;
2372 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2374 txnid_t oldest = 0, last;
2379 /* If there are any loose pages, just use them */
2380 if (num == 1 && txn->mt_loose_pgs) {
2381 np = txn->mt_loose_pgs;
2382 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2383 txn->mt_loose_count--;
2384 DPRINTF(("db %d use loose page %"Yu, DDBI(mc), np->mp_pgno));
2391 /* If our dirty list is already full, we can't do anything */
2392 if (txn->mt_dirty_room == 0) {
2397 for (op = MDB_FIRST;; op = MDB_NEXT) {
2402 /* Seek a big enough contiguous page range. Prefer
2403 * pages at the tail, just truncating the list.
2409 if (mop[i-n2] == pgno+n2)
2416 if (op == MDB_FIRST) { /* 1st iteration */
2417 /* Prepare to fetch more and coalesce */
2418 last = env->me_pglast;
2419 oldest = env->me_pgoldest;
2420 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2421 #if (MDB_DEVEL) & 2 /* "& 2" so MDB_DEVEL=1 won't hide bugs breaking freeDB */
2422 /* Use original snapshot. TODO: Should need less care in code
2423 * which modifies the database. Maybe we can delete some code?
2425 m2.mc_flags |= C_ORIG_RDONLY;
2426 m2.mc_db = &env->me_metas[(txn->mt_txnid-1) & 1]->mm_dbs[FREE_DBI];
2427 m2.mc_dbflag = (unsigned char *)""; /* probably unnecessary */
2431 key.mv_data = &last; /* will look up last+1 */
2432 key.mv_size = sizeof(last);
2434 if (Paranoid && mc->mc_dbi == FREE_DBI)
2437 if (Paranoid && retry < 0 && mop_len)
2441 /* Do not fetch more if the record will be too recent */
2442 if (oldest <= last) {
2444 oldest = mdb_find_oldest(txn);
2445 env->me_pgoldest = oldest;
2451 rc = mdb_cursor_get(&m2, &key, NULL, op);
2453 if (rc == MDB_NOTFOUND)
2457 last = *(txnid_t*)key.mv_data;
2458 if (oldest <= last) {
2460 oldest = mdb_find_oldest(txn);
2461 env->me_pgoldest = oldest;
2467 np = m2.mc_pg[m2.mc_top];
2468 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2469 if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
2472 idl = (MDB_ID *) data.mv_data;
2475 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2480 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2482 mop = env->me_pghead;
2484 env->me_pglast = last;
2486 DPRINTF(("IDL read txn %"Yu" root %"Yu" num %u",
2487 last, txn->mt_dbs[FREE_DBI].md_root, i));
2489 DPRINTF(("IDL %"Yu, idl[j]));
2491 /* Merge in descending sorted order */
2492 mdb_midl_xmerge(mop, idl);
2496 /* Use new pages from the map when nothing suitable in the freeDB */
2498 pgno = txn->mt_next_pgno;
2499 if (pgno + num >= env->me_maxpg) {
2500 DPUTS("DB size maxed out");
2504 #if defined(_WIN32) && !defined(MDB_VL32)
2505 if (!(env->me_flags & MDB_RDONLY)) {
2507 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
2508 p = VirtualAlloc(p, env->me_psize * num, MEM_COMMIT,
2509 (env->me_flags & MDB_WRITEMAP) ? PAGE_READWRITE:
2512 DPUTS("VirtualAlloc failed");
2520 if (env->me_flags & MDB_WRITEMAP) {
2521 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2523 if (!(np = mdb_page_malloc(txn, num))) {
2529 mop[0] = mop_len -= num;
2530 /* Move any stragglers down */
2531 for (j = i-num; j < mop_len; )
2532 mop[++j] = mop[++i];
2534 txn->mt_next_pgno = pgno + num;
2537 mdb_page_dirty(txn, np);
2543 txn->mt_flags |= MDB_TXN_ERROR;
2547 /** Copy the used portions of a non-overflow page.
2548 * @param[in] dst page to copy into
2549 * @param[in] src page to copy from
2550 * @param[in] psize size of a page
2553 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2555 enum { Align = sizeof(pgno_t) };
2556 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2558 /* If page isn't full, just copy the used portion. Adjust
2559 * alignment so memcpy may copy words instead of bytes.
2561 if ((unused &= -Align) && !IS_LEAF2(src)) {
2562 upper = (upper + PAGEBASE) & -Align;
2563 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2564 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2567 memcpy(dst, src, psize - unused);
2571 /** Pull a page off the txn's spill list, if present.
2572 * If a page being referenced was spilled to disk in this txn, bring
2573 * it back and make it dirty/writable again.
2574 * @param[in] txn the transaction handle.
2575 * @param[in] mp the page being referenced. It must not be dirty.
2576 * @param[out] ret the writable page, if any. ret is unchanged if
2577 * mp wasn't spilled.
2580 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2582 MDB_env *env = txn->mt_env;
2585 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2587 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2588 if (!tx2->mt_spill_pgs)
2590 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2591 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2594 if (txn->mt_dirty_room == 0)
2595 return MDB_TXN_FULL;
2596 if (IS_OVERFLOW(mp))
2600 if (env->me_flags & MDB_WRITEMAP) {
2603 np = mdb_page_malloc(txn, num);
2607 memcpy(np, mp, num * env->me_psize);
2609 mdb_page_copy(np, mp, env->me_psize);
2612 /* If in current txn, this page is no longer spilled.
2613 * If it happens to be the last page, truncate the spill list.
2614 * Otherwise mark it as deleted by setting the LSB.
2616 if (x == txn->mt_spill_pgs[0])
2617 txn->mt_spill_pgs[0]--;
2619 txn->mt_spill_pgs[x] |= 1;
2620 } /* otherwise, if belonging to a parent txn, the
2621 * page remains spilled until child commits
2624 mdb_page_dirty(txn, np);
2625 np->mp_flags |= P_DIRTY;
2633 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2634 * Set #MDB_TXN_ERROR on failure.
2635 * @param[in] mc cursor pointing to the page to be touched
2636 * @return 0 on success, non-zero on failure.
2639 mdb_page_touch(MDB_cursor *mc)
2641 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2642 MDB_txn *txn = mc->mc_txn;
2643 MDB_cursor *m2, *m3;
2647 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2648 if (txn->mt_flags & MDB_TXN_SPILLS) {
2650 rc = mdb_page_unspill(txn, mp, &np);
2656 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2657 (rc = mdb_page_alloc(mc, 1, &np)))
2660 DPRINTF(("touched db %d page %"Yu" -> %"Yu, DDBI(mc),
2661 mp->mp_pgno, pgno));
2662 mdb_cassert(mc, mp->mp_pgno != pgno);
2663 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2664 /* Update the parent page, if any, to point to the new page */
2666 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2667 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2668 SETPGNO(node, pgno);
2670 mc->mc_db->md_root = pgno;
2672 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2673 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2675 /* If txn has a parent, make sure the page is in our
2679 unsigned x = mdb_mid2l_search(dl, pgno);
2680 if (x <= dl[0].mid && dl[x].mid == pgno) {
2681 if (mp != dl[x].mptr) { /* bad cursor? */
2682 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2683 txn->mt_flags |= MDB_TXN_ERROR;
2689 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2691 np = mdb_page_malloc(txn, 1);
2696 rc = mdb_mid2l_insert(dl, &mid);
2697 mdb_cassert(mc, rc == 0);
2702 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2704 np->mp_flags |= P_DIRTY;
2707 /* Adjust cursors pointing to mp */
2708 mc->mc_pg[mc->mc_top] = np;
2709 m2 = txn->mt_cursors[mc->mc_dbi];
2710 if (mc->mc_flags & C_SUB) {
2711 for (; m2; m2=m2->mc_next) {
2712 m3 = &m2->mc_xcursor->mx_cursor;
2713 if (m3->mc_snum < mc->mc_snum) continue;
2714 if (m3->mc_pg[mc->mc_top] == mp)
2715 m3->mc_pg[mc->mc_top] = np;
2718 for (; m2; m2=m2->mc_next) {
2719 if (m2->mc_snum < mc->mc_snum) continue;
2720 if (m2 == mc) continue;
2721 if (m2->mc_pg[mc->mc_top] == mp) {
2722 m2->mc_pg[mc->mc_top] = np;
2723 if (XCURSOR_INITED(m2) && IS_LEAF(np))
2724 XCURSOR_REFRESH(m2, np, m2->mc_ki[mc->mc_top]);
2728 MDB_PAGE_UNREF(mc->mc_txn, mp);
2732 txn->mt_flags |= MDB_TXN_ERROR;
2737 mdb_env_sync0(MDB_env *env, int force, pgno_t numpgs)
2740 if (env->me_flags & MDB_RDONLY)
2742 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2743 if (env->me_flags & MDB_WRITEMAP) {
2744 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2745 ? MS_ASYNC : MS_SYNC;
2746 if (MDB_MSYNC(env->me_map, env->me_psize * numpgs, flags))
2749 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2753 #ifdef BROKEN_FDATASYNC
2754 if (env->me_flags & MDB_FSYNCONLY) {
2755 if (fsync(env->me_fd))
2759 if (MDB_FDATASYNC(env->me_fd))
2767 mdb_env_sync(MDB_env *env, int force)
2769 MDB_meta *m = mdb_env_pick_meta(env);
2770 return mdb_env_sync0(env, force, m->mm_last_pg+1);
2773 /** Back up parent txn's cursors, then grab the originals for tracking */
2775 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2777 MDB_cursor *mc, *bk;
2782 for (i = src->mt_numdbs; --i >= 0; ) {
2783 if ((mc = src->mt_cursors[i]) != NULL) {
2784 size = sizeof(MDB_cursor);
2786 size += sizeof(MDB_xcursor);
2787 for (; mc; mc = bk->mc_next) {
2793 mc->mc_db = &dst->mt_dbs[i];
2794 /* Kill pointers into src to reduce abuse: The
2795 * user may not use mc until dst ends. But we need a valid
2796 * txn pointer here for cursor fixups to keep working.
2799 mc->mc_dbflag = &dst->mt_dbflags[i];
2800 if ((mx = mc->mc_xcursor) != NULL) {
2801 *(MDB_xcursor *)(bk+1) = *mx;
2802 mx->mx_cursor.mc_txn = dst;
2804 mc->mc_next = dst->mt_cursors[i];
2805 dst->mt_cursors[i] = mc;
2812 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2813 * @param[in] txn the transaction handle.
2814 * @param[in] merge true to keep changes to parent cursors, false to revert.
2815 * @return 0 on success, non-zero on failure.
2818 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2820 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2824 for (i = txn->mt_numdbs; --i >= 0; ) {
2825 for (mc = cursors[i]; mc; mc = next) {
2827 if ((bk = mc->mc_backup) != NULL) {
2829 /* Commit changes to parent txn */
2830 mc->mc_next = bk->mc_next;
2831 mc->mc_backup = bk->mc_backup;
2832 mc->mc_txn = bk->mc_txn;
2833 mc->mc_db = bk->mc_db;
2834 mc->mc_dbflag = bk->mc_dbflag;
2835 if ((mx = mc->mc_xcursor) != NULL)
2836 mx->mx_cursor.mc_txn = bk->mc_txn;
2838 /* Abort nested txn */
2840 if ((mx = mc->mc_xcursor) != NULL)
2841 *mx = *(MDB_xcursor *)(bk+1);
2845 /* Only malloced cursors are permanently tracked. */
2852 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2858 Pidset = F_SETLK, Pidcheck = F_GETLK
2862 /** Set or check a pid lock. Set returns 0 on success.
2863 * Check returns 0 if the process is certainly dead, nonzero if it may
2864 * be alive (the lock exists or an error happened so we do not know).
2866 * On Windows Pidset is a no-op, we merely check for the existence
2867 * of the process with the given pid. On POSIX we use a single byte
2868 * lock on the lockfile, set at an offset equal to the pid.
2871 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2873 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2876 if (op == Pidcheck) {
2877 h = OpenProcess(env->me_pidquery, FALSE, pid);
2878 /* No documented "no such process" code, but other program use this: */
2880 return ErrCode() != ERROR_INVALID_PARAMETER;
2881 /* A process exists until all handles to it close. Has it exited? */
2882 ret = WaitForSingleObject(h, 0) != 0;
2889 struct flock lock_info;
2890 memset(&lock_info, 0, sizeof(lock_info));
2891 lock_info.l_type = F_WRLCK;
2892 lock_info.l_whence = SEEK_SET;
2893 lock_info.l_start = pid;
2894 lock_info.l_len = 1;
2895 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2896 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2898 } else if ((rc = ErrCode()) == EINTR) {
2906 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2907 * @param[in] txn the transaction handle to initialize
2908 * @return 0 on success, non-zero on failure.
2911 mdb_txn_renew0(MDB_txn *txn)
2913 MDB_env *env = txn->mt_env;
2914 MDB_txninfo *ti = env->me_txns;
2916 unsigned int i, nr, flags = txn->mt_flags;
2918 int rc, new_notls = 0;
2920 if ((flags &= MDB_TXN_RDONLY) != 0) {
2922 meta = mdb_env_pick_meta(env);
2923 txn->mt_txnid = meta->mm_txnid;
2924 txn->mt_u.reader = NULL;
2926 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2927 pthread_getspecific(env->me_txkey);
2929 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2930 return MDB_BAD_RSLOT;
2932 MDB_PID_T pid = env->me_pid;
2933 MDB_THR_T tid = pthread_self();
2934 mdb_mutexref_t rmutex = env->me_rmutex;
2936 if (!env->me_live_reader) {
2937 rc = mdb_reader_pid(env, Pidset, pid);
2940 env->me_live_reader = 1;
2943 if (LOCK_MUTEX(rc, env, rmutex))
2945 nr = ti->mti_numreaders;
2946 for (i=0; i<nr; i++)
2947 if (ti->mti_readers[i].mr_pid == 0)
2949 if (i == env->me_maxreaders) {
2950 UNLOCK_MUTEX(rmutex);
2951 return MDB_READERS_FULL;
2953 r = &ti->mti_readers[i];
2954 /* Claim the reader slot, carefully since other code
2955 * uses the reader table un-mutexed: First reset the
2956 * slot, next publish it in mti_numreaders. After
2957 * that, it is safe for mdb_env_close() to touch it.
2958 * When it will be closed, we can finally claim it.
2961 r->mr_txnid = (txnid_t)-1;
2964 ti->mti_numreaders = ++nr;
2965 env->me_close_readers = nr;
2967 UNLOCK_MUTEX(rmutex);
2969 new_notls = (env->me_flags & MDB_NOTLS);
2970 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2975 do /* LY: Retry on a race, ITS#7970. */
2976 r->mr_txnid = ti->mti_txnid;
2977 while(r->mr_txnid != ti->mti_txnid);
2978 txn->mt_txnid = r->mr_txnid;
2979 txn->mt_u.reader = r;
2980 meta = env->me_metas[txn->mt_txnid & 1];
2984 /* Not yet touching txn == env->me_txn0, it may be active */
2986 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2988 txn->mt_txnid = ti->mti_txnid;
2989 meta = env->me_metas[txn->mt_txnid & 1];
2991 meta = mdb_env_pick_meta(env);
2992 txn->mt_txnid = meta->mm_txnid;
2996 if (txn->mt_txnid == mdb_debug_start)
2999 txn->mt_child = NULL;
3000 txn->mt_loose_pgs = NULL;
3001 txn->mt_loose_count = 0;
3002 txn->mt_dirty_room = MDB_IDL_UM_MAX;
3003 txn->mt_u.dirty_list = env->me_dirty_list;
3004 txn->mt_u.dirty_list[0].mid = 0;
3005 txn->mt_free_pgs = env->me_free_pgs;
3006 txn->mt_free_pgs[0] = 0;
3007 txn->mt_spill_pgs = NULL;
3009 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
3012 /* Copy the DB info and flags */
3013 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
3015 /* Moved to here to avoid a data race in read TXNs */
3016 txn->mt_next_pgno = meta->mm_last_pg+1;
3018 txn->mt_last_pgno = txn->mt_next_pgno - 1;
3021 txn->mt_flags = flags;
3024 txn->mt_numdbs = env->me_numdbs;
3025 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3026 x = env->me_dbflags[i];
3027 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
3028 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
3030 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
3031 txn->mt_dbflags[FREE_DBI] = DB_VALID;
3033 if (env->me_flags & MDB_FATAL_ERROR) {
3034 DPUTS("environment had fatal error, must shutdown!");
3036 } else if (env->me_maxpg < txn->mt_next_pgno) {
3037 rc = MDB_MAP_RESIZED;
3041 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
3046 mdb_txn_renew(MDB_txn *txn)
3050 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
3053 rc = mdb_txn_renew0(txn);
3054 if (rc == MDB_SUCCESS) {
3055 DPRINTF(("renew txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3056 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
3057 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
3063 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
3067 int rc, size, tsize;
3069 flags &= MDB_TXN_BEGIN_FLAGS;
3070 flags |= env->me_flags & MDB_WRITEMAP;
3072 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
3076 /* Nested transactions: Max 1 child, write txns only, no writemap */
3077 flags |= parent->mt_flags;
3078 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
3079 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
3081 /* Child txns save MDB_pgstate and use own copy of cursors */
3082 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
3083 size += tsize = sizeof(MDB_ntxn);
3084 } else if (flags & MDB_RDONLY) {
3085 size = env->me_maxdbs * (sizeof(MDB_db)+1);
3086 size += tsize = sizeof(MDB_txn);
3088 /* Reuse preallocated write txn. However, do not touch it until
3089 * mdb_txn_renew0() succeeds, since it currently may be active.
3094 if ((txn = calloc(1, size)) == NULL) {
3095 DPRINTF(("calloc: %s", strerror(errno)));
3100 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
3101 if (!txn->mt_rpages) {
3105 txn->mt_rpages[0].mid = 0;
3106 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
3109 txn->mt_dbxs = env->me_dbxs; /* static */
3110 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
3111 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
3112 txn->mt_flags = flags;
3117 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
3118 txn->mt_dbiseqs = parent->mt_dbiseqs;
3119 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
3120 if (!txn->mt_u.dirty_list ||
3121 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
3123 free(txn->mt_u.dirty_list);
3127 txn->mt_txnid = parent->mt_txnid;
3128 txn->mt_dirty_room = parent->mt_dirty_room;
3129 txn->mt_u.dirty_list[0].mid = 0;
3130 txn->mt_spill_pgs = NULL;
3131 txn->mt_next_pgno = parent->mt_next_pgno;
3132 parent->mt_flags |= MDB_TXN_HAS_CHILD;
3133 parent->mt_child = txn;
3134 txn->mt_parent = parent;
3135 txn->mt_numdbs = parent->mt_numdbs;
3137 txn->mt_rpages = parent->mt_rpages;
3139 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3140 /* Copy parent's mt_dbflags, but clear DB_NEW */
3141 for (i=0; i<txn->mt_numdbs; i++)
3142 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
3144 ntxn = (MDB_ntxn *)txn;
3145 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
3146 if (env->me_pghead) {
3147 size = MDB_IDL_SIZEOF(env->me_pghead);
3148 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
3150 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
3155 rc = mdb_cursor_shadow(parent, txn);
3157 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
3158 } else { /* MDB_RDONLY */
3159 txn->mt_dbiseqs = env->me_dbiseqs;
3161 rc = mdb_txn_renew0(txn);
3164 if (txn != env->me_txn0) {
3166 free(txn->mt_rpages);
3171 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
3173 DPRINTF(("begin txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3174 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
3175 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
3182 mdb_txn_env(MDB_txn *txn)
3184 if(!txn) return NULL;
3189 mdb_txn_id(MDB_txn *txn)
3192 return txn->mt_txnid;
3195 /** Export or close DBI handles opened in this txn. */
3197 mdb_dbis_update(MDB_txn *txn, int keep)
3200 MDB_dbi n = txn->mt_numdbs;
3201 MDB_env *env = txn->mt_env;
3202 unsigned char *tdbflags = txn->mt_dbflags;
3204 for (i = n; --i >= CORE_DBS;) {
3205 if (tdbflags[i] & DB_NEW) {
3207 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
3209 char *ptr = env->me_dbxs[i].md_name.mv_data;
3211 env->me_dbxs[i].md_name.mv_data = NULL;
3212 env->me_dbxs[i].md_name.mv_size = 0;
3213 env->me_dbflags[i] = 0;
3214 env->me_dbiseqs[i]++;
3220 if (keep && env->me_numdbs < n)
3224 /** End a transaction, except successful commit of a nested transaction.
3225 * May be called twice for readonly txns: First reset it, then abort.
3226 * @param[in] txn the transaction handle to end
3227 * @param[in] mode why and how to end the transaction
3230 mdb_txn_end(MDB_txn *txn, unsigned mode)
3232 MDB_env *env = txn->mt_env;
3234 static const char *const names[] = MDB_END_NAMES;
3237 /* Export or close DBI handles opened in this txn */
3238 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
3240 DPRINTF(("%s txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3241 names[mode & MDB_END_OPMASK],
3242 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
3243 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
3245 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3246 if (txn->mt_u.reader) {
3247 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
3248 if (!(env->me_flags & MDB_NOTLS)) {
3249 txn->mt_u.reader = NULL; /* txn does not own reader */
3250 } else if (mode & MDB_END_SLOT) {
3251 txn->mt_u.reader->mr_pid = 0;
3252 txn->mt_u.reader = NULL;
3253 } /* else txn owns the slot until it does MDB_END_SLOT */
3255 txn->mt_numdbs = 0; /* prevent further DBI activity */
3256 txn->mt_flags |= MDB_TXN_FINISHED;
3258 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
3259 pgno_t *pghead = env->me_pghead;
3261 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
3262 mdb_cursors_close(txn, 0);
3263 if (!(env->me_flags & MDB_WRITEMAP)) {
3264 mdb_dlist_free(txn);
3268 txn->mt_flags = MDB_TXN_FINISHED;
3270 if (!txn->mt_parent) {
3271 mdb_midl_shrink(&txn->mt_free_pgs);
3272 env->me_free_pgs = txn->mt_free_pgs;
3274 env->me_pghead = NULL;
3278 mode = 0; /* txn == env->me_txn0, do not free() it */
3280 /* The writer mutex was locked in mdb_txn_begin. */
3282 UNLOCK_MUTEX(env->me_wmutex);
3284 txn->mt_parent->mt_child = NULL;
3285 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
3286 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
3287 mdb_midl_free(txn->mt_free_pgs);
3288 mdb_midl_free(txn->mt_spill_pgs);
3289 free(txn->mt_u.dirty_list);
3292 mdb_midl_free(pghead);
3295 if (!txn->mt_parent) {
3296 MDB_ID3L el = env->me_rpages, tl = txn->mt_rpages;
3297 unsigned i, x, n = tl[0].mid;
3298 pthread_mutex_lock(&env->me_rpmutex);
3299 for (i = 1; i <= n; i++) {
3300 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
3301 /* tmp overflow pages that we didn't share in env */
3302 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3304 x = mdb_mid3l_search(el, tl[i].mid);
3305 if (tl[i].mptr == el[x].mptr) {
3308 /* another tmp overflow page */
3309 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3313 pthread_mutex_unlock(&env->me_rpmutex);
3315 if (mode & MDB_END_FREE)
3319 if (mode & MDB_END_FREE)
3324 mdb_txn_reset(MDB_txn *txn)
3329 /* This call is only valid for read-only txns */
3330 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3333 mdb_txn_end(txn, MDB_END_RESET);
3337 mdb_txn_abort(MDB_txn *txn)
3343 mdb_txn_abort(txn->mt_child);
3345 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3348 /** Save the freelist as of this transaction to the freeDB.
3349 * This changes the freelist. Keep trying until it stabilizes.
3351 * When (MDB_DEVEL) & 2, the changes do not affect #mdb_page_alloc(),
3352 * it then uses the transaction's original snapshot of the freeDB.
3355 mdb_freelist_save(MDB_txn *txn)
3357 /* env->me_pghead[] can grow and shrink during this call.
3358 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3359 * Page numbers cannot disappear from txn->mt_free_pgs[].
3362 MDB_env *env = txn->mt_env;
3363 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3364 txnid_t pglast = 0, head_id = 0;
3365 pgno_t freecnt = 0, *free_pgs, *mop;
3366 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3368 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3370 if (env->me_pghead) {
3371 /* Make sure first page of freeDB is touched and on freelist */
3372 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3373 if (rc && rc != MDB_NOTFOUND)
3377 if (!env->me_pghead && txn->mt_loose_pgs) {
3378 /* Put loose page numbers in mt_free_pgs, since
3379 * we may be unable to return them to me_pghead.
3381 MDB_page *mp = txn->mt_loose_pgs;
3382 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3384 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3385 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3386 txn->mt_loose_pgs = NULL;
3387 txn->mt_loose_count = 0;
3390 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3391 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3392 ? SSIZE_MAX : maxfree_1pg;
3395 /* Come back here after each Put() in case freelist changed */
3400 /* If using records from freeDB which we have not yet
3401 * deleted, delete them and any we reserved for me_pghead.
3403 while (pglast < env->me_pglast) {
3404 rc = mdb_cursor_first(&mc, &key, NULL);
3407 pglast = head_id = *(txnid_t *)key.mv_data;
3408 total_room = head_room = 0;
3409 mdb_tassert(txn, pglast <= env->me_pglast);
3410 rc = mdb_cursor_del(&mc, 0);
3415 /* Save the IDL of pages freed by this txn, to a single record */
3416 if (freecnt < txn->mt_free_pgs[0]) {
3418 /* Make sure last page of freeDB is touched and on freelist */
3419 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3420 if (rc && rc != MDB_NOTFOUND)
3423 free_pgs = txn->mt_free_pgs;
3424 /* Write to last page of freeDB */
3425 key.mv_size = sizeof(txn->mt_txnid);
3426 key.mv_data = &txn->mt_txnid;
3428 freecnt = free_pgs[0];
3429 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3430 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3433 /* Retry if mt_free_pgs[] grew during the Put() */
3434 free_pgs = txn->mt_free_pgs;
3435 } while (freecnt < free_pgs[0]);
3436 mdb_midl_sort(free_pgs);
3437 memcpy(data.mv_data, free_pgs, data.mv_size);
3440 unsigned int i = free_pgs[0];
3441 DPRINTF(("IDL write txn %"Yu" root %"Yu" num %u",
3442 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3444 DPRINTF(("IDL %"Yu, free_pgs[i]));
3450 mop = env->me_pghead;
3451 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3453 /* Reserve records for me_pghead[]. Split it if multi-page,
3454 * to avoid searching freeDB for a page range. Use keys in
3455 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3457 if (total_room >= mop_len) {
3458 if (total_room == mop_len || --more < 0)
3460 } else if (head_room >= maxfree_1pg && head_id > 1) {
3461 /* Keep current record (overflow page), add a new one */
3465 /* (Re)write {key = head_id, IDL length = head_room} */
3466 total_room -= head_room;
3467 head_room = mop_len - total_room;
3468 if (head_room > maxfree_1pg && head_id > 1) {
3469 /* Overflow multi-page for part of me_pghead */
3470 head_room /= head_id; /* amortize page sizes */
3471 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3472 } else if (head_room < 0) {
3473 /* Rare case, not bothering to delete this record */
3476 key.mv_size = sizeof(head_id);
3477 key.mv_data = &head_id;
3478 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3479 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3482 /* IDL is initially empty, zero out at least the length */
3483 pgs = (pgno_t *)data.mv_data;
3484 j = head_room > clean_limit ? head_room : 0;
3488 total_room += head_room;
3491 /* Return loose page numbers to me_pghead, though usually none are
3492 * left at this point. The pages themselves remain in dirty_list.
3494 if (txn->mt_loose_pgs) {
3495 MDB_page *mp = txn->mt_loose_pgs;
3496 unsigned count = txn->mt_loose_count;
3498 /* Room for loose pages + temp IDL with same */
3499 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3501 mop = env->me_pghead;
3502 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3503 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3504 loose[ ++count ] = mp->mp_pgno;
3506 mdb_midl_sort(loose);
3507 mdb_midl_xmerge(mop, loose);
3508 txn->mt_loose_pgs = NULL;
3509 txn->mt_loose_count = 0;
3513 /* Fill in the reserved me_pghead records */
3519 rc = mdb_cursor_first(&mc, &key, &data);
3520 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3521 txnid_t id = *(txnid_t *)key.mv_data;
3522 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3525 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3527 if (len > mop_len) {
3529 data.mv_size = (len + 1) * sizeof(MDB_ID);
3531 data.mv_data = mop -= len;
3534 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3536 if (rc || !(mop_len -= len))
3543 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3544 * @param[in] txn the transaction that's being committed
3545 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3546 * @return 0 on success, non-zero on failure.
3549 mdb_page_flush(MDB_txn *txn, int keep)
3551 MDB_env *env = txn->mt_env;
3552 MDB_ID2L dl = txn->mt_u.dirty_list;
3553 unsigned psize = env->me_psize, j;
3554 int i, pagecount = dl[0].mid, rc;
3558 MDB_page *dp = NULL;
3562 struct iovec iov[MDB_COMMIT_PAGES];
3563 ssize_t wsize = 0, wres;
3564 off_t wpos = 0, next_pos = 1; /* impossible pos, so pos != next_pos */
3570 if (env->me_flags & MDB_WRITEMAP) {
3571 /* Clear dirty flags */
3572 while (++i <= pagecount) {
3574 /* Don't flush this page yet */
3575 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3576 dp->mp_flags &= ~P_KEEP;
3580 dp->mp_flags &= ~P_DIRTY;
3585 /* Write the pages */
3587 if (++i <= pagecount) {
3589 /* Don't flush this page yet */
3590 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3591 dp->mp_flags &= ~P_KEEP;
3596 /* clear dirty flag */
3597 dp->mp_flags &= ~P_DIRTY;
3600 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3605 /* Windows actually supports scatter/gather I/O, but only on
3606 * unbuffered file handles. Since we're relying on the OS page
3607 * cache for all our data, that's self-defeating. So we just
3608 * write pages one at a time. We use the ov structure to set
3609 * the write offset, to at least save the overhead of a Seek
3612 DPRINTF(("committing page %"Yu, pgno));
3613 memset(&ov, 0, sizeof(ov));
3614 ov.Offset = pos & 0xffffffff;
3615 ov.OffsetHigh = pos >> 16 >> 16;
3616 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3618 DPRINTF(("WriteFile: %d", rc));
3622 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3623 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3626 /* Write previous page(s) */
3627 #ifdef MDB_USE_PWRITEV
3628 wres = pwritev(env->me_fd, iov, n, wpos);
3631 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3634 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3638 DPRINTF(("lseek: %s", strerror(rc)));
3641 wres = writev(env->me_fd, iov, n);
3644 if (wres != wsize) {
3649 DPRINTF(("Write error: %s", strerror(rc)));
3651 rc = EIO; /* TODO: Use which error code? */
3652 DPUTS("short write, filesystem full?");
3663 DPRINTF(("committing page %"Yu, pgno));
3664 next_pos = pos + size;
3665 iov[n].iov_len = size;
3666 iov[n].iov_base = (char *)dp;
3672 if (pgno > txn->mt_last_pgno)
3673 txn->mt_last_pgno = pgno;
3676 /* MIPS has cache coherency issues, this is a no-op everywhere else
3677 * Note: for any size >= on-chip cache size, entire on-chip cache is
3680 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3682 for (i = keep; ++i <= pagecount; ) {
3684 /* This is a page we skipped above */
3687 dl[j].mid = dp->mp_pgno;
3690 mdb_dpage_free(env, dp);
3695 txn->mt_dirty_room += i - j;
3701 mdb_txn_commit(MDB_txn *txn)
3704 unsigned int i, end_mode;
3710 /* mdb_txn_end() mode for a commit which writes nothing */
3711 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3713 if (txn->mt_child) {
3714 rc = mdb_txn_commit(txn->mt_child);
3721 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3725 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3726 DPUTS("txn has failed/finished, can't commit");
3728 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3733 if (txn->mt_parent) {
3734 MDB_txn *parent = txn->mt_parent;
3738 unsigned x, y, len, ps_len;
3740 /* Append our free list to parent's */
3741 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3744 mdb_midl_free(txn->mt_free_pgs);
3745 /* Failures after this must either undo the changes
3746 * to the parent or set MDB_TXN_ERROR in the parent.
3749 parent->mt_next_pgno = txn->mt_next_pgno;
3750 parent->mt_flags = txn->mt_flags;
3752 /* Merge our cursors into parent's and close them */
3753 mdb_cursors_close(txn, 1);
3755 /* Update parent's DB table. */
3756 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3757 parent->mt_numdbs = txn->mt_numdbs;
3758 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3759 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3760 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3761 /* preserve parent's DB_NEW status */
3762 x = parent->mt_dbflags[i] & DB_NEW;
3763 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3766 dst = parent->mt_u.dirty_list;
3767 src = txn->mt_u.dirty_list;
3768 /* Remove anything in our dirty list from parent's spill list */
3769 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3771 pspill[0] = (pgno_t)-1;
3772 /* Mark our dirty pages as deleted in parent spill list */
3773 for (i=0, len=src[0].mid; ++i <= len; ) {
3774 MDB_ID pn = src[i].mid << 1;
3775 while (pn > pspill[x])
3777 if (pn == pspill[x]) {
3782 /* Squash deleted pagenums if we deleted any */
3783 for (x=y; ++x <= ps_len; )
3784 if (!(pspill[x] & 1))
3785 pspill[++y] = pspill[x];
3789 /* Remove anything in our spill list from parent's dirty list */
3790 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3791 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3792 MDB_ID pn = txn->mt_spill_pgs[i];
3794 continue; /* deleted spillpg */
3796 y = mdb_mid2l_search(dst, pn);
3797 if (y <= dst[0].mid && dst[y].mid == pn) {
3799 while (y < dst[0].mid) {
3808 /* Find len = length of merging our dirty list with parent's */
3810 dst[0].mid = 0; /* simplify loops */
3811 if (parent->mt_parent) {
3812 len = x + src[0].mid;
3813 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3814 for (i = x; y && i; y--) {
3815 pgno_t yp = src[y].mid;
3816 while (yp < dst[i].mid)
3818 if (yp == dst[i].mid) {
3823 } else { /* Simplify the above for single-ancestor case */
3824 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3826 /* Merge our dirty list with parent's */
3828 for (i = len; y; dst[i--] = src[y--]) {
3829 pgno_t yp = src[y].mid;
3830 while (yp < dst[x].mid)
3831 dst[i--] = dst[x--];
3832 if (yp == dst[x].mid)
3833 free(dst[x--].mptr);
3835 mdb_tassert(txn, i == x);
3837 free(txn->mt_u.dirty_list);
3838 parent->mt_dirty_room = txn->mt_dirty_room;
3839 if (txn->mt_spill_pgs) {
3840 if (parent->mt_spill_pgs) {
3841 /* TODO: Prevent failure here, so parent does not fail */
3842 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3844 parent->mt_flags |= MDB_TXN_ERROR;
3845 mdb_midl_free(txn->mt_spill_pgs);
3846 mdb_midl_sort(parent->mt_spill_pgs);
3848 parent->mt_spill_pgs = txn->mt_spill_pgs;
3852 /* Append our loose page list to parent's */
3853 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3855 *lp = txn->mt_loose_pgs;
3856 parent->mt_loose_count += txn->mt_loose_count;
3858 parent->mt_child = NULL;
3859 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3864 if (txn != env->me_txn) {
3865 DPUTS("attempt to commit unknown transaction");
3870 mdb_cursors_close(txn, 0);
3872 if (!txn->mt_u.dirty_list[0].mid &&
3873 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3876 DPRINTF(("committing txn %"Yu" %p on mdbenv %p, root page %"Yu,
3877 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3879 /* Update DB root pointers */
3880 if (txn->mt_numdbs > CORE_DBS) {
3884 data.mv_size = sizeof(MDB_db);
3886 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3887 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3888 if (txn->mt_dbflags[i] & DB_DIRTY) {
3889 if (TXN_DBI_CHANGED(txn, i)) {
3893 data.mv_data = &txn->mt_dbs[i];
3894 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3902 rc = mdb_freelist_save(txn);
3906 mdb_midl_free(env->me_pghead);
3907 env->me_pghead = NULL;
3908 mdb_midl_shrink(&txn->mt_free_pgs);
3914 if ((rc = mdb_page_flush(txn, 0)))
3916 if (!F_ISSET(txn->mt_flags, MDB_TXN_NOSYNC) &&
3917 (rc = mdb_env_sync0(env, 0, txn->mt_next_pgno)))
3919 if ((rc = mdb_env_write_meta(txn)))
3921 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3924 mdb_txn_end(txn, end_mode);
3932 /** Read the environment parameters of a DB environment before
3933 * mapping it into memory.
3934 * @param[in] env the environment handle
3935 * @param[out] meta address of where to store the meta information
3936 * @return 0 on success, non-zero on failure.
3939 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3945 enum { Size = sizeof(pbuf) };
3947 /* We don't know the page size yet, so use a minimum value.
3948 * Read both meta pages so we can use the latest one.
3951 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3955 memset(&ov, 0, sizeof(ov));
3957 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3958 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3961 rc = pread(env->me_fd, &pbuf, Size, off);
3964 if (rc == 0 && off == 0)
3966 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3967 DPRINTF(("read: %s", mdb_strerror(rc)));
3971 p = (MDB_page *)&pbuf;
3973 if (!F_ISSET(p->mp_flags, P_META)) {
3974 DPRINTF(("page %"Yu" not a meta page", p->mp_pgno));
3979 if (m->mm_magic != MDB_MAGIC) {
3980 DPUTS("meta has invalid magic");
3984 if (m->mm_version != MDB_DATA_VERSION) {
3985 DPRINTF(("database is version %u, expected version %u",
3986 m->mm_version, MDB_DATA_VERSION));
3987 return MDB_VERSION_MISMATCH;
3990 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3996 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3998 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
4000 meta->mm_magic = MDB_MAGIC;
4001 meta->mm_version = MDB_DATA_VERSION;
4002 meta->mm_mapsize = env->me_mapsize;
4003 meta->mm_psize = env->me_psize;
4004 meta->mm_last_pg = NUM_METAS-1;
4005 meta->mm_flags = env->me_flags & 0xffff;
4006 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
4007 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
4008 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
4011 /** Write the environment parameters of a freshly created DB environment.
4012 * @param[in] env the environment handle
4013 * @param[in] meta the #MDB_meta to write
4014 * @return 0 on success, non-zero on failure.
4017 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
4025 memset(&ov, 0, sizeof(ov));
4026 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
4028 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
4031 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
4032 len = pwrite(fd, ptr, size, pos); \
4033 if (len == -1 && ErrCode() == EINTR) continue; \
4034 rc = (len >= 0); break; } while(1)
4037 DPUTS("writing new meta page");
4039 psize = env->me_psize;
4041 p = calloc(NUM_METAS, psize);
4045 p->mp_flags = P_META;
4046 *(MDB_meta *)METADATA(p) = *meta;
4048 q = (MDB_page *)((char *)p + psize);
4050 q->mp_flags = P_META;
4051 *(MDB_meta *)METADATA(q) = *meta;
4053 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
4056 else if ((unsigned) len == psize * NUM_METAS)
4064 /** Update the environment info to commit a transaction.
4065 * @param[in] txn the transaction that's being committed
4066 * @return 0 on success, non-zero on failure.
4069 mdb_env_write_meta(MDB_txn *txn)
4072 MDB_meta meta, metab, *mp;
4076 int rc, len, toggle;
4085 toggle = txn->mt_txnid & 1;
4086 DPRINTF(("writing meta page %d for root page %"Yu,
4087 toggle, txn->mt_dbs[MAIN_DBI].md_root));
4090 flags = txn->mt_flags | env->me_flags;
4091 mp = env->me_metas[toggle];
4092 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
4093 /* Persist any increases of mapsize config */
4094 if (mapsize < env->me_mapsize)
4095 mapsize = env->me_mapsize;
4097 if (flags & MDB_WRITEMAP) {
4098 mp->mm_mapsize = mapsize;
4099 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4100 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4101 mp->mm_last_pg = txn->mt_next_pgno - 1;
4102 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
4103 !(defined(__i386__) || defined(__x86_64__))
4104 /* LY: issue a memory barrier, if not x86. ITS#7969 */
4105 __sync_synchronize();
4107 mp->mm_txnid = txn->mt_txnid;
4108 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
4109 unsigned meta_size = env->me_psize;
4110 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
4111 ptr = (char *)mp - PAGEHDRSZ;
4112 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
4113 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
4117 if (MDB_MSYNC(ptr, meta_size, rc)) {
4124 metab.mm_txnid = mp->mm_txnid;
4125 metab.mm_last_pg = mp->mm_last_pg;
4127 meta.mm_mapsize = mapsize;
4128 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4129 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4130 meta.mm_last_pg = txn->mt_next_pgno - 1;
4131 meta.mm_txnid = txn->mt_txnid;
4133 off = offsetof(MDB_meta, mm_mapsize);
4134 ptr = (char *)&meta + off;
4135 len = sizeof(MDB_meta) - off;
4136 off += (char *)mp - env->me_map;
4138 /* Write to the SYNC fd unless MDB_NOSYNC/MDB_NOMETASYNC.
4139 * (me_mfd goes to the same file as me_fd, but writing to it
4140 * also syncs to disk. Avoids a separate fdatasync() call.)
4142 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
4145 memset(&ov, 0, sizeof(ov));
4147 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
4152 rc = pwrite(mfd, ptr, len, off);
4155 rc = rc < 0 ? ErrCode() : EIO;
4160 DPUTS("write failed, disk error?");
4161 /* On a failure, the pagecache still contains the new data.
4162 * Write some old data back, to prevent it from being used.
4163 * Use the non-SYNC fd; we know it will fail anyway.
4165 meta.mm_last_pg = metab.mm_last_pg;
4166 meta.mm_txnid = metab.mm_txnid;
4168 memset(&ov, 0, sizeof(ov));
4170 WriteFile(env->me_fd, ptr, len, NULL, &ov);
4172 r2 = pwrite(env->me_fd, ptr, len, off);
4173 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
4176 env->me_flags |= MDB_FATAL_ERROR;
4179 /* MIPS has cache coherency issues, this is a no-op everywhere else */
4180 CACHEFLUSH(env->me_map + off, len, DCACHE);
4182 /* Memory ordering issues are irrelevant; since the entire writer
4183 * is wrapped by wmutex, all of these changes will become visible
4184 * after the wmutex is unlocked. Since the DB is multi-version,
4185 * readers will get consistent data regardless of how fresh or
4186 * how stale their view of these values is.
4189 env->me_txns->mti_txnid = txn->mt_txnid;
4194 /** Check both meta pages to see which one is newer.
4195 * @param[in] env the environment handle
4196 * @return newest #MDB_meta.
4199 mdb_env_pick_meta(const MDB_env *env)
4201 MDB_meta *const *metas = env->me_metas;
4202 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
4206 mdb_env_create(MDB_env **env)
4210 e = calloc(1, sizeof(MDB_env));
4214 e->me_maxreaders = DEFAULT_READERS;
4215 e->me_maxdbs = e->me_numdbs = CORE_DBS;
4216 e->me_fd = INVALID_HANDLE_VALUE;
4217 e->me_lfd = INVALID_HANDLE_VALUE;
4218 e->me_mfd = INVALID_HANDLE_VALUE;
4219 #ifdef MDB_USE_POSIX_SEM
4220 e->me_rmutex = SEM_FAILED;
4221 e->me_wmutex = SEM_FAILED;
4222 #elif defined MDB_USE_SYSV_SEM
4223 e->me_rmutex->semid = -1;
4224 e->me_wmutex->semid = -1;
4226 e->me_pid = getpid();
4227 GET_PAGESIZE(e->me_os_psize);
4228 VGMEMP_CREATE(e,0,0);
4234 /** @brief Map a result from an NTAPI call to WIN32. */
4236 mdb_nt2win32(NTSTATUS st)
4241 GetOverlappedResult(NULL, &o, &br, FALSE);
4242 return GetLastError();
4247 mdb_env_map(MDB_env *env, void *addr)
4250 unsigned int flags = env->me_flags;
4253 int access = SECTION_MAP_READ;
4257 ULONG pageprot = PAGE_READONLY, secprot, alloctype;
4259 if (flags & MDB_WRITEMAP) {
4260 access |= SECTION_MAP_WRITE;
4261 pageprot = PAGE_READWRITE;
4263 if (flags & MDB_RDONLY) {
4264 secprot = PAGE_READONLY;
4268 secprot = PAGE_READWRITE;
4269 msize = env->me_mapsize;
4270 alloctype = MEM_RESERVE;
4273 rc = NtCreateSection(&mh, access, NULL, NULL, secprot, SEC_RESERVE, env->me_fd);
4275 return mdb_nt2win32(rc);
4278 msize = NUM_METAS * env->me_psize;
4280 rc = NtMapViewOfSection(mh, GetCurrentProcess(), &map, 0, 0, NULL, &msize, ViewUnmap, alloctype, pageprot);
4287 return mdb_nt2win32(rc);
4292 env->me_map = mmap(addr, NUM_METAS * env->me_psize, PROT_READ, MAP_SHARED,
4294 if (env->me_map == MAP_FAILED) {
4299 int prot = PROT_READ;
4300 if (flags & MDB_WRITEMAP) {
4302 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
4305 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
4307 if (env->me_map == MAP_FAILED) {
4312 if (flags & MDB_NORDAHEAD) {
4313 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
4315 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
4317 #ifdef POSIX_MADV_RANDOM
4318 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
4319 #endif /* POSIX_MADV_RANDOM */
4320 #endif /* MADV_RANDOM */
4324 /* Can happen because the address argument to mmap() is just a
4325 * hint. mmap() can pick another, e.g. if the range is in use.
4326 * The MAP_FIXED flag would prevent that, but then mmap could
4327 * instead unmap existing pages to make room for the new map.
4329 if (addr && env->me_map != addr)
4330 return EBUSY; /* TODO: Make a new MDB_* error code? */
4333 p = (MDB_page *)env->me_map;
4334 env->me_metas[0] = METADATA(p);
4335 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
4341 mdb_env_set_mapsize(MDB_env *env, mdb_size_t size)
4343 /* If env is already open, caller is responsible for making
4344 * sure there are no active txns.
4354 meta = mdb_env_pick_meta(env);
4356 size = meta->mm_mapsize;
4358 /* Silently round up to minimum if the size is too small */
4359 mdb_size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
4364 /* For MDB_VL32 this bit is a noop since we dynamically remap
4365 * chunks of the DB anyway.
4367 munmap(env->me_map, env->me_mapsize);
4368 env->me_mapsize = size;
4369 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4370 rc = mdb_env_map(env, old);
4373 #endif /* !MDB_VL32 */
4375 env->me_mapsize = size;
4377 env->me_maxpg = env->me_mapsize / env->me_psize;
4382 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4386 env->me_maxdbs = dbs + CORE_DBS;
4391 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4393 if (env->me_map || readers < 1)
4395 env->me_maxreaders = readers;
4400 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4402 if (!env || !readers)
4404 *readers = env->me_maxreaders;
4409 mdb_fsize(HANDLE fd, mdb_size_t *size)
4412 LARGE_INTEGER fsize;
4414 if (!GetFileSizeEx(fd, &fsize))
4417 *size = fsize.QuadPart;
4431 typedef wchar_t mdb_nchar_t;
4432 # define MDB_NAME(str) L##str
4433 # define mdb_name_cpy wcscpy
4435 /** Character type for file names: char on Unix, wchar_t on Windows */
4436 typedef char mdb_nchar_t;
4437 # define MDB_NAME(str) str /**< #mdb_nchar_t[] string literal */
4438 # define mdb_name_cpy strcpy /**< Copy name (#mdb_nchar_t string) */
4441 /** Filename - string of #mdb_nchar_t[] */
4442 typedef struct MDB_name {
4443 int mn_len; /**< Length */
4444 int mn_alloced; /**< True if #mn_val was malloced */
4445 mdb_nchar_t *mn_val; /**< Contents */
4448 /** Filename suffixes [datafile,lockfile][without,with MDB_NOSUBDIR] */
4449 static const mdb_nchar_t *const mdb_suffixes[2][2] = {
4450 { MDB_NAME("/data.mdb"), MDB_NAME("") },
4451 { MDB_NAME("/lock.mdb"), MDB_NAME("-lock") }
4454 #define MDB_SUFFLEN 9 /**< Max string length in #mdb_suffixes[] */
4456 /** Set up filename + scratch area for filename suffix, for opening files.
4457 * It should be freed with #mdb_fname_destroy().
4458 * On Windows, paths are converted from char *UTF-8 to wchar_t *UTF-16.
4460 * @param[in] path Pathname for #mdb_env_open().
4461 * @param[in] envflags Whether a subdir and/or lockfile will be used.
4462 * @param[out] fname Resulting filename, with room for a suffix if necessary.
4465 mdb_fname_init(const char *path, unsigned envflags, MDB_name *fname)
4467 int no_suffix = F_ISSET(envflags, MDB_NOSUBDIR|MDB_NOLOCK);
4468 fname->mn_alloced = 0;
4470 return utf8_to_utf16(path, fname, no_suffix ? 0 : MDB_SUFFLEN);
4472 fname->mn_len = strlen(path);
4474 fname->mn_val = (char *) path;
4475 else if ((fname->mn_val = malloc(fname->mn_len + MDB_SUFFLEN+1)) != NULL) {
4476 fname->mn_alloced = 1;
4477 strcpy(fname->mn_val, path);
4485 /** Destroy \b fname from #mdb_fname_init() */
4486 #define mdb_fname_destroy(fname) \
4487 do { if ((fname).mn_alloced) free((fname).mn_val); } while (0)
4489 #ifdef O_CLOEXEC /* POSIX.1-2008: Set FD_CLOEXEC atomically at open() */
4490 # define MDB_CLOEXEC O_CLOEXEC
4492 # define MDB_CLOEXEC 0
4495 /** File type, access mode etc. for #mdb_fopen() */
4496 enum mdb_fopen_type {
4498 MDB_O_RDONLY, MDB_O_RDWR, MDB_O_META, MDB_O_COPY, MDB_O_LOCKS
4500 /* A comment in mdb_fopen() explains some O_* flag choices. */
4501 MDB_O_RDONLY= O_RDONLY, /**< for RDONLY me_fd */
4502 MDB_O_RDWR = O_RDWR |O_CREAT, /**< for me_fd */
4503 MDB_O_META = O_WRONLY|MDB_DSYNC |MDB_CLOEXEC, /**< for me_mfd */
4504 MDB_O_COPY = O_WRONLY|O_CREAT|O_EXCL|MDB_CLOEXEC, /**< for #mdb_env_copy() */
4505 /** Bitmask for open() flags in enum #mdb_fopen_type. The other bits
4506 * distinguish otherwise-equal MDB_O_* constants from each other.
4508 MDB_O_MASK = MDB_O_RDWR|MDB_CLOEXEC | MDB_O_RDONLY|MDB_O_META|MDB_O_COPY,
4509 MDB_O_LOCKS = MDB_O_RDWR|MDB_CLOEXEC | ((MDB_O_MASK+1) & ~MDB_O_MASK) /**< for me_lfd */
4513 /** Open an LMDB file.
4514 * @param[in] env The LMDB environment.
4515 * @param[in,out] fname Path from from #mdb_fname_init(). A suffix is
4516 * appended if necessary to create the filename, without changing mn_len.
4517 * @param[in] which Determines file type, access mode, etc.
4518 * @param[in] mode The Unix permissions for the file, if we create it.
4519 * @param[out] res Resulting file handle.
4520 * @return 0 on success, non-zero on failure.
4523 mdb_fopen(const MDB_env *env, MDB_name *fname,
4524 enum mdb_fopen_type which, mdb_mode_t mode,
4527 int rc = MDB_SUCCESS;
4530 DWORD acc, share, disp, attrs;
4535 if (fname->mn_alloced) /* modifiable copy */
4536 mdb_name_cpy(fname->mn_val + fname->mn_len,
4537 mdb_suffixes[which==MDB_O_LOCKS][F_ISSET(env->me_flags, MDB_NOSUBDIR)]);
4539 /* The directory must already exist. Usually the file need not.
4540 * MDB_O_META requires the file because we already created it using
4541 * MDB_O_RDWR. MDB_O_COPY must not overwrite an existing file.
4543 * With MDB_O_COPY we do not want the OS to cache the writes, since
4544 * the source data is already in the OS cache.
4546 * The lockfile needs FD_CLOEXEC (close file descriptor on exec*())
4547 * to avoid the flock() issues noted under Caveats in lmdb.h.
4548 * Also set it for other filehandles which the user cannot get at
4549 * and close himself, which he may need after fork(). I.e. all but
4550 * me_fd, which programs do use via mdb_env_get_fd().
4554 acc = GENERIC_READ|GENERIC_WRITE;
4555 share = FILE_SHARE_READ|FILE_SHARE_WRITE;
4557 attrs = FILE_ATTRIBUTE_NORMAL;
4559 case MDB_O_RDONLY: /* read-only datafile */
4561 disp = OPEN_EXISTING;
4563 case MDB_O_META: /* for writing metapages */
4564 acc = GENERIC_WRITE;
4565 disp = OPEN_EXISTING;
4566 attrs = FILE_ATTRIBUTE_NORMAL|FILE_FLAG_WRITE_THROUGH;
4568 case MDB_O_COPY: /* mdb_env_copy() & co */
4569 acc = GENERIC_WRITE;
4572 attrs = FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH;
4574 default: break; /* silence gcc -Wswitch (not all enum values handled) */
4576 fd = CreateFileW(fname->mn_val, acc, share, NULL, disp, attrs, NULL);
4578 fd = open(fname->mn_val, which & MDB_O_MASK, mode);
4581 if (fd == INVALID_HANDLE_VALUE)
4585 if (which != MDB_O_RDONLY && which != MDB_O_RDWR) {
4586 /* Set CLOEXEC if we could not pass it to open() */
4587 if (!MDB_CLOEXEC && (flags = fcntl(fd, F_GETFD)) != -1)
4588 (void) fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
4590 if (which == MDB_O_COPY && env->me_psize >= env->me_os_psize) {
4591 /* This may require buffer alignment. There is no portable
4592 * way to ask how much, so we require OS pagesize alignment.
4594 # ifdef F_NOCACHE /* __APPLE__ */
4595 (void) fcntl(fd, F_NOCACHE, 1);
4596 # elif defined O_DIRECT
4597 /* open(...O_DIRECT...) would break on filesystems without
4598 * O_DIRECT support (ITS#7682). Try to set it here instead.
4600 if ((flags = fcntl(fd, F_GETFL)) != -1)
4601 (void) fcntl(fd, F_SETFL, flags | O_DIRECT);
4605 #endif /* !_WIN32 */
4612 #ifdef BROKEN_FDATASYNC
4613 #include <sys/utsname.h>
4614 #include <sys/vfs.h>
4617 /** Further setup required for opening an LMDB environment
4620 mdb_env_open2(MDB_env *env)
4622 unsigned int flags = env->me_flags;
4623 int i, newenv = 0, rc;
4627 /* See if we should use QueryLimited */
4629 if ((rc & 0xff) > 5)
4630 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4632 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4635 #ifdef BROKEN_FDATASYNC
4636 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4637 * https://lkml.org/lkml/2012/9/3/83
4638 * Kernels after 3.6-rc6 are known good.
4639 * https://lkml.org/lkml/2012/9/10/556
4640 * See if the DB is on ext3/ext4, then check for new enough kernel
4641 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4646 fstatfs(env->me_fd, &st);
4647 while (st.f_type == 0xEF53) {
4651 if (uts.release[0] < '3') {
4652 if (!strncmp(uts.release, "2.6.32.", 7)) {
4653 i = atoi(uts.release+7);
4655 break; /* 2.6.32.60 and newer is OK */
4656 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4657 i = atoi(uts.release+7);
4659 break; /* 2.6.34.15 and newer is OK */
4661 } else if (uts.release[0] == '3') {
4662 i = atoi(uts.release+2);
4664 break; /* 3.6 and newer is OK */
4666 i = atoi(uts.release+4);
4668 break; /* 3.5.4 and newer is OK */
4669 } else if (i == 2) {
4670 i = atoi(uts.release+4);
4672 break; /* 3.2.30 and newer is OK */
4674 } else { /* 4.x and newer is OK */
4677 env->me_flags |= MDB_FSYNCONLY;
4683 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4686 DPUTS("new mdbenv");
4688 env->me_psize = env->me_os_psize;
4689 if (env->me_psize > MAX_PAGESIZE)
4690 env->me_psize = MAX_PAGESIZE;
4691 memset(&meta, 0, sizeof(meta));
4692 mdb_env_init_meta0(env, &meta);
4693 meta.mm_mapsize = DEFAULT_MAPSIZE;
4695 env->me_psize = meta.mm_psize;
4698 /* Was a mapsize configured? */
4699 if (!env->me_mapsize) {
4700 env->me_mapsize = meta.mm_mapsize;
4703 /* Make sure mapsize >= committed data size. Even when using
4704 * mm_mapsize, which could be broken in old files (ITS#7789).
4706 mdb_size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4707 if (env->me_mapsize < minsize)
4708 env->me_mapsize = minsize;
4710 meta.mm_mapsize = env->me_mapsize;
4712 if (newenv && !(flags & MDB_FIXEDMAP)) {
4713 /* mdb_env_map() may grow the datafile. Write the metapages
4714 * first, so the file will be valid if initialization fails.
4715 * Except with FIXEDMAP, since we do not yet know mm_address.
4716 * We could fill in mm_address later, but then a different
4717 * program might end up doing that - one with a memory layout
4718 * and map address which does not suit the main program.
4720 rc = mdb_env_init_meta(env, &meta);
4726 /* For FIXEDMAP, make sure the file is non-empty before we attempt to map it */
4730 rc = WriteFile(env->me_fd, &dummy, 1, &len, NULL);
4738 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4743 if (flags & MDB_FIXEDMAP)
4744 meta.mm_address = env->me_map;
4745 i = mdb_env_init_meta(env, &meta);
4746 if (i != MDB_SUCCESS) {
4751 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4752 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4754 #if !(MDB_MAXKEYSIZE)
4755 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4757 env->me_maxpg = env->me_mapsize / env->me_psize;
4761 MDB_meta *meta = mdb_env_pick_meta(env);
4762 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4764 DPRINTF(("opened database version %u, pagesize %u",
4765 meta->mm_version, env->me_psize));
4766 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4767 DPRINTF(("depth: %u", db->md_depth));
4768 DPRINTF(("entries: %"Yu, db->md_entries));
4769 DPRINTF(("branch pages: %"Yu, db->md_branch_pages));
4770 DPRINTF(("leaf pages: %"Yu, db->md_leaf_pages));
4771 DPRINTF(("overflow pages: %"Yu, db->md_overflow_pages));
4772 DPRINTF(("root: %"Yu, db->md_root));
4780 /** Release a reader thread's slot in the reader lock table.
4781 * This function is called automatically when a thread exits.
4782 * @param[in] ptr This points to the slot in the reader lock table.
4785 mdb_env_reader_dest(void *ptr)
4787 MDB_reader *reader = ptr;
4790 if (reader->mr_pid == getpid()) /* catch pthread_exit() in child process */
4792 /* We omit the mutex, so do this atomically (i.e. skip mr_txnid) */
4797 /** Junk for arranging thread-specific callbacks on Windows. This is
4798 * necessarily platform and compiler-specific. Windows supports up
4799 * to 1088 keys. Let's assume nobody opens more than 64 environments
4800 * in a single process, for now. They can override this if needed.
4802 #ifndef MAX_TLS_KEYS
4803 #define MAX_TLS_KEYS 64
4805 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4806 static int mdb_tls_nkeys;
4808 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4812 case DLL_PROCESS_ATTACH: break;
4813 case DLL_THREAD_ATTACH: break;
4814 case DLL_THREAD_DETACH:
4815 for (i=0; i<mdb_tls_nkeys; i++) {
4816 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4818 mdb_env_reader_dest(r);
4822 case DLL_PROCESS_DETACH: break;
4827 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4829 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4833 /* Force some symbol references.
4834 * _tls_used forces the linker to create the TLS directory if not already done
4835 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4837 #pragma comment(linker, "/INCLUDE:_tls_used")
4838 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4839 #pragma const_seg(".CRT$XLB")
4840 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4841 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4844 #pragma comment(linker, "/INCLUDE:__tls_used")
4845 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4846 #pragma data_seg(".CRT$XLB")
4847 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4849 #endif /* WIN 32/64 */
4850 #endif /* !__GNUC__ */
4853 /** Downgrade the exclusive lock on the region back to shared */
4855 mdb_env_share_locks(MDB_env *env, int *excl)
4858 MDB_meta *meta = mdb_env_pick_meta(env);
4860 env->me_txns->mti_txnid = meta->mm_txnid;
4865 /* First acquire a shared lock. The Unlock will
4866 * then release the existing exclusive lock.
4868 memset(&ov, 0, sizeof(ov));
4869 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4872 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4878 struct flock lock_info;
4879 /* The shared lock replaces the existing lock */
4880 memset((void *)&lock_info, 0, sizeof(lock_info));
4881 lock_info.l_type = F_RDLCK;
4882 lock_info.l_whence = SEEK_SET;
4883 lock_info.l_start = 0;
4884 lock_info.l_len = 1;
4885 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4886 (rc = ErrCode()) == EINTR) ;
4887 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4894 /** Try to get exclusive lock, otherwise shared.
4895 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4898 mdb_env_excl_lock(MDB_env *env, int *excl)
4902 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4906 memset(&ov, 0, sizeof(ov));
4907 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4914 struct flock lock_info;
4915 memset((void *)&lock_info, 0, sizeof(lock_info));
4916 lock_info.l_type = F_WRLCK;
4917 lock_info.l_whence = SEEK_SET;
4918 lock_info.l_start = 0;
4919 lock_info.l_len = 1;
4920 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4921 (rc = ErrCode()) == EINTR) ;
4925 # ifndef MDB_USE_POSIX_MUTEX
4926 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4929 lock_info.l_type = F_RDLCK;
4930 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4931 (rc = ErrCode()) == EINTR) ;
4941 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4943 * @(#) $Revision: 5.1 $
4944 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4945 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4947 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4951 * Please do not copyright this code. This code is in the public domain.
4953 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4954 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4955 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4956 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4957 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4958 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4959 * PERFORMANCE OF THIS SOFTWARE.
4962 * chongo <Landon Curt Noll> /\oo/\
4963 * http://www.isthe.com/chongo/
4965 * Share and Enjoy! :-)
4968 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4969 * @param[in] val value to hash
4970 * @param[in] len length of value
4971 * @return 64 bit hash
4974 mdb_hash(const void *val, size_t len)
4976 const unsigned char *s = (const unsigned char *) val, *end = s + len;
4977 mdb_hash_t hval = 0xcbf29ce484222325ULL;
4979 * FNV-1a hash each octet of the buffer
4982 hval = (hval ^ *s++) * 0x100000001b3ULL;
4984 /* return our new hash value */
4988 /** Hash the string and output the encoded hash.
4989 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4990 * very short name limits. We don't care about the encoding being reversible,
4991 * we just want to preserve as many bits of the input as possible in a
4992 * small printable string.
4993 * @param[in] str string to hash
4994 * @param[out] encbuf an array of 11 chars to hold the hash
4996 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4999 mdb_pack85(unsigned long long l, char *out)
5003 for (i=0; i<10 && l; i++) {
5004 *out++ = mdb_a85[l % 85];
5010 /** Init #MDB_env.me_mutexname[] except the char which #MUTEXNAME() will set.
5011 * Changes to this code must be reflected in #MDB_LOCK_FORMAT.
5014 mdb_env_mname_init(MDB_env *env)
5016 char *nm = env->me_mutexname;
5017 strcpy(nm, MUTEXNAME_PREFIX);
5018 mdb_pack85(env->me_txns->mti_mutexid, nm + sizeof(MUTEXNAME_PREFIX));
5021 /** Return env->me_mutexname after filling in ch ('r'/'w') for convenience */
5022 #define MUTEXNAME(env, ch) ( \
5023 (void) ((env)->me_mutexname[sizeof(MUTEXNAME_PREFIX)-1] = (ch)), \
5024 (env)->me_mutexname)
5028 /** Open and/or initialize the lock region for the environment.
5029 * @param[in] env The LMDB environment.
5030 * @param[in] fname Filename + scratch area, from #mdb_fname_init().
5031 * @param[in] mode The Unix permissions for the file, if we create it.
5032 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
5033 * @return 0 on success, non-zero on failure.
5036 mdb_env_setup_locks(MDB_env *env, MDB_name *fname, int mode, int *excl)
5039 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
5041 # define MDB_ERRCODE_ROFS EROFS
5043 #ifdef MDB_USE_SYSV_SEM
5050 rc = mdb_fopen(env, fname, MDB_O_LOCKS, mode, &env->me_lfd);
5052 /* Omit lockfile if read-only env on read-only filesystem */
5053 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
5059 if (!(env->me_flags & MDB_NOTLS)) {
5060 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
5063 env->me_flags |= MDB_ENV_TXKEY;
5065 /* Windows TLS callbacks need help finding their TLS info. */
5066 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
5070 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
5074 /* Try to get exclusive lock. If we succeed, then
5075 * nobody is using the lock region and we should initialize it.
5077 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
5080 size = GetFileSize(env->me_lfd, NULL);
5082 size = lseek(env->me_lfd, 0, SEEK_END);
5083 if (size == -1) goto fail_errno;
5085 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
5086 if (size < rsize && *excl > 0) {
5088 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
5089 || !SetEndOfFile(env->me_lfd))
5092 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
5096 size = rsize - sizeof(MDB_txninfo);
5097 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
5102 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
5104 if (!mh) goto fail_errno;
5105 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
5107 if (!env->me_txns) goto fail_errno;
5109 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
5111 if (m == MAP_FAILED) goto fail_errno;
5117 BY_HANDLE_FILE_INFORMATION stbuf;
5124 if (!mdb_sec_inited) {
5125 InitializeSecurityDescriptor(&mdb_null_sd,
5126 SECURITY_DESCRIPTOR_REVISION);
5127 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
5128 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
5129 mdb_all_sa.bInheritHandle = FALSE;
5130 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
5133 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
5134 idbuf.volume = stbuf.dwVolumeSerialNumber;
5135 idbuf.nhigh = stbuf.nFileIndexHigh;
5136 idbuf.nlow = stbuf.nFileIndexLow;
5137 env->me_txns->mti_mutexid = mdb_hash(&idbuf, sizeof(idbuf));
5138 mdb_env_mname_init(env);
5139 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, MUTEXNAME(env, 'r'));
5140 if (!env->me_rmutex) goto fail_errno;
5141 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, MUTEXNAME(env, 'w'));
5142 if (!env->me_wmutex) goto fail_errno;
5143 #elif defined(MDB_USE_POSIX_SEM)
5150 #if defined(__NetBSD__)
5151 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
5153 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
5154 memset(&idbuf, 0, sizeof(idbuf));
5155 idbuf.dev = stbuf.st_dev;
5156 idbuf.ino = stbuf.st_ino;
5157 env->me_txns->mti_mutexid = mdb_hash(&idbuf, sizeof(idbuf))
5158 #ifdef MDB_SHORT_SEMNAMES
5159 /* Max 9 base85-digits. We truncate here instead of in
5160 * mdb_env_mname_init() to keep the latter portable.
5162 % ((mdb_hash_t)85*85*85*85*85*85*85*85*85)
5165 mdb_env_mname_init(env);
5166 /* Clean up after a previous run, if needed: Try to
5167 * remove both semaphores before doing anything else.
5169 sem_unlink(MUTEXNAME(env, 'r'));
5170 sem_unlink(MUTEXNAME(env, 'w'));
5171 env->me_rmutex = sem_open(MUTEXNAME(env, 'r'), O_CREAT|O_EXCL, mode, 1);
5172 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
5173 env->me_wmutex = sem_open(MUTEXNAME(env, 'w'), O_CREAT|O_EXCL, mode, 1);
5174 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
5175 #elif defined(MDB_USE_SYSV_SEM)
5176 unsigned short vals[2] = {1, 1};
5177 key_t key = ftok(fname->mn_val, 'M'); /* fname is lockfile path now */
5180 semid = semget(key, 2, (mode & 0777) | IPC_CREAT);
5184 if (semctl(semid, 0, SETALL, semu) < 0)
5186 env->me_txns->mti_semid = semid;
5187 env->me_txns->mti_rlocked = 0;
5188 env->me_txns->mti_wlocked = 0;
5189 #else /* MDB_USE_POSIX_MUTEX: */
5190 pthread_mutexattr_t mattr;
5192 /* Solaris needs this before initing a robust mutex. Otherwise
5193 * it may skip the init and return EBUSY "seems someone already
5194 * inited" or EINVAL "it was inited differently".
5196 memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
5197 memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
5199 if ((rc = pthread_mutexattr_init(&mattr)) != 0)
5201 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
5202 #ifdef MDB_ROBUST_SUPPORTED
5203 if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
5205 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
5206 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
5207 pthread_mutexattr_destroy(&mattr);
5210 #endif /* _WIN32 || ... */
5212 env->me_txns->mti_magic = MDB_MAGIC;
5213 env->me_txns->mti_format = MDB_LOCK_FORMAT;
5214 env->me_txns->mti_txnid = 0;
5215 env->me_txns->mti_numreaders = 0;
5218 #ifdef MDB_USE_SYSV_SEM
5219 struct semid_ds buf;
5221 if (env->me_txns->mti_magic != MDB_MAGIC) {
5222 DPUTS("lock region has invalid magic");
5226 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
5227 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
5228 env->me_txns->mti_format, MDB_LOCK_FORMAT));
5229 rc = MDB_VERSION_MISMATCH;
5233 if (rc && rc != EACCES && rc != EAGAIN) {
5237 mdb_env_mname_init(env);
5238 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, MUTEXNAME(env, 'r'));
5239 if (!env->me_rmutex) goto fail_errno;
5240 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, MUTEXNAME(env, 'w'));
5241 if (!env->me_wmutex) goto fail_errno;
5242 #elif defined(MDB_USE_POSIX_SEM)
5243 mdb_env_mname_init(env);
5244 env->me_rmutex = sem_open(MUTEXNAME(env, 'r'), 0);
5245 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
5246 env->me_wmutex = sem_open(MUTEXNAME(env, 'w'), 0);
5247 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
5248 #elif defined(MDB_USE_SYSV_SEM)
5249 semid = env->me_txns->mti_semid;
5251 /* check for read access */
5252 if (semctl(semid, 0, IPC_STAT, semu) < 0)
5254 /* check for write access */
5255 if (semctl(semid, 0, IPC_SET, semu) < 0)
5259 #ifdef MDB_USE_SYSV_SEM
5260 env->me_rmutex->semid = semid;
5261 env->me_wmutex->semid = semid;
5262 env->me_rmutex->semnum = 0;
5263 env->me_wmutex->semnum = 1;
5264 env->me_rmutex->locked = &env->me_txns->mti_rlocked;
5265 env->me_wmutex->locked = &env->me_txns->mti_wlocked;
5276 /** Only a subset of the @ref mdb_env flags can be changed
5277 * at runtime. Changing other flags requires closing the
5278 * environment and re-opening it with the new flags.
5280 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
5281 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
5282 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
5284 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
5285 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
5289 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
5294 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
5298 if (flags & MDB_WRITEMAP) {
5299 /* silently ignore WRITEMAP in 32 bit mode */
5300 flags ^= MDB_WRITEMAP;
5302 if (flags & MDB_FIXEDMAP) {
5303 /* cannot support FIXEDMAP */
5307 flags |= env->me_flags;
5309 rc = mdb_fname_init(path, flags, &fname);
5315 env->me_rpmutex = CreateMutex(NULL, FALSE, NULL);
5316 if (!env->me_rpmutex) {
5321 rc = pthread_mutex_init(&env->me_rpmutex, NULL);
5326 flags |= MDB_ENV_ACTIVE; /* tell mdb_env_close0() to clean up */
5328 if (flags & MDB_RDONLY) {
5329 /* silently ignore WRITEMAP when we're only getting read access */
5330 flags &= ~MDB_WRITEMAP;
5332 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
5333 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
5337 env->me_flags = flags;
5343 env->me_rpages = malloc(MDB_ERPAGE_SIZE * sizeof(MDB_ID3));
5344 if (!env->me_rpages) {
5348 env->me_rpages[0].mid = 0;
5349 env->me_rpcheck = MDB_ERPAGE_SIZE/2;
5353 env->me_path = strdup(path);
5354 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
5355 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
5356 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
5357 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
5361 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
5363 /* For RDONLY, get lockfile after we know datafile exists */
5364 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
5365 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
5370 rc = mdb_fopen(env, &fname,
5371 (flags & MDB_RDONLY) ? MDB_O_RDONLY : MDB_O_RDWR,
5376 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
5377 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
5382 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
5383 if (!(flags & (MDB_RDONLY|MDB_WRITEMAP))) {
5384 /* Synchronous fd for meta writes. Needed even with
5385 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
5387 rc = mdb_fopen(env, &fname, MDB_O_META, mode, &env->me_mfd);
5391 DPRINTF(("opened dbenv %p", (void *) env));
5393 rc = mdb_env_share_locks(env, &excl);
5397 if (!(flags & MDB_RDONLY)) {
5399 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
5400 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
5401 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
5402 (txn = calloc(1, size)))
5404 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
5405 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
5406 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
5407 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
5410 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
5411 if (!txn->mt_rpages) {
5416 txn->mt_rpages[0].mid = 0;
5417 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
5419 txn->mt_dbxs = env->me_dbxs;
5420 txn->mt_flags = MDB_TXN_FINISHED;
5430 mdb_env_close0(env, excl);
5432 mdb_fname_destroy(fname);
5436 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
5438 mdb_env_close0(MDB_env *env, int excl)
5442 if (!(env->me_flags & MDB_ENV_ACTIVE))
5445 /* Doing this here since me_dbxs may not exist during mdb_env_close */
5447 for (i = env->me_maxdbs; --i >= CORE_DBS; )
5448 free(env->me_dbxs[i].md_name.mv_data);
5453 free(env->me_dbiseqs);
5454 free(env->me_dbflags);
5456 free(env->me_dirty_list);
5458 if (env->me_txn0 && env->me_txn0->mt_rpages)
5459 free(env->me_txn0->mt_rpages);
5460 if (env->me_rpages) {
5461 MDB_ID3L el = env->me_rpages;
5463 for (x=1; x<=el[0].mid; x++)
5464 munmap(el[x].mptr, el[x].mcnt * env->me_psize);
5469 mdb_midl_free(env->me_free_pgs);
5471 if (env->me_flags & MDB_ENV_TXKEY) {
5472 pthread_key_delete(env->me_txkey);
5474 /* Delete our key from the global list */
5475 for (i=0; i<mdb_tls_nkeys; i++)
5476 if (mdb_tls_keys[i] == env->me_txkey) {
5477 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
5486 munmap(env->me_map, NUM_METAS*env->me_psize);
5488 munmap(env->me_map, env->me_mapsize);
5491 if (env->me_mfd != INVALID_HANDLE_VALUE)
5492 (void) close(env->me_mfd);
5493 if (env->me_fd != INVALID_HANDLE_VALUE)
5494 (void) close(env->me_fd);
5496 MDB_PID_T pid = env->me_pid;
5497 /* Clearing readers is done in this function because
5498 * me_txkey with its destructor must be disabled first.
5500 * We skip the the reader mutex, so we touch only
5501 * data owned by this process (me_close_readers and
5502 * our readers), and clear each reader atomically.
5504 for (i = env->me_close_readers; --i >= 0; )
5505 if (env->me_txns->mti_readers[i].mr_pid == pid)
5506 env->me_txns->mti_readers[i].mr_pid = 0;
5508 if (env->me_rmutex) {
5509 CloseHandle(env->me_rmutex);
5510 if (env->me_wmutex) CloseHandle(env->me_wmutex);
5512 /* Windows automatically destroys the mutexes when
5513 * the last handle closes.
5515 #elif defined(MDB_USE_POSIX_SEM)
5516 if (env->me_rmutex != SEM_FAILED) {
5517 sem_close(env->me_rmutex);
5518 if (env->me_wmutex != SEM_FAILED)
5519 sem_close(env->me_wmutex);
5520 /* If we have the filelock: If we are the
5521 * only remaining user, clean up semaphores.
5524 mdb_env_excl_lock(env, &excl);
5526 sem_unlink(MUTEXNAME(env, 'r'));
5527 sem_unlink(MUTEXNAME(env, 'w'));
5530 #elif defined(MDB_USE_SYSV_SEM)
5531 if (env->me_rmutex->semid != -1) {
5532 /* If we have the filelock: If we are the
5533 * only remaining user, clean up semaphores.
5536 mdb_env_excl_lock(env, &excl);
5538 semctl(env->me_rmutex->semid, 0, IPC_RMID);
5541 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
5543 if (env->me_lfd != INVALID_HANDLE_VALUE) {
5546 /* Unlock the lockfile. Windows would have unlocked it
5547 * after closing anyway, but not necessarily at once.
5549 UnlockFile(env->me_lfd, 0, 0, 1, 0);
5552 (void) close(env->me_lfd);
5556 if (env->me_fmh) CloseHandle(env->me_fmh);
5557 if (env->me_rpmutex) CloseHandle(env->me_rpmutex);
5559 pthread_mutex_destroy(&env->me_rpmutex);
5563 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
5567 mdb_env_close(MDB_env *env)
5574 VGMEMP_DESTROY(env);
5575 while ((dp = env->me_dpages) != NULL) {
5576 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5577 env->me_dpages = dp->mp_next;
5581 mdb_env_close0(env, 0);
5585 /** Compare two items pointing at aligned #mdb_size_t's */
5587 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5589 return (*(mdb_size_t *)a->mv_data < *(mdb_size_t *)b->mv_data) ? -1 :
5590 *(mdb_size_t *)a->mv_data > *(mdb_size_t *)b->mv_data;
5593 /** Compare two items pointing at aligned unsigned int's.
5595 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5596 * but #mdb_cmp_clong() is called instead if the data type is #mdb_size_t.
5599 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5601 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5602 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5605 /** Compare two items pointing at unsigned ints of unknown alignment.
5606 * Nodes and keys are guaranteed to be 2-byte aligned.
5609 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5611 #if BYTE_ORDER == LITTLE_ENDIAN
5612 unsigned short *u, *c;
5615 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5616 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5619 } while(!x && u > (unsigned short *)a->mv_data);
5622 unsigned short *u, *c, *end;
5625 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5626 u = (unsigned short *)a->mv_data;
5627 c = (unsigned short *)b->mv_data;
5630 } while(!x && u < end);
5635 /** Compare two items lexically */
5637 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5644 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5650 diff = memcmp(a->mv_data, b->mv_data, len);
5651 return diff ? diff : len_diff<0 ? -1 : len_diff;
5654 /** Compare two items in reverse byte order */
5656 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5658 const unsigned char *p1, *p2, *p1_lim;
5662 p1_lim = (const unsigned char *)a->mv_data;
5663 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5664 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5666 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5672 while (p1 > p1_lim) {
5673 diff = *--p1 - *--p2;
5677 return len_diff<0 ? -1 : len_diff;
5680 /** Search for key within a page, using binary search.
5681 * Returns the smallest entry larger or equal to the key.
5682 * If exactp is non-null, stores whether the found entry was an exact match
5683 * in *exactp (1 or 0).
5684 * Updates the cursor index with the index of the found entry.
5685 * If no entry larger or equal to the key is found, returns NULL.
5688 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5690 unsigned int i = 0, nkeys;
5693 MDB_page *mp = mc->mc_pg[mc->mc_top];
5694 MDB_node *node = NULL;
5699 nkeys = NUMKEYS(mp);
5701 DPRINTF(("searching %u keys in %s %spage %"Yu,
5702 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5705 low = IS_LEAF(mp) ? 0 : 1;
5707 cmp = mc->mc_dbx->md_cmp;
5709 /* Branch pages have no data, so if using integer keys,
5710 * alignment is guaranteed. Use faster mdb_cmp_int.
5712 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5713 if (NODEPTR(mp, 1)->mn_ksize == sizeof(mdb_size_t))
5720 nodekey.mv_size = mc->mc_db->md_pad;
5721 node = NODEPTR(mp, 0); /* fake */
5722 while (low <= high) {
5723 i = (low + high) >> 1;
5724 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5725 rc = cmp(key, &nodekey);
5726 DPRINTF(("found leaf index %u [%s], rc = %i",
5727 i, DKEY(&nodekey), rc));
5736 while (low <= high) {
5737 i = (low + high) >> 1;
5739 node = NODEPTR(mp, i);
5740 nodekey.mv_size = NODEKSZ(node);
5741 nodekey.mv_data = NODEKEY(node);
5743 rc = cmp(key, &nodekey);
5746 DPRINTF(("found leaf index %u [%s], rc = %i",
5747 i, DKEY(&nodekey), rc));
5749 DPRINTF(("found branch index %u [%s -> %"Yu"], rc = %i",
5750 i, DKEY(&nodekey), NODEPGNO(node), rc));
5761 if (rc > 0) { /* Found entry is less than the key. */
5762 i++; /* Skip to get the smallest entry larger than key. */
5764 node = NODEPTR(mp, i);
5767 *exactp = (rc == 0 && nkeys > 0);
5768 /* store the key index */
5769 mc->mc_ki[mc->mc_top] = i;
5771 /* There is no entry larger or equal to the key. */
5774 /* nodeptr is fake for LEAF2 */
5780 mdb_cursor_adjust(MDB_cursor *mc, func)
5784 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5785 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5792 /** Pop a page off the top of the cursor's stack. */
5794 mdb_cursor_pop(MDB_cursor *mc)
5797 DPRINTF(("popping page %"Yu" off db %d cursor %p",
5798 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5804 mc->mc_flags &= ~C_INITIALIZED;
5809 /** Push a page onto the top of the cursor's stack.
5810 * Set #MDB_TXN_ERROR on failure.
5813 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5815 DPRINTF(("pushing page %"Yu" on db %d cursor %p", mp->mp_pgno,
5816 DDBI(mc), (void *) mc));
5818 if (mc->mc_snum >= CURSOR_STACK) {
5819 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5820 return MDB_CURSOR_FULL;
5823 mc->mc_top = mc->mc_snum++;
5824 mc->mc_pg[mc->mc_top] = mp;
5825 mc->mc_ki[mc->mc_top] = 0;
5831 /** Map a read-only page.
5832 * There are two levels of tracking in use, a per-txn list and a per-env list.
5833 * ref'ing and unref'ing the per-txn list is faster since it requires no
5834 * locking. Pages are cached in the per-env list for global reuse, and a lock
5835 * is required. Pages are not immediately unmapped when their refcnt goes to
5836 * zero; they hang around in case they will be reused again soon.
5838 * When the per-txn list gets full, all pages with refcnt=0 are purged from the
5839 * list and their refcnts in the per-env list are decremented.
5841 * When the per-env list gets full, all pages with refcnt=0 are purged from the
5842 * list and their pages are unmapped.
5844 * @note "full" means the list has reached its respective rpcheck threshold.
5845 * This threshold slowly raises if no pages could be purged on a given check,
5846 * and returns to its original value when enough pages were purged.
5848 * If purging doesn't free any slots, filling the per-txn list will return
5849 * MDB_TXN_FULL, and filling the per-env list returns MDB_MAP_FULL.
5851 * Reference tracking in a txn is imperfect, pages can linger with non-zero
5852 * refcnt even without active references. It was deemed to be too invasive
5853 * to add unrefs in every required location. However, all pages are unref'd
5854 * at the end of the transaction. This guarantees that no stale references
5855 * linger in the per-env list.
5857 * Usually we map chunks of 16 pages at a time, but if an overflow page begins
5858 * at the tail of the chunk we extend the chunk to include the entire overflow
5859 * page. Unfortunately, pages can be turned into overflow pages after their
5860 * chunk was already mapped. In that case we must remap the chunk if the
5861 * overflow page is referenced. If the chunk's refcnt is 0 we can just remap
5862 * it, otherwise we temporarily map a new chunk just for the overflow page.
5864 * @note this chunk handling means we cannot guarantee that a data item
5865 * returned from the DB will stay alive for the duration of the transaction:
5866 * We unref pages as soon as a cursor moves away from the page
5867 * A subsequent op may cause a purge, which may unmap any unref'd chunks
5868 * The caller must copy the data if it must be used later in the same txn.
5870 * Also - our reference counting revolves around cursors, but overflow pages
5871 * aren't pointed to by a cursor's page stack. We have to remember them
5872 * explicitly, in the added mc_ovpg field. A single cursor can only hold a
5873 * reference to one overflow page at a time.
5875 * @param[in] txn the transaction for this access.
5876 * @param[in] pgno the page number for the page to retrieve.
5877 * @param[out] ret address of a pointer where the page's address will be stored.
5878 * @return 0 on success, non-zero on failure.
5881 mdb_rpage_get(MDB_txn *txn, pgno_t pg0, MDB_page **ret)
5883 MDB_env *env = txn->mt_env;
5885 MDB_ID3L tl = txn->mt_rpages;
5886 MDB_ID3L el = env->me_rpages;
5890 int rc, retries = 1;
5894 #define SET_OFF(off,val) off.QuadPart = val
5895 #define MAP(rc,env,addr,len,off) \
5897 rc = NtMapViewOfSection(env->me_fmh, GetCurrentProcess(), &addr, 0, \
5898 len, &off, &len, ViewUnmap, (env->me_flags & MDB_RDONLY) ? 0 : MEM_RESERVE, PAGE_READONLY); \
5899 if (rc) rc = mdb_nt2win32(rc)
5903 #define SET_OFF(off,val) off = val
5904 #define MAP(rc,env,addr,len,off) \
5905 addr = mmap(NULL, len, PROT_READ, MAP_SHARED, env->me_fd, off); \
5906 rc = (addr == MAP_FAILED) ? errno : 0
5909 /* remember the offset of the actual page number, so we can
5910 * return the correct pointer at the end.
5912 rem = pg0 & (MDB_RPAGE_CHUNK-1);
5916 x = mdb_mid3l_search(tl, pgno);
5917 if (x <= tl[0].mid && tl[x].mid == pgno) {
5918 if (x != tl[0].mid && tl[x+1].mid == pg0)
5920 /* check for overflow size */
5921 p = (MDB_page *)((char *)tl[x].mptr + rem * env->me_psize);
5922 if (IS_OVERFLOW(p) && p->mp_pages + rem > tl[x].mcnt) {
5923 id3.mcnt = p->mp_pages + rem;
5924 len = id3.mcnt * env->me_psize;
5925 SET_OFF(off, pgno * env->me_psize);
5926 MAP(rc, env, id3.mptr, len, off);
5929 /* check for local-only page */
5931 mdb_tassert(txn, tl[x].mid != pg0);
5932 /* hope there's room to insert this locally.
5933 * setting mid here tells later code to just insert
5934 * this id3 instead of searching for a match.
5939 /* ignore the mapping we got from env, use new one */
5940 tl[x].mptr = id3.mptr;
5941 tl[x].mcnt = id3.mcnt;
5942 /* if no active ref, see if we can replace in env */
5945 pthread_mutex_lock(&env->me_rpmutex);
5946 i = mdb_mid3l_search(el, tl[x].mid);
5947 if (el[i].mref == 1) {
5948 /* just us, replace it */
5949 munmap(el[i].mptr, el[i].mcnt * env->me_psize);
5950 el[i].mptr = tl[x].mptr;
5951 el[i].mcnt = tl[x].mcnt;
5953 /* there are others, remove ourself */
5956 pthread_mutex_unlock(&env->me_rpmutex);
5960 id3.mptr = tl[x].mptr;
5961 id3.mcnt = tl[x].mcnt;
5967 if (tl[0].mid >= MDB_TRPAGE_MAX - txn->mt_rpcheck) {
5969 /* purge unref'd pages from our list and unref in env */
5970 pthread_mutex_lock(&env->me_rpmutex);
5973 for (i=1; i<=tl[0].mid; i++) {
5976 /* tmp overflow pages don't go to env */
5977 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
5978 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
5981 x = mdb_mid3l_search(el, tl[i].mid);
5985 pthread_mutex_unlock(&env->me_rpmutex);
5987 /* we didn't find any unref'd chunks.
5988 * if we're out of room, fail.
5990 if (tl[0].mid >= MDB_TRPAGE_MAX)
5991 return MDB_TXN_FULL;
5992 /* otherwise, raise threshold for next time around
5995 txn->mt_rpcheck /= 2;
5997 /* we found some unused; consolidate the list */
5998 for (i=y+1; i<= tl[0].mid; i++)
6002 /* decrease the check threshold toward its original value */
6003 if (!txn->mt_rpcheck)
6004 txn->mt_rpcheck = 1;
6005 while (txn->mt_rpcheck < tl[0].mid && txn->mt_rpcheck < MDB_TRPAGE_SIZE/2)
6006 txn->mt_rpcheck *= 2;
6009 if (tl[0].mid < MDB_TRPAGE_SIZE) {
6013 /* don't map past last written page in read-only envs */
6014 if ((env->me_flags & MDB_RDONLY) && pgno + MDB_RPAGE_CHUNK-1 > txn->mt_last_pgno)
6015 id3.mcnt = txn->mt_last_pgno + 1 - pgno;
6017 id3.mcnt = MDB_RPAGE_CHUNK;
6018 len = id3.mcnt * env->me_psize;
6021 /* search for page in env */
6022 pthread_mutex_lock(&env->me_rpmutex);
6023 x = mdb_mid3l_search(el, pgno);
6024 if (x <= el[0].mid && el[x].mid == pgno) {
6025 id3.mptr = el[x].mptr;
6026 id3.mcnt = el[x].mcnt;
6027 /* check for overflow size */
6028 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
6029 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
6030 id3.mcnt = p->mp_pages + rem;
6031 len = id3.mcnt * env->me_psize;
6032 SET_OFF(off, pgno * env->me_psize);
6033 MAP(rc, env, id3.mptr, len, off);
6037 munmap(el[x].mptr, env->me_psize * el[x].mcnt);
6038 el[x].mptr = id3.mptr;
6039 el[x].mcnt = id3.mcnt;
6042 pthread_mutex_unlock(&env->me_rpmutex);
6047 pthread_mutex_unlock(&env->me_rpmutex);
6050 if (el[0].mid >= MDB_ERPAGE_MAX - env->me_rpcheck) {
6051 /* purge unref'd pages */
6053 for (i=1; i<=el[0].mid; i++) {
6056 munmap(el[i].mptr, env->me_psize * el[i].mcnt);
6061 /* see if we can unref some local pages */
6066 if (el[0].mid >= MDB_ERPAGE_MAX) {
6067 pthread_mutex_unlock(&env->me_rpmutex);
6068 return MDB_MAP_FULL;
6070 env->me_rpcheck /= 2;
6072 for (i=y+1; i<= el[0].mid; i++)
6076 if (!env->me_rpcheck)
6077 env->me_rpcheck = 1;
6078 while (env->me_rpcheck < el[0].mid && env->me_rpcheck < MDB_ERPAGE_SIZE/2)
6079 env->me_rpcheck *= 2;
6082 SET_OFF(off, pgno * env->me_psize);
6083 MAP(rc, env, id3.mptr, len, off);
6086 pthread_mutex_unlock(&env->me_rpmutex);
6089 /* check for overflow size */
6090 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
6091 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
6092 id3.mcnt = p->mp_pages + rem;
6093 munmap(id3.mptr, len);
6094 len = id3.mcnt * env->me_psize;
6095 MAP(rc, env, id3.mptr, len, off);
6099 mdb_mid3l_insert(el, &id3);
6100 pthread_mutex_unlock(&env->me_rpmutex);
6102 mdb_mid3l_insert(tl, &id3);
6104 return MDB_TXN_FULL;
6107 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
6108 #if MDB_DEBUG /* we don't need this check any more */
6109 if (IS_OVERFLOW(p)) {
6110 mdb_tassert(txn, p->mp_pages + rem <= id3.mcnt);
6118 /** Find the address of the page corresponding to a given page number.
6119 * Set #MDB_TXN_ERROR on failure.
6120 * @param[in] mc the cursor accessing the page.
6121 * @param[in] pgno the page number for the page to retrieve.
6122 * @param[out] ret address of a pointer where the page's address will be stored.
6123 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
6124 * @return 0 on success, non-zero on failure.
6127 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
6129 MDB_txn *txn = mc->mc_txn;
6133 if (! (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP))) {
6137 MDB_ID2L dl = tx2->mt_u.dirty_list;
6139 /* Spilled pages were dirtied in this txn and flushed
6140 * because the dirty list got full. Bring this page
6141 * back in from the map (but don't unspill it here,
6142 * leave that unless page_touch happens again).
6144 if (tx2->mt_spill_pgs) {
6145 MDB_ID pn = pgno << 1;
6146 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
6147 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
6152 unsigned x = mdb_mid2l_search(dl, pgno);
6153 if (x <= dl[0].mid && dl[x].mid == pgno) {
6159 } while ((tx2 = tx2->mt_parent) != NULL);
6162 if (pgno >= txn->mt_next_pgno) {
6163 DPRINTF(("page %"Yu" not found", pgno));
6164 txn->mt_flags |= MDB_TXN_ERROR;
6165 return MDB_PAGE_NOTFOUND;
6173 int rc = mdb_rpage_get(txn, pgno, &p);
6175 txn->mt_flags |= MDB_TXN_ERROR;
6179 MDB_env *env = txn->mt_env;
6180 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
6191 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
6192 * The cursor is at the root page, set up the rest of it.
6195 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
6197 MDB_page *mp = mc->mc_pg[mc->mc_top];
6201 while (IS_BRANCH(mp)) {
6205 DPRINTF(("branch page %"Yu" has %u keys", mp->mp_pgno, NUMKEYS(mp)));
6206 /* Don't assert on branch pages in the FreeDB. We can get here
6207 * while in the process of rebalancing a FreeDB branch page; we must
6208 * let that proceed. ITS#8336
6210 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
6211 DPRINTF(("found index 0 to page %"Yu, NODEPGNO(NODEPTR(mp, 0))));
6213 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
6215 if (flags & MDB_PS_LAST) {
6216 i = NUMKEYS(mp) - 1;
6217 /* if already init'd, see if we're already in right place */
6218 if (mc->mc_flags & C_INITIALIZED) {
6219 if (mc->mc_ki[mc->mc_top] == i) {
6220 mc->mc_top = mc->mc_snum++;
6221 mp = mc->mc_pg[mc->mc_top];
6228 node = mdb_node_search(mc, key, &exact);
6230 i = NUMKEYS(mp) - 1;
6232 i = mc->mc_ki[mc->mc_top];
6234 mdb_cassert(mc, i > 0);
6238 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
6241 mdb_cassert(mc, i < NUMKEYS(mp));
6242 node = NODEPTR(mp, i);
6244 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6247 mc->mc_ki[mc->mc_top] = i;
6248 if ((rc = mdb_cursor_push(mc, mp)))
6252 if (flags & MDB_PS_MODIFY) {
6253 if ((rc = mdb_page_touch(mc)) != 0)
6255 mp = mc->mc_pg[mc->mc_top];
6260 DPRINTF(("internal error, index points to a %02X page!?",
6262 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6263 return MDB_CORRUPTED;
6266 DPRINTF(("found leaf page %"Yu" for key [%s]", mp->mp_pgno,
6267 key ? DKEY(key) : "null"));
6268 mc->mc_flags |= C_INITIALIZED;
6269 mc->mc_flags &= ~C_EOF;
6274 /** Search for the lowest key under the current branch page.
6275 * This just bypasses a NUMKEYS check in the current page
6276 * before calling mdb_page_search_root(), because the callers
6277 * are all in situations where the current page is known to
6281 mdb_page_search_lowest(MDB_cursor *mc)
6283 MDB_page *mp = mc->mc_pg[mc->mc_top];
6284 MDB_node *node = NODEPTR(mp, 0);
6287 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6290 mc->mc_ki[mc->mc_top] = 0;
6291 if ((rc = mdb_cursor_push(mc, mp)))
6293 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
6296 /** Search for the page a given key should be in.
6297 * Push it and its parent pages on the cursor stack.
6298 * @param[in,out] mc the cursor for this operation.
6299 * @param[in] key the key to search for, or NULL for first/last page.
6300 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
6301 * are touched (updated with new page numbers).
6302 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
6303 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
6304 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
6305 * @return 0 on success, non-zero on failure.
6308 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
6313 /* Make sure the txn is still viable, then find the root from
6314 * the txn's db table and set it as the root of the cursor's stack.
6316 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
6317 DPUTS("transaction may not be used now");
6320 /* Make sure we're using an up-to-date root */
6321 if (*mc->mc_dbflag & DB_STALE) {
6323 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6325 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
6326 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
6333 MDB_node *leaf = mdb_node_search(&mc2,
6334 &mc->mc_dbx->md_name, &exact);
6336 return MDB_NOTFOUND;
6337 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
6338 return MDB_INCOMPATIBLE; /* not a named DB */
6339 rc = mdb_node_read(&mc2, leaf, &data);
6342 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
6344 /* The txn may not know this DBI, or another process may
6345 * have dropped and recreated the DB with other flags.
6347 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
6348 return MDB_INCOMPATIBLE;
6349 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
6351 *mc->mc_dbflag &= ~DB_STALE;
6353 root = mc->mc_db->md_root;
6355 if (root == P_INVALID) { /* Tree is empty. */
6356 DPUTS("tree is empty");
6357 return MDB_NOTFOUND;
6361 mdb_cassert(mc, root > 1);
6362 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root) {
6365 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[0]);
6367 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
6374 for (i=1; i<mc->mc_snum; i++)
6375 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[i]);
6381 DPRINTF(("db %d root page %"Yu" has flags 0x%X",
6382 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
6384 if (flags & MDB_PS_MODIFY) {
6385 if ((rc = mdb_page_touch(mc)))
6389 if (flags & MDB_PS_ROOTONLY)
6392 return mdb_page_search_root(mc, key, flags);
6396 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
6398 MDB_txn *txn = mc->mc_txn;
6399 pgno_t pg = mp->mp_pgno;
6400 unsigned x = 0, ovpages = mp->mp_pages;
6401 MDB_env *env = txn->mt_env;
6402 MDB_IDL sl = txn->mt_spill_pgs;
6403 MDB_ID pn = pg << 1;
6406 DPRINTF(("free ov page %"Yu" (%d)", pg, ovpages));
6407 /* If the page is dirty or on the spill list we just acquired it,
6408 * so we should give it back to our current free list, if any.
6409 * Otherwise put it onto the list of pages we freed in this txn.
6411 * Won't create me_pghead: me_pglast must be inited along with it.
6412 * Unsupported in nested txns: They would need to hide the page
6413 * range in ancestor txns' dirty and spilled lists.
6415 if (env->me_pghead &&
6417 ((mp->mp_flags & P_DIRTY) ||
6418 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
6422 MDB_ID2 *dl, ix, iy;
6423 rc = mdb_midl_need(&env->me_pghead, ovpages);
6426 if (!(mp->mp_flags & P_DIRTY)) {
6427 /* This page is no longer spilled */
6434 /* Remove from dirty list */
6435 dl = txn->mt_u.dirty_list;
6437 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
6443 mdb_cassert(mc, x > 1);
6445 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
6446 txn->mt_flags |= MDB_TXN_ERROR;
6450 txn->mt_dirty_room++;
6451 if (!(env->me_flags & MDB_WRITEMAP))
6452 mdb_dpage_free(env, mp);
6454 /* Insert in me_pghead */
6455 mop = env->me_pghead;
6456 j = mop[0] + ovpages;
6457 for (i = mop[0]; i && mop[i] < pg; i--)
6463 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
6467 mc->mc_db->md_overflow_pages -= ovpages;
6471 /** Return the data associated with a given node.
6472 * @param[in] mc The cursor for this operation.
6473 * @param[in] leaf The node being read.
6474 * @param[out] data Updated to point to the node's data.
6475 * @return 0 on success, non-zero on failure.
6478 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
6480 MDB_page *omp; /* overflow page */
6485 MDB_PAGE_UNREF(mc->mc_txn, MC_OVPG(mc));
6486 MC_SET_OVPG(mc, NULL);
6488 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6489 data->mv_size = NODEDSZ(leaf);
6490 data->mv_data = NODEDATA(leaf);
6494 /* Read overflow data.
6496 data->mv_size = NODEDSZ(leaf);
6497 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
6498 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
6499 DPRINTF(("read overflow page %"Yu" failed", pgno));
6502 data->mv_data = METADATA(omp);
6503 MC_SET_OVPG(mc, omp);
6509 mdb_get(MDB_txn *txn, MDB_dbi dbi,
6510 MDB_val *key, MDB_val *data)
6517 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
6519 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
6522 if (txn->mt_flags & MDB_TXN_BLOCKED)
6525 mdb_cursor_init(&mc, txn, dbi, &mx);
6526 rc = mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
6527 /* unref all the pages when MDB_VL32 - caller must copy the data
6528 * before doing anything else
6530 MDB_CURSOR_UNREF(&mc, 1);
6534 /** Find a sibling for a page.
6535 * Replaces the page at the top of the cursor's stack with the
6536 * specified sibling, if one exists.
6537 * @param[in] mc The cursor for this operation.
6538 * @param[in] move_right Non-zero if the right sibling is requested,
6539 * otherwise the left sibling.
6540 * @return 0 on success, non-zero on failure.
6543 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
6552 if (mc->mc_snum < 2) {
6553 return MDB_NOTFOUND; /* root has no siblings */
6557 op = mc->mc_pg[mc->mc_top];
6560 DPRINTF(("parent page is page %"Yu", index %u",
6561 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
6563 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6564 : (mc->mc_ki[mc->mc_top] == 0)) {
6565 DPRINTF(("no more keys left, moving to %s sibling",
6566 move_right ? "right" : "left"));
6567 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
6568 /* undo cursor_pop before returning */
6575 mc->mc_ki[mc->mc_top]++;
6577 mc->mc_ki[mc->mc_top]--;
6578 DPRINTF(("just moving to %s index key %u",
6579 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
6581 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
6583 MDB_PAGE_UNREF(mc->mc_txn, op);
6585 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6586 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
6587 /* mc will be inconsistent if caller does mc_snum++ as above */
6588 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6592 mdb_cursor_push(mc, mp);
6594 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
6599 /** Move the cursor to the next data item. */
6601 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6607 if ((mc->mc_flags & C_DEL && op == MDB_NEXT_DUP))
6608 return MDB_NOTFOUND;
6610 if (!(mc->mc_flags & C_INITIALIZED))
6611 return mdb_cursor_first(mc, key, data);
6613 mp = mc->mc_pg[mc->mc_top];
6615 if (mc->mc_flags & C_EOF) {
6616 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mp)-1)
6617 return MDB_NOTFOUND;
6618 mc->mc_flags ^= C_EOF;
6621 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6622 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6623 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6624 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
6625 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
6626 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
6627 if (rc == MDB_SUCCESS)
6628 MDB_GET_KEY(leaf, key);
6633 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6636 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6637 if (op == MDB_NEXT_DUP)
6638 return MDB_NOTFOUND;
6642 DPRINTF(("cursor_next: top page is %"Yu" in cursor %p",
6643 mdb_dbg_pgno(mp), (void *) mc));
6644 if (mc->mc_flags & C_DEL) {
6645 mc->mc_flags ^= C_DEL;
6649 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
6650 DPUTS("=====> move to next sibling page");
6651 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6652 mc->mc_flags |= C_EOF;
6655 mp = mc->mc_pg[mc->mc_top];
6656 DPRINTF(("next page is %"Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6658 mc->mc_ki[mc->mc_top]++;
6661 DPRINTF(("==> cursor points to page %"Yu" with %u keys, key index %u",
6662 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6665 key->mv_size = mc->mc_db->md_pad;
6666 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6670 mdb_cassert(mc, IS_LEAF(mp));
6671 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6673 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6674 mdb_xcursor_init1(mc, leaf);
6677 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6680 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6681 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6682 if (rc != MDB_SUCCESS)
6687 MDB_GET_KEY(leaf, key);
6691 /** Move the cursor to the previous data item. */
6693 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6699 if (!(mc->mc_flags & C_INITIALIZED)) {
6700 rc = mdb_cursor_last(mc, key, data);
6703 mc->mc_ki[mc->mc_top]++;
6706 mp = mc->mc_pg[mc->mc_top];
6708 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6709 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6710 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6711 if (op == MDB_PREV || op == MDB_PREV_DUP) {
6712 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
6713 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
6714 if (rc == MDB_SUCCESS) {
6715 MDB_GET_KEY(leaf, key);
6716 mc->mc_flags &= ~C_EOF;
6722 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6725 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6726 if (op == MDB_PREV_DUP)
6727 return MDB_NOTFOUND;
6731 DPRINTF(("cursor_prev: top page is %"Yu" in cursor %p",
6732 mdb_dbg_pgno(mp), (void *) mc));
6734 mc->mc_flags &= ~(C_EOF|C_DEL);
6736 if (mc->mc_ki[mc->mc_top] == 0) {
6737 DPUTS("=====> move to prev sibling page");
6738 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
6741 mp = mc->mc_pg[mc->mc_top];
6742 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
6743 DPRINTF(("prev page is %"Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6745 mc->mc_ki[mc->mc_top]--;
6747 DPRINTF(("==> cursor points to page %"Yu" with %u keys, key index %u",
6748 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6751 key->mv_size = mc->mc_db->md_pad;
6752 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6756 mdb_cassert(mc, IS_LEAF(mp));
6757 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6759 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6760 mdb_xcursor_init1(mc, leaf);
6763 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6766 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6767 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6768 if (rc != MDB_SUCCESS)
6773 MDB_GET_KEY(leaf, key);
6777 /** Set the cursor on a specific data item. */
6779 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6780 MDB_cursor_op op, int *exactp)
6784 MDB_node *leaf = NULL;
6787 if (key->mv_size == 0)
6788 return MDB_BAD_VALSIZE;
6790 if (mc->mc_xcursor) {
6791 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6792 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6795 /* See if we're already on the right page */
6796 if (mc->mc_flags & C_INITIALIZED) {
6799 mp = mc->mc_pg[mc->mc_top];
6801 mc->mc_ki[mc->mc_top] = 0;
6802 return MDB_NOTFOUND;
6804 if (mp->mp_flags & P_LEAF2) {
6805 nodekey.mv_size = mc->mc_db->md_pad;
6806 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
6808 leaf = NODEPTR(mp, 0);
6809 MDB_GET_KEY2(leaf, nodekey);
6811 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6813 /* Probably happens rarely, but first node on the page
6814 * was the one we wanted.
6816 mc->mc_ki[mc->mc_top] = 0;
6823 unsigned int nkeys = NUMKEYS(mp);
6825 if (mp->mp_flags & P_LEAF2) {
6826 nodekey.mv_data = LEAF2KEY(mp,
6827 nkeys-1, nodekey.mv_size);
6829 leaf = NODEPTR(mp, nkeys-1);
6830 MDB_GET_KEY2(leaf, nodekey);
6832 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6834 /* last node was the one we wanted */
6835 mc->mc_ki[mc->mc_top] = nkeys-1;
6841 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
6842 /* This is definitely the right page, skip search_page */
6843 if (mp->mp_flags & P_LEAF2) {
6844 nodekey.mv_data = LEAF2KEY(mp,
6845 mc->mc_ki[mc->mc_top], nodekey.mv_size);
6847 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6848 MDB_GET_KEY2(leaf, nodekey);
6850 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6852 /* current node was the one we wanted */
6859 mc->mc_flags &= ~C_EOF;
6863 /* If any parents have right-sibs, search.
6864 * Otherwise, there's nothing further.
6866 for (i=0; i<mc->mc_top; i++)
6868 NUMKEYS(mc->mc_pg[i])-1)
6870 if (i == mc->mc_top) {
6871 /* There are no other pages */
6872 mc->mc_ki[mc->mc_top] = nkeys;
6873 return MDB_NOTFOUND;
6877 /* There are no other pages */
6878 mc->mc_ki[mc->mc_top] = 0;
6879 if (op == MDB_SET_RANGE && !exactp) {
6883 return MDB_NOTFOUND;
6889 rc = mdb_page_search(mc, key, 0);
6890 if (rc != MDB_SUCCESS)
6893 mp = mc->mc_pg[mc->mc_top];
6894 mdb_cassert(mc, IS_LEAF(mp));
6897 leaf = mdb_node_search(mc, key, exactp);
6898 if (exactp != NULL && !*exactp) {
6899 /* MDB_SET specified and not an exact match. */
6900 return MDB_NOTFOUND;
6904 DPUTS("===> inexact leaf not found, goto sibling");
6905 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6906 mc->mc_flags |= C_EOF;
6907 return rc; /* no entries matched */
6909 mp = mc->mc_pg[mc->mc_top];
6910 mdb_cassert(mc, IS_LEAF(mp));
6911 leaf = NODEPTR(mp, 0);
6915 mc->mc_flags |= C_INITIALIZED;
6916 mc->mc_flags &= ~C_EOF;
6919 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
6920 key->mv_size = mc->mc_db->md_pad;
6921 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6926 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6927 mdb_xcursor_init1(mc, leaf);
6930 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6931 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
6932 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6935 if (op == MDB_GET_BOTH) {
6941 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
6942 if (rc != MDB_SUCCESS)
6945 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
6948 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
6950 dcmp = mc->mc_dbx->md_dcmp;
6951 if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
6952 dcmp = mdb_cmp_clong;
6953 rc = dcmp(data, &olddata);
6955 if (op == MDB_GET_BOTH || rc > 0)
6956 return MDB_NOTFOUND;
6963 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6964 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6969 /* The key already matches in all other cases */
6970 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6971 MDB_GET_KEY(leaf, key);
6972 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6977 /** Move the cursor to the first item in the database. */
6979 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6984 if (mc->mc_xcursor) {
6985 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6986 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6989 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6990 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6991 if (rc != MDB_SUCCESS)
6994 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6996 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6997 mc->mc_flags |= C_INITIALIZED;
6998 mc->mc_flags &= ~C_EOF;
7000 mc->mc_ki[mc->mc_top] = 0;
7002 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7003 key->mv_size = mc->mc_db->md_pad;
7004 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
7009 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7010 mdb_xcursor_init1(mc, leaf);
7011 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
7015 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
7019 MDB_GET_KEY(leaf, key);
7023 /** Move the cursor to the last item in the database. */
7025 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
7030 if (mc->mc_xcursor) {
7031 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
7032 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
7035 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
7036 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
7037 if (rc != MDB_SUCCESS)
7040 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
7042 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
7043 mc->mc_flags |= C_INITIALIZED|C_EOF;
7044 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7046 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7047 key->mv_size = mc->mc_db->md_pad;
7048 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
7053 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7054 mdb_xcursor_init1(mc, leaf);
7055 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
7059 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
7064 MDB_GET_KEY(leaf, key);
7069 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7074 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
7079 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
7083 case MDB_GET_CURRENT:
7084 if (!(mc->mc_flags & C_INITIALIZED)) {
7087 MDB_page *mp = mc->mc_pg[mc->mc_top];
7088 int nkeys = NUMKEYS(mp);
7089 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
7090 mc->mc_ki[mc->mc_top] = nkeys;
7096 key->mv_size = mc->mc_db->md_pad;
7097 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
7099 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7100 MDB_GET_KEY(leaf, key);
7102 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7103 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
7105 rc = mdb_node_read(mc, leaf, data);
7112 case MDB_GET_BOTH_RANGE:
7117 if (mc->mc_xcursor == NULL) {
7118 rc = MDB_INCOMPATIBLE;
7128 rc = mdb_cursor_set(mc, key, data, op,
7129 op == MDB_SET_RANGE ? NULL : &exact);
7132 case MDB_GET_MULTIPLE:
7133 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7137 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7138 rc = MDB_INCOMPATIBLE;
7142 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
7143 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
7146 case MDB_NEXT_MULTIPLE:
7151 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7152 rc = MDB_INCOMPATIBLE;
7155 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
7156 if (rc == MDB_SUCCESS) {
7157 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
7160 mx = &mc->mc_xcursor->mx_cursor;
7161 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
7163 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
7164 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
7170 case MDB_PREV_MULTIPLE:
7175 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7176 rc = MDB_INCOMPATIBLE;
7179 if (!(mc->mc_flags & C_INITIALIZED))
7180 rc = mdb_cursor_last(mc, key, data);
7183 if (rc == MDB_SUCCESS) {
7184 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
7185 if (mx->mc_flags & C_INITIALIZED) {
7186 rc = mdb_cursor_sibling(mx, 0);
7187 if (rc == MDB_SUCCESS)
7196 case MDB_NEXT_NODUP:
7197 rc = mdb_cursor_next(mc, key, data, op);
7201 case MDB_PREV_NODUP:
7202 rc = mdb_cursor_prev(mc, key, data, op);
7205 rc = mdb_cursor_first(mc, key, data);
7208 mfunc = mdb_cursor_first;
7210 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7214 if (mc->mc_xcursor == NULL) {
7215 rc = MDB_INCOMPATIBLE;
7219 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7220 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7221 MDB_GET_KEY(leaf, key);
7222 rc = mdb_node_read(mc, leaf, data);
7226 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
7230 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
7233 rc = mdb_cursor_last(mc, key, data);
7236 mfunc = mdb_cursor_last;
7239 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
7244 if (mc->mc_flags & C_DEL)
7245 mc->mc_flags ^= C_DEL;
7250 /** Touch all the pages in the cursor stack. Set mc_top.
7251 * Makes sure all the pages are writable, before attempting a write operation.
7252 * @param[in] mc The cursor to operate on.
7255 mdb_cursor_touch(MDB_cursor *mc)
7257 int rc = MDB_SUCCESS;
7259 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & (DB_DIRTY|DB_DUPDATA))) {
7260 /* Touch DB record of named DB */
7263 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
7265 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
7266 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
7269 *mc->mc_dbflag |= DB_DIRTY;
7274 rc = mdb_page_touch(mc);
7275 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
7276 mc->mc_top = mc->mc_snum-1;
7281 /** Do not spill pages to disk if txn is getting full, may fail instead */
7282 #define MDB_NOSPILL 0x8000
7285 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7289 MDB_node *leaf = NULL;
7290 MDB_page *fp, *mp, *sub_root = NULL;
7292 MDB_val xdata, *rdata, dkey, olddata;
7294 int do_sub = 0, insert_key, insert_data;
7295 unsigned int mcount = 0, dcount = 0, nospill;
7298 unsigned int nflags;
7301 if (mc == NULL || key == NULL)
7304 env = mc->mc_txn->mt_env;
7306 /* Check this first so counter will always be zero on any
7309 if (flags & MDB_MULTIPLE) {
7310 dcount = data[1].mv_size;
7311 data[1].mv_size = 0;
7312 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
7313 return MDB_INCOMPATIBLE;
7316 nospill = flags & MDB_NOSPILL;
7317 flags &= ~MDB_NOSPILL;
7319 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7320 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7322 if (key->mv_size-1 >= ENV_MAXKEY(env))
7323 return MDB_BAD_VALSIZE;
7325 #if SIZE_MAX > MAXDATASIZE
7326 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
7327 return MDB_BAD_VALSIZE;
7329 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
7330 return MDB_BAD_VALSIZE;
7333 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
7334 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
7338 if (flags == MDB_CURRENT) {
7339 if (!(mc->mc_flags & C_INITIALIZED))
7342 } else if (mc->mc_db->md_root == P_INVALID) {
7343 /* new database, cursor has nothing to point to */
7346 mc->mc_flags &= ~C_INITIALIZED;
7351 if (flags & MDB_APPEND) {
7353 rc = mdb_cursor_last(mc, &k2, &d2);
7355 rc = mc->mc_dbx->md_cmp(key, &k2);
7358 mc->mc_ki[mc->mc_top]++;
7360 /* new key is <= last key */
7365 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
7367 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
7368 DPRINTF(("duplicate key [%s]", DKEY(key)));
7370 return MDB_KEYEXIST;
7372 if (rc && rc != MDB_NOTFOUND)
7376 if (mc->mc_flags & C_DEL)
7377 mc->mc_flags ^= C_DEL;
7379 /* Cursor is positioned, check for room in the dirty list */
7381 if (flags & MDB_MULTIPLE) {
7383 xdata.mv_size = data->mv_size * dcount;
7387 if ((rc2 = mdb_page_spill(mc, key, rdata)))
7391 if (rc == MDB_NO_ROOT) {
7393 /* new database, write a root leaf page */
7394 DPUTS("allocating new root leaf page");
7395 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
7398 mdb_cursor_push(mc, np);
7399 mc->mc_db->md_root = np->mp_pgno;
7400 mc->mc_db->md_depth++;
7401 *mc->mc_dbflag |= DB_DIRTY;
7402 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
7404 np->mp_flags |= P_LEAF2;
7405 mc->mc_flags |= C_INITIALIZED;
7407 /* make sure all cursor pages are writable */
7408 rc2 = mdb_cursor_touch(mc);
7413 insert_key = insert_data = rc;
7415 /* The key does not exist */
7416 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
7417 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
7418 LEAFSIZE(key, data) > env->me_nodemax)
7420 /* Too big for a node, insert in sub-DB. Set up an empty
7421 * "old sub-page" for prep_subDB to expand to a full page.
7423 fp_flags = P_LEAF|P_DIRTY;
7425 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
7426 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
7427 olddata.mv_size = PAGEHDRSZ;
7431 /* there's only a key anyway, so this is a no-op */
7432 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7434 unsigned int ksize = mc->mc_db->md_pad;
7435 if (key->mv_size != ksize)
7436 return MDB_BAD_VALSIZE;
7437 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
7438 memcpy(ptr, key->mv_data, ksize);
7440 /* if overwriting slot 0 of leaf, need to
7441 * update branch key if there is a parent page
7443 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7444 unsigned short dtop = 1;
7446 /* slot 0 is always an empty key, find real slot */
7447 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7451 if (mc->mc_ki[mc->mc_top])
7452 rc2 = mdb_update_key(mc, key);
7463 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7464 olddata.mv_size = NODEDSZ(leaf);
7465 olddata.mv_data = NODEDATA(leaf);
7468 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
7469 /* Prepare (sub-)page/sub-DB to accept the new item,
7470 * if needed. fp: old sub-page or a header faking
7471 * it. mp: new (sub-)page. offset: growth in page
7472 * size. xdata: node data with new page or DB.
7474 unsigned i, offset = 0;
7475 mp = fp = xdata.mv_data = env->me_pbuf;
7476 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
7478 /* Was a single item before, must convert now */
7479 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7481 /* Just overwrite the current item */
7482 if (flags == MDB_CURRENT)
7484 dcmp = mc->mc_dbx->md_dcmp;
7485 if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
7486 dcmp = mdb_cmp_clong;
7487 /* does data match? */
7488 if (!dcmp(data, &olddata)) {
7489 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
7490 return MDB_KEYEXIST;
7495 /* Back up original data item */
7496 dkey.mv_size = olddata.mv_size;
7497 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
7499 /* Make sub-page header for the dup items, with dummy body */
7500 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
7501 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
7502 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
7503 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7504 fp->mp_flags |= P_LEAF2;
7505 fp->mp_pad = data->mv_size;
7506 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
7508 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
7509 (dkey.mv_size & 1) + (data->mv_size & 1);
7511 fp->mp_upper = xdata.mv_size - PAGEBASE;
7512 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
7513 } else if (leaf->mn_flags & F_SUBDATA) {
7514 /* Data is on sub-DB, just store it */
7515 flags |= F_DUPDATA|F_SUBDATA;
7518 /* Data is on sub-page */
7519 fp = olddata.mv_data;
7522 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7523 offset = EVEN(NODESIZE + sizeof(indx_t) +
7527 offset = fp->mp_pad;
7528 if (SIZELEFT(fp) < offset) {
7529 offset *= 4; /* space for 4 more */
7532 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
7534 fp->mp_flags |= P_DIRTY;
7535 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
7536 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
7540 xdata.mv_size = olddata.mv_size + offset;
7543 fp_flags = fp->mp_flags;
7544 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
7545 /* Too big for a sub-page, convert to sub-DB */
7546 fp_flags &= ~P_SUBP;
7548 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7549 fp_flags |= P_LEAF2;
7550 dummy.md_pad = fp->mp_pad;
7551 dummy.md_flags = MDB_DUPFIXED;
7552 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7553 dummy.md_flags |= MDB_INTEGERKEY;
7559 dummy.md_branch_pages = 0;
7560 dummy.md_leaf_pages = 1;
7561 dummy.md_overflow_pages = 0;
7562 dummy.md_entries = NUMKEYS(fp);
7563 xdata.mv_size = sizeof(MDB_db);
7564 xdata.mv_data = &dummy;
7565 if ((rc = mdb_page_alloc(mc, 1, &mp)))
7567 offset = env->me_psize - olddata.mv_size;
7568 flags |= F_DUPDATA|F_SUBDATA;
7569 dummy.md_root = mp->mp_pgno;
7573 mp->mp_flags = fp_flags | P_DIRTY;
7574 mp->mp_pad = fp->mp_pad;
7575 mp->mp_lower = fp->mp_lower;
7576 mp->mp_upper = fp->mp_upper + offset;
7577 if (fp_flags & P_LEAF2) {
7578 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
7580 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
7581 olddata.mv_size - fp->mp_upper - PAGEBASE);
7582 for (i=0; i<NUMKEYS(fp); i++)
7583 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
7591 mdb_node_del(mc, 0);
7595 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
7596 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
7597 return MDB_INCOMPATIBLE;
7598 /* overflow page overwrites need special handling */
7599 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7602 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
7604 memcpy(&pg, olddata.mv_data, sizeof(pg));
7605 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
7607 ovpages = omp->mp_pages;
7609 /* Is the ov page large enough? */
7610 if (ovpages >= dpages) {
7611 if (!(omp->mp_flags & P_DIRTY) &&
7612 (level || (env->me_flags & MDB_WRITEMAP)))
7614 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
7617 level = 0; /* dirty in this txn or clean */
7620 if (omp->mp_flags & P_DIRTY) {
7621 /* yes, overwrite it. Note in this case we don't
7622 * bother to try shrinking the page if the new data
7623 * is smaller than the overflow threshold.
7626 /* It is writable only in a parent txn */
7627 size_t sz = (size_t) env->me_psize * ovpages, off;
7628 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
7634 /* Note - this page is already counted in parent's dirty_room */
7635 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
7636 mdb_cassert(mc, rc2 == 0);
7637 /* Currently we make the page look as with put() in the
7638 * parent txn, in case the user peeks at MDB_RESERVEd
7639 * or unused parts. Some users treat ovpages specially.
7641 if (!(flags & MDB_RESERVE)) {
7642 /* Skip the part where LMDB will put *data.
7643 * Copy end of page, adjusting alignment so
7644 * compiler may copy words instead of bytes.
7646 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
7647 memcpy((size_t *)((char *)np + off),
7648 (size_t *)((char *)omp + off), sz - off);
7651 memcpy(np, omp, sz); /* Copy beginning of page */
7654 SETDSZ(leaf, data->mv_size);
7655 if (F_ISSET(flags, MDB_RESERVE))
7656 data->mv_data = METADATA(omp);
7658 memcpy(METADATA(omp), data->mv_data, data->mv_size);
7662 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
7664 } else if (data->mv_size == olddata.mv_size) {
7665 /* same size, just replace it. Note that we could
7666 * also reuse this node if the new data is smaller,
7667 * but instead we opt to shrink the node in that case.
7669 if (F_ISSET(flags, MDB_RESERVE))
7670 data->mv_data = olddata.mv_data;
7671 else if (!(mc->mc_flags & C_SUB))
7672 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
7674 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
7679 mdb_node_del(mc, 0);
7685 nflags = flags & NODE_ADD_FLAGS;
7686 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
7687 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
7688 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
7689 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
7691 nflags |= MDB_SPLIT_REPLACE;
7692 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
7694 /* There is room already in this leaf page. */
7695 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
7697 /* Adjust other cursors pointing to mp */
7698 MDB_cursor *m2, *m3;
7699 MDB_dbi dbi = mc->mc_dbi;
7700 unsigned i = mc->mc_top;
7701 MDB_page *mp = mc->mc_pg[i];
7703 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7704 if (mc->mc_flags & C_SUB)
7705 m3 = &m2->mc_xcursor->mx_cursor;
7708 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
7709 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
7712 if (XCURSOR_INITED(m3))
7713 XCURSOR_REFRESH(m3, mp, m3->mc_ki[i]);
7718 if (rc == MDB_SUCCESS) {
7719 /* Now store the actual data in the child DB. Note that we're
7720 * storing the user data in the keys field, so there are strict
7721 * size limits on dupdata. The actual data fields of the child
7722 * DB are all zero size.
7725 int xflags, new_dupdata;
7730 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7731 if (flags & MDB_CURRENT) {
7732 xflags = MDB_CURRENT|MDB_NOSPILL;
7734 mdb_xcursor_init1(mc, leaf);
7735 xflags = (flags & MDB_NODUPDATA) ?
7736 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
7739 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
7740 new_dupdata = (int)dkey.mv_size;
7741 /* converted, write the original data first */
7743 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
7746 /* we've done our job */
7749 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
7750 /* Adjust other cursors pointing to mp */
7752 MDB_xcursor *mx = mc->mc_xcursor;
7753 unsigned i = mc->mc_top;
7754 MDB_page *mp = mc->mc_pg[i];
7755 int nkeys = NUMKEYS(mp);
7757 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7758 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7759 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7760 if (m2->mc_pg[i] == mp) {
7761 if (m2->mc_ki[i] == mc->mc_ki[i]) {
7762 mdb_xcursor_init2(m2, mx, new_dupdata);
7763 } else if (!insert_key && m2->mc_ki[i] < nkeys) {
7764 XCURSOR_REFRESH(m2, mp, m2->mc_ki[i]);
7769 ecount = mc->mc_xcursor->mx_db.md_entries;
7770 if (flags & MDB_APPENDDUP)
7771 xflags |= MDB_APPEND;
7772 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
7773 if (flags & F_SUBDATA) {
7774 void *db = NODEDATA(leaf);
7775 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7777 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
7779 /* Increment count unless we just replaced an existing item. */
7781 mc->mc_db->md_entries++;
7783 /* Invalidate txn if we created an empty sub-DB */
7786 /* If we succeeded and the key didn't exist before,
7787 * make sure the cursor is marked valid.
7789 mc->mc_flags |= C_INITIALIZED;
7791 if (flags & MDB_MULTIPLE) {
7794 /* let caller know how many succeeded, if any */
7795 data[1].mv_size = mcount;
7796 if (mcount < dcount) {
7797 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
7798 insert_key = insert_data = 0;
7805 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
7808 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7813 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
7819 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7820 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7822 if (!(mc->mc_flags & C_INITIALIZED))
7825 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
7826 return MDB_NOTFOUND;
7828 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
7831 rc = mdb_cursor_touch(mc);
7835 mp = mc->mc_pg[mc->mc_top];
7838 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7840 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7841 if (flags & MDB_NODUPDATA) {
7842 /* mdb_cursor_del0() will subtract the final entry */
7843 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
7844 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7846 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
7847 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7849 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
7852 /* If sub-DB still has entries, we're done */
7853 if (mc->mc_xcursor->mx_db.md_entries) {
7854 if (leaf->mn_flags & F_SUBDATA) {
7855 /* update subDB info */
7856 void *db = NODEDATA(leaf);
7857 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7860 /* shrink fake page */
7861 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
7862 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7863 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7864 /* fix other sub-DB cursors pointed at fake pages on this page */
7865 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7866 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7867 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7868 if (m2->mc_pg[mc->mc_top] == mp) {
7869 MDB_node *n2 = leaf;
7870 if (m2->mc_ki[mc->mc_top] != mc->mc_ki[mc->mc_top]) {
7871 n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
7872 if (n2->mn_flags & F_SUBDATA) continue;
7874 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7878 mc->mc_db->md_entries--;
7881 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7883 /* otherwise fall thru and delete the sub-DB */
7886 if (leaf->mn_flags & F_SUBDATA) {
7887 /* add all the child DB's pages to the free list */
7888 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7893 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
7894 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
7895 rc = MDB_INCOMPATIBLE;
7899 /* add overflow pages to free list */
7900 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7904 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7905 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
7906 (rc = mdb_ovpage_free(mc, omp)))
7911 return mdb_cursor_del0(mc);
7914 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7918 /** Allocate and initialize new pages for a database.
7919 * Set #MDB_TXN_ERROR on failure.
7920 * @param[in] mc a cursor on the database being added to.
7921 * @param[in] flags flags defining what type of page is being allocated.
7922 * @param[in] num the number of pages to allocate. This is usually 1,
7923 * unless allocating overflow pages for a large record.
7924 * @param[out] mp Address of a page, or NULL on failure.
7925 * @return 0 on success, non-zero on failure.
7928 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
7933 if ((rc = mdb_page_alloc(mc, num, &np)))
7935 DPRINTF(("allocated new mpage %"Yu", page size %u",
7936 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
7937 np->mp_flags = flags | P_DIRTY;
7938 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
7939 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
7942 mc->mc_db->md_branch_pages++;
7943 else if (IS_LEAF(np))
7944 mc->mc_db->md_leaf_pages++;
7945 else if (IS_OVERFLOW(np)) {
7946 mc->mc_db->md_overflow_pages += num;
7954 /** Calculate the size of a leaf node.
7955 * The size depends on the environment's page size; if a data item
7956 * is too large it will be put onto an overflow page and the node
7957 * size will only include the key and not the data. Sizes are always
7958 * rounded up to an even number of bytes, to guarantee 2-byte alignment
7959 * of the #MDB_node headers.
7960 * @param[in] env The environment handle.
7961 * @param[in] key The key for the node.
7962 * @param[in] data The data for the node.
7963 * @return The number of bytes needed to store the node.
7966 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
7970 sz = LEAFSIZE(key, data);
7971 if (sz > env->me_nodemax) {
7972 /* put on overflow page */
7973 sz -= data->mv_size - sizeof(pgno_t);
7976 return EVEN(sz + sizeof(indx_t));
7979 /** Calculate the size of a branch node.
7980 * The size should depend on the environment's page size but since
7981 * we currently don't support spilling large keys onto overflow
7982 * pages, it's simply the size of the #MDB_node header plus the
7983 * size of the key. Sizes are always rounded up to an even number
7984 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7985 * @param[in] env The environment handle.
7986 * @param[in] key The key for the node.
7987 * @return The number of bytes needed to store the node.
7990 mdb_branch_size(MDB_env *env, MDB_val *key)
7995 if (sz > env->me_nodemax) {
7996 /* put on overflow page */
7997 /* not implemented */
7998 /* sz -= key->size - sizeof(pgno_t); */
8001 return sz + sizeof(indx_t);
8004 /** Add a node to the page pointed to by the cursor.
8005 * Set #MDB_TXN_ERROR on failure.
8006 * @param[in] mc The cursor for this operation.
8007 * @param[in] indx The index on the page where the new node should be added.
8008 * @param[in] key The key for the new node.
8009 * @param[in] data The data for the new node, if any.
8010 * @param[in] pgno The page number, if adding a branch node.
8011 * @param[in] flags Flags for the node.
8012 * @return 0 on success, non-zero on failure. Possible errors are:
8014 * <li>ENOMEM - failed to allocate overflow pages for the node.
8015 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
8016 * should never happen since all callers already calculate the
8017 * page's free space before calling this function.
8021 mdb_node_add(MDB_cursor *mc, indx_t indx,
8022 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
8025 size_t node_size = NODESIZE;
8029 MDB_page *mp = mc->mc_pg[mc->mc_top];
8030 MDB_page *ofp = NULL; /* overflow page */
8034 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
8036 DPRINTF(("add to %s %spage %"Yu" index %i, data size %"Z"u key size %"Z"u [%s]",
8037 IS_LEAF(mp) ? "leaf" : "branch",
8038 IS_SUBP(mp) ? "sub-" : "",
8039 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
8040 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
8043 /* Move higher keys up one slot. */
8044 int ksize = mc->mc_db->md_pad, dif;
8045 char *ptr = LEAF2KEY(mp, indx, ksize);
8046 dif = NUMKEYS(mp) - indx;
8048 memmove(ptr+ksize, ptr, dif*ksize);
8049 /* insert new key */
8050 memcpy(ptr, key->mv_data, ksize);
8052 /* Just using these for counting */
8053 mp->mp_lower += sizeof(indx_t);
8054 mp->mp_upper -= ksize - sizeof(indx_t);
8058 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
8060 node_size += key->mv_size;
8062 mdb_cassert(mc, key && data);
8063 if (F_ISSET(flags, F_BIGDATA)) {
8064 /* Data already on overflow page. */
8065 node_size += sizeof(pgno_t);
8066 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
8067 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
8069 /* Put data on overflow page. */
8070 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
8071 data->mv_size, node_size+data->mv_size));
8072 node_size = EVEN(node_size + sizeof(pgno_t));
8073 if ((ssize_t)node_size > room)
8075 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
8077 DPRINTF(("allocated overflow page %"Yu, ofp->mp_pgno));
8081 node_size += data->mv_size;
8084 node_size = EVEN(node_size);
8085 if ((ssize_t)node_size > room)
8089 /* Move higher pointers up one slot. */
8090 for (i = NUMKEYS(mp); i > indx; i--)
8091 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
8093 /* Adjust free space offsets. */
8094 ofs = mp->mp_upper - node_size;
8095 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
8096 mp->mp_ptrs[indx] = ofs;
8098 mp->mp_lower += sizeof(indx_t);
8100 /* Write the node data. */
8101 node = NODEPTR(mp, indx);
8102 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
8103 node->mn_flags = flags;
8105 SETDSZ(node,data->mv_size);
8110 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8113 ndata = NODEDATA(node);
8115 if (F_ISSET(flags, F_BIGDATA))
8116 memcpy(ndata, data->mv_data, sizeof(pgno_t));
8117 else if (F_ISSET(flags, MDB_RESERVE))
8118 data->mv_data = ndata;
8120 memcpy(ndata, data->mv_data, data->mv_size);
8122 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
8123 ndata = METADATA(ofp);
8124 if (F_ISSET(flags, MDB_RESERVE))
8125 data->mv_data = ndata;
8127 memcpy(ndata, data->mv_data, data->mv_size);
8134 DPRINTF(("not enough room in page %"Yu", got %u ptrs",
8135 mdb_dbg_pgno(mp), NUMKEYS(mp)));
8136 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
8137 DPRINTF(("node size = %"Z"u", node_size));
8138 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8139 return MDB_PAGE_FULL;
8142 /** Delete the specified node from a page.
8143 * @param[in] mc Cursor pointing to the node to delete.
8144 * @param[in] ksize The size of a node. Only used if the page is
8145 * part of a #MDB_DUPFIXED database.
8148 mdb_node_del(MDB_cursor *mc, int ksize)
8150 MDB_page *mp = mc->mc_pg[mc->mc_top];
8151 indx_t indx = mc->mc_ki[mc->mc_top];
8153 indx_t i, j, numkeys, ptr;
8157 DPRINTF(("delete node %u on %s page %"Yu, indx,
8158 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
8159 numkeys = NUMKEYS(mp);
8160 mdb_cassert(mc, indx < numkeys);
8163 int x = numkeys - 1 - indx;
8164 base = LEAF2KEY(mp, indx, ksize);
8166 memmove(base, base + ksize, x * ksize);
8167 mp->mp_lower -= sizeof(indx_t);
8168 mp->mp_upper += ksize - sizeof(indx_t);
8172 node = NODEPTR(mp, indx);
8173 sz = NODESIZE + node->mn_ksize;
8175 if (F_ISSET(node->mn_flags, F_BIGDATA))
8176 sz += sizeof(pgno_t);
8178 sz += NODEDSZ(node);
8182 ptr = mp->mp_ptrs[indx];
8183 for (i = j = 0; i < numkeys; i++) {
8185 mp->mp_ptrs[j] = mp->mp_ptrs[i];
8186 if (mp->mp_ptrs[i] < ptr)
8187 mp->mp_ptrs[j] += sz;
8192 base = (char *)mp + mp->mp_upper + PAGEBASE;
8193 memmove(base + sz, base, ptr - mp->mp_upper);
8195 mp->mp_lower -= sizeof(indx_t);
8199 /** Compact the main page after deleting a node on a subpage.
8200 * @param[in] mp The main page to operate on.
8201 * @param[in] indx The index of the subpage on the main page.
8204 mdb_node_shrink(MDB_page *mp, indx_t indx)
8209 indx_t delta, nsize, len, ptr;
8212 node = NODEPTR(mp, indx);
8213 sp = (MDB_page *)NODEDATA(node);
8214 delta = SIZELEFT(sp);
8215 nsize = NODEDSZ(node) - delta;
8217 /* Prepare to shift upward, set len = length(subpage part to shift) */
8221 return; /* do not make the node uneven-sized */
8223 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
8224 for (i = NUMKEYS(sp); --i >= 0; )
8225 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
8228 sp->mp_upper = sp->mp_lower;
8229 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
8230 SETDSZ(node, nsize);
8232 /* Shift <lower nodes...initial part of subpage> upward */
8233 base = (char *)mp + mp->mp_upper + PAGEBASE;
8234 memmove(base + delta, base, (char *)sp + len - base);
8236 ptr = mp->mp_ptrs[indx];
8237 for (i = NUMKEYS(mp); --i >= 0; ) {
8238 if (mp->mp_ptrs[i] <= ptr)
8239 mp->mp_ptrs[i] += delta;
8241 mp->mp_upper += delta;
8244 /** Initial setup of a sorted-dups cursor.
8245 * Sorted duplicates are implemented as a sub-database for the given key.
8246 * The duplicate data items are actually keys of the sub-database.
8247 * Operations on the duplicate data items are performed using a sub-cursor
8248 * initialized when the sub-database is first accessed. This function does
8249 * the preliminary setup of the sub-cursor, filling in the fields that
8250 * depend only on the parent DB.
8251 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8254 mdb_xcursor_init0(MDB_cursor *mc)
8256 MDB_xcursor *mx = mc->mc_xcursor;
8258 mx->mx_cursor.mc_xcursor = NULL;
8259 mx->mx_cursor.mc_txn = mc->mc_txn;
8260 mx->mx_cursor.mc_db = &mx->mx_db;
8261 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
8262 mx->mx_cursor.mc_dbi = mc->mc_dbi;
8263 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
8264 mx->mx_cursor.mc_snum = 0;
8265 mx->mx_cursor.mc_top = 0;
8266 MC_SET_OVPG(&mx->mx_cursor, NULL);
8267 mx->mx_cursor.mc_flags = C_SUB | (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP));
8268 mx->mx_dbx.md_name.mv_size = 0;
8269 mx->mx_dbx.md_name.mv_data = NULL;
8270 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
8271 mx->mx_dbx.md_dcmp = NULL;
8272 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
8275 /** Final setup of a sorted-dups cursor.
8276 * Sets up the fields that depend on the data from the main cursor.
8277 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8278 * @param[in] node The data containing the #MDB_db record for the
8279 * sorted-dup database.
8282 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
8284 MDB_xcursor *mx = mc->mc_xcursor;
8286 mx->mx_cursor.mc_flags &= C_SUB|C_ORIG_RDONLY|C_WRITEMAP;
8287 if (node->mn_flags & F_SUBDATA) {
8288 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
8289 mx->mx_cursor.mc_pg[0] = 0;
8290 mx->mx_cursor.mc_snum = 0;
8291 mx->mx_cursor.mc_top = 0;
8293 MDB_page *fp = NODEDATA(node);
8294 mx->mx_db.md_pad = 0;
8295 mx->mx_db.md_flags = 0;
8296 mx->mx_db.md_depth = 1;
8297 mx->mx_db.md_branch_pages = 0;
8298 mx->mx_db.md_leaf_pages = 1;
8299 mx->mx_db.md_overflow_pages = 0;
8300 mx->mx_db.md_entries = NUMKEYS(fp);
8301 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
8302 mx->mx_cursor.mc_snum = 1;
8303 mx->mx_cursor.mc_top = 0;
8304 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8305 mx->mx_cursor.mc_pg[0] = fp;
8306 mx->mx_cursor.mc_ki[0] = 0;
8307 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
8308 mx->mx_db.md_flags = MDB_DUPFIXED;
8309 mx->mx_db.md_pad = fp->mp_pad;
8310 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
8311 mx->mx_db.md_flags |= MDB_INTEGERKEY;
8314 DPRINTF(("Sub-db -%u root page %"Yu, mx->mx_cursor.mc_dbi,
8315 mx->mx_db.md_root));
8316 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
8317 if (NEED_CMP_CLONG(mx->mx_dbx.md_cmp, mx->mx_db.md_pad))
8318 mx->mx_dbx.md_cmp = mdb_cmp_clong;
8322 /** Fixup a sorted-dups cursor due to underlying update.
8323 * Sets up some fields that depend on the data from the main cursor.
8324 * Almost the same as init1, but skips initialization steps if the
8325 * xcursor had already been used.
8326 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
8327 * @param[in] src_mx The xcursor of an up-to-date cursor.
8328 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
8331 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
8333 MDB_xcursor *mx = mc->mc_xcursor;
8336 mx->mx_cursor.mc_snum = 1;
8337 mx->mx_cursor.mc_top = 0;
8338 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8339 mx->mx_cursor.mc_ki[0] = 0;
8340 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
8341 #if UINT_MAX < MDB_SIZE_MAX /* matches mdb_xcursor_init1:NEED_CMP_CLONG() */
8342 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
8344 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
8347 mx->mx_db = src_mx->mx_db;
8348 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
8349 DPRINTF(("Sub-db -%u root page %"Yu, mx->mx_cursor.mc_dbi,
8350 mx->mx_db.md_root));
8353 /** Initialize a cursor for a given transaction and database. */
8355 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
8358 mc->mc_backup = NULL;
8361 mc->mc_db = &txn->mt_dbs[dbi];
8362 mc->mc_dbx = &txn->mt_dbxs[dbi];
8363 mc->mc_dbflag = &txn->mt_dbflags[dbi];
8368 MC_SET_OVPG(mc, NULL);
8369 mc->mc_flags = txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
8370 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
8371 mdb_tassert(txn, mx != NULL);
8372 mc->mc_xcursor = mx;
8373 mdb_xcursor_init0(mc);
8375 mc->mc_xcursor = NULL;
8377 if (*mc->mc_dbflag & DB_STALE) {
8378 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
8383 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
8386 size_t size = sizeof(MDB_cursor);
8388 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
8391 if (txn->mt_flags & MDB_TXN_BLOCKED)
8394 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8397 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
8398 size += sizeof(MDB_xcursor);
8400 if ((mc = malloc(size)) != NULL) {
8401 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
8402 if (txn->mt_cursors) {
8403 mc->mc_next = txn->mt_cursors[dbi];
8404 txn->mt_cursors[dbi] = mc;
8405 mc->mc_flags |= C_UNTRACK;
8417 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
8419 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
8422 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
8425 if (txn->mt_flags & MDB_TXN_BLOCKED)
8428 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
8432 /* Return the count of duplicate data items for the current key */
8434 mdb_cursor_count(MDB_cursor *mc, mdb_size_t *countp)
8438 if (mc == NULL || countp == NULL)
8441 if (mc->mc_xcursor == NULL)
8442 return MDB_INCOMPATIBLE;
8444 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
8447 if (!(mc->mc_flags & C_INITIALIZED))
8451 return MDB_NOTFOUND;
8453 if (mc->mc_flags & C_EOF) {
8454 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
8455 return MDB_NOTFOUND;
8456 mc->mc_flags ^= C_EOF;
8459 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8460 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
8463 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
8466 *countp = mc->mc_xcursor->mx_db.md_entries;
8472 mdb_cursor_close(MDB_cursor *mc)
8475 MDB_CURSOR_UNREF(mc, 0);
8477 if (mc && !mc->mc_backup) {
8478 /* Remove from txn, if tracked.
8479 * A read-only txn (!C_UNTRACK) may have been freed already,
8480 * so do not peek inside it. Only write txns track cursors.
8482 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
8483 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
8484 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
8486 *prev = mc->mc_next;
8493 mdb_cursor_txn(MDB_cursor *mc)
8495 if (!mc) return NULL;
8500 mdb_cursor_dbi(MDB_cursor *mc)
8505 /** Replace the key for a branch node with a new key.
8506 * Set #MDB_TXN_ERROR on failure.
8507 * @param[in] mc Cursor pointing to the node to operate on.
8508 * @param[in] key The new key to use.
8509 * @return 0 on success, non-zero on failure.
8512 mdb_update_key(MDB_cursor *mc, MDB_val *key)
8518 int delta, ksize, oksize;
8519 indx_t ptr, i, numkeys, indx;
8522 indx = mc->mc_ki[mc->mc_top];
8523 mp = mc->mc_pg[mc->mc_top];
8524 node = NODEPTR(mp, indx);
8525 ptr = mp->mp_ptrs[indx];
8529 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
8530 k2.mv_data = NODEKEY(node);
8531 k2.mv_size = node->mn_ksize;
8532 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Yu,
8534 mdb_dkey(&k2, kbuf2),
8540 /* Sizes must be 2-byte aligned. */
8541 ksize = EVEN(key->mv_size);
8542 oksize = EVEN(node->mn_ksize);
8543 delta = ksize - oksize;
8545 /* Shift node contents if EVEN(key length) changed. */
8547 if (delta > 0 && SIZELEFT(mp) < delta) {
8549 /* not enough space left, do a delete and split */
8550 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
8551 pgno = NODEPGNO(node);
8552 mdb_node_del(mc, 0);
8553 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
8556 numkeys = NUMKEYS(mp);
8557 for (i = 0; i < numkeys; i++) {
8558 if (mp->mp_ptrs[i] <= ptr)
8559 mp->mp_ptrs[i] -= delta;
8562 base = (char *)mp + mp->mp_upper + PAGEBASE;
8563 len = ptr - mp->mp_upper + NODESIZE;
8564 memmove(base - delta, base, len);
8565 mp->mp_upper -= delta;
8567 node = NODEPTR(mp, indx);
8570 /* But even if no shift was needed, update ksize */
8571 if (node->mn_ksize != key->mv_size)
8572 node->mn_ksize = key->mv_size;
8575 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8581 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
8583 /** Perform \b act while tracking temporary cursor \b mn */
8584 #define WITH_CURSOR_TRACKING(mn, act) do { \
8585 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
8586 if ((mn).mc_flags & C_SUB) { \
8587 dummy.mc_flags = C_INITIALIZED; \
8588 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
8593 tracked->mc_next = *tp; \
8596 *tp = tracked->mc_next; \
8599 /** Move a node from csrc to cdst.
8602 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
8609 unsigned short flags;
8613 /* Mark src and dst as dirty. */
8614 if ((rc = mdb_page_touch(csrc)) ||
8615 (rc = mdb_page_touch(cdst)))
8618 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8619 key.mv_size = csrc->mc_db->md_pad;
8620 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
8622 data.mv_data = NULL;
8626 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
8627 mdb_cassert(csrc, !((size_t)srcnode & 1));
8628 srcpg = NODEPGNO(srcnode);
8629 flags = srcnode->mn_flags;
8630 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8631 unsigned int snum = csrc->mc_snum;
8633 /* must find the lowest key below src */
8634 rc = mdb_page_search_lowest(csrc);
8637 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8638 key.mv_size = csrc->mc_db->md_pad;
8639 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8641 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8642 key.mv_size = NODEKSZ(s2);
8643 key.mv_data = NODEKEY(s2);
8645 csrc->mc_snum = snum--;
8646 csrc->mc_top = snum;
8648 key.mv_size = NODEKSZ(srcnode);
8649 key.mv_data = NODEKEY(srcnode);
8651 data.mv_size = NODEDSZ(srcnode);
8652 data.mv_data = NODEDATA(srcnode);
8654 mn.mc_xcursor = NULL;
8655 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
8656 unsigned int snum = cdst->mc_snum;
8659 /* must find the lowest key below dst */
8660 mdb_cursor_copy(cdst, &mn);
8661 rc = mdb_page_search_lowest(&mn);
8664 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8665 bkey.mv_size = mn.mc_db->md_pad;
8666 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
8668 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8669 bkey.mv_size = NODEKSZ(s2);
8670 bkey.mv_data = NODEKEY(s2);
8672 mn.mc_snum = snum--;
8675 rc = mdb_update_key(&mn, &bkey);
8680 DPRINTF(("moving %s node %u [%s] on page %"Yu" to node %u on page %"Yu,
8681 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
8682 csrc->mc_ki[csrc->mc_top],
8684 csrc->mc_pg[csrc->mc_top]->mp_pgno,
8685 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
8687 /* Add the node to the destination page.
8689 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
8690 if (rc != MDB_SUCCESS)
8693 /* Delete the node from the source page.
8695 mdb_node_del(csrc, key.mv_size);
8698 /* Adjust other cursors pointing to mp */
8699 MDB_cursor *m2, *m3;
8700 MDB_dbi dbi = csrc->mc_dbi;
8701 MDB_page *mpd, *mps;
8703 mps = csrc->mc_pg[csrc->mc_top];
8704 /* If we're adding on the left, bump others up */
8706 mpd = cdst->mc_pg[csrc->mc_top];
8707 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8708 if (csrc->mc_flags & C_SUB)
8709 m3 = &m2->mc_xcursor->mx_cursor;
8712 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8715 m3->mc_pg[csrc->mc_top] == mpd &&
8716 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
8717 m3->mc_ki[csrc->mc_top]++;
8720 m3->mc_pg[csrc->mc_top] == mps &&
8721 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
8722 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8723 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8724 m3->mc_ki[csrc->mc_top-1]++;
8726 if (XCURSOR_INITED(m3) && IS_LEAF(mps))
8727 XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8730 /* Adding on the right, bump others down */
8732 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8733 if (csrc->mc_flags & C_SUB)
8734 m3 = &m2->mc_xcursor->mx_cursor;
8737 if (m3 == csrc) continue;
8738 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8740 if (m3->mc_pg[csrc->mc_top] == mps) {
8741 if (!m3->mc_ki[csrc->mc_top]) {
8742 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8743 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8744 m3->mc_ki[csrc->mc_top-1]--;
8746 m3->mc_ki[csrc->mc_top]--;
8748 if (XCURSOR_INITED(m3) && IS_LEAF(mps))
8749 XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8755 /* Update the parent separators.
8757 if (csrc->mc_ki[csrc->mc_top] == 0) {
8758 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
8759 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8760 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8762 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8763 key.mv_size = NODEKSZ(srcnode);
8764 key.mv_data = NODEKEY(srcnode);
8766 DPRINTF(("update separator for source page %"Yu" to [%s]",
8767 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
8768 mdb_cursor_copy(csrc, &mn);
8771 /* We want mdb_rebalance to find mn when doing fixups */
8772 WITH_CURSOR_TRACKING(mn,
8773 rc = mdb_update_key(&mn, &key));
8777 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8779 indx_t ix = csrc->mc_ki[csrc->mc_top];
8780 nullkey.mv_size = 0;
8781 csrc->mc_ki[csrc->mc_top] = 0;
8782 rc = mdb_update_key(csrc, &nullkey);
8783 csrc->mc_ki[csrc->mc_top] = ix;
8784 mdb_cassert(csrc, rc == MDB_SUCCESS);
8788 if (cdst->mc_ki[cdst->mc_top] == 0) {
8789 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
8790 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8791 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
8793 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
8794 key.mv_size = NODEKSZ(srcnode);
8795 key.mv_data = NODEKEY(srcnode);
8797 DPRINTF(("update separator for destination page %"Yu" to [%s]",
8798 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
8799 mdb_cursor_copy(cdst, &mn);
8802 /* We want mdb_rebalance to find mn when doing fixups */
8803 WITH_CURSOR_TRACKING(mn,
8804 rc = mdb_update_key(&mn, &key));
8808 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
8810 indx_t ix = cdst->mc_ki[cdst->mc_top];
8811 nullkey.mv_size = 0;
8812 cdst->mc_ki[cdst->mc_top] = 0;
8813 rc = mdb_update_key(cdst, &nullkey);
8814 cdst->mc_ki[cdst->mc_top] = ix;
8815 mdb_cassert(cdst, rc == MDB_SUCCESS);
8822 /** Merge one page into another.
8823 * The nodes from the page pointed to by \b csrc will
8824 * be copied to the page pointed to by \b cdst and then
8825 * the \b csrc page will be freed.
8826 * @param[in] csrc Cursor pointing to the source page.
8827 * @param[in] cdst Cursor pointing to the destination page.
8828 * @return 0 on success, non-zero on failure.
8831 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
8833 MDB_page *psrc, *pdst;
8840 psrc = csrc->mc_pg[csrc->mc_top];
8841 pdst = cdst->mc_pg[cdst->mc_top];
8843 DPRINTF(("merging page %"Yu" into %"Yu, psrc->mp_pgno, pdst->mp_pgno));
8845 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
8846 mdb_cassert(csrc, cdst->mc_snum > 1);
8848 /* Mark dst as dirty. */
8849 if ((rc = mdb_page_touch(cdst)))
8852 /* get dst page again now that we've touched it. */
8853 pdst = cdst->mc_pg[cdst->mc_top];
8855 /* Move all nodes from src to dst.
8857 j = nkeys = NUMKEYS(pdst);
8858 if (IS_LEAF2(psrc)) {
8859 key.mv_size = csrc->mc_db->md_pad;
8860 key.mv_data = METADATA(psrc);
8861 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8862 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
8863 if (rc != MDB_SUCCESS)
8865 key.mv_data = (char *)key.mv_data + key.mv_size;
8868 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8869 srcnode = NODEPTR(psrc, i);
8870 if (i == 0 && IS_BRANCH(psrc)) {
8873 mdb_cursor_copy(csrc, &mn);
8874 mn.mc_xcursor = NULL;
8875 /* must find the lowest key below src */
8876 rc = mdb_page_search_lowest(&mn);
8879 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8880 key.mv_size = mn.mc_db->md_pad;
8881 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
8883 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8884 key.mv_size = NODEKSZ(s2);
8885 key.mv_data = NODEKEY(s2);
8888 key.mv_size = srcnode->mn_ksize;
8889 key.mv_data = NODEKEY(srcnode);
8892 data.mv_size = NODEDSZ(srcnode);
8893 data.mv_data = NODEDATA(srcnode);
8894 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
8895 if (rc != MDB_SUCCESS)
8900 DPRINTF(("dst page %"Yu" now has %u keys (%.1f%% filled)",
8901 pdst->mp_pgno, NUMKEYS(pdst),
8902 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
8904 /* Unlink the src page from parent and add to free list.
8907 mdb_node_del(csrc, 0);
8908 if (csrc->mc_ki[csrc->mc_top] == 0) {
8910 rc = mdb_update_key(csrc, &key);
8918 psrc = csrc->mc_pg[csrc->mc_top];
8919 /* If not operating on FreeDB, allow this page to be reused
8920 * in this txn. Otherwise just add to free list.
8922 rc = mdb_page_loose(csrc, psrc);
8926 csrc->mc_db->md_leaf_pages--;
8928 csrc->mc_db->md_branch_pages--;
8930 /* Adjust other cursors pointing to mp */
8931 MDB_cursor *m2, *m3;
8932 MDB_dbi dbi = csrc->mc_dbi;
8933 unsigned int top = csrc->mc_top;
8935 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8936 if (csrc->mc_flags & C_SUB)
8937 m3 = &m2->mc_xcursor->mx_cursor;
8940 if (m3 == csrc) continue;
8941 if (m3->mc_snum < csrc->mc_snum) continue;
8942 if (m3->mc_pg[top] == psrc) {
8943 m3->mc_pg[top] = pdst;
8944 m3->mc_ki[top] += nkeys;
8945 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
8946 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
8947 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
8950 if (XCURSOR_INITED(m3) && IS_LEAF(psrc))
8951 XCURSOR_REFRESH(m3, m3->mc_pg[top], m3->mc_ki[top]);
8955 unsigned int snum = cdst->mc_snum;
8956 uint16_t depth = cdst->mc_db->md_depth;
8957 mdb_cursor_pop(cdst);
8958 rc = mdb_rebalance(cdst);
8959 /* Did the tree height change? */
8960 if (depth != cdst->mc_db->md_depth)
8961 snum += cdst->mc_db->md_depth - depth;
8962 cdst->mc_snum = snum;
8963 cdst->mc_top = snum-1;
8968 /** Copy the contents of a cursor.
8969 * @param[in] csrc The cursor to copy from.
8970 * @param[out] cdst The cursor to copy to.
8973 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
8977 cdst->mc_txn = csrc->mc_txn;
8978 cdst->mc_dbi = csrc->mc_dbi;
8979 cdst->mc_db = csrc->mc_db;
8980 cdst->mc_dbx = csrc->mc_dbx;
8981 cdst->mc_snum = csrc->mc_snum;
8982 cdst->mc_top = csrc->mc_top;
8983 cdst->mc_flags = csrc->mc_flags;
8984 MC_SET_OVPG(cdst, MC_OVPG(csrc));
8986 for (i=0; i<csrc->mc_snum; i++) {
8987 cdst->mc_pg[i] = csrc->mc_pg[i];
8988 cdst->mc_ki[i] = csrc->mc_ki[i];
8992 /** Rebalance the tree after a delete operation.
8993 * @param[in] mc Cursor pointing to the page where rebalancing
8995 * @return 0 on success, non-zero on failure.
8998 mdb_rebalance(MDB_cursor *mc)
9002 unsigned int ptop, minkeys, thresh;
9006 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
9011 thresh = FILL_THRESHOLD;
9013 DPRINTF(("rebalancing %s page %"Yu" (has %u keys, %.1f%% full)",
9014 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
9015 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
9016 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
9018 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
9019 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
9020 DPRINTF(("no need to rebalance page %"Yu", above fill threshold",
9021 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
9025 if (mc->mc_snum < 2) {
9026 MDB_page *mp = mc->mc_pg[0];
9028 DPUTS("Can't rebalance a subpage, ignoring");
9031 if (NUMKEYS(mp) == 0) {
9032 DPUTS("tree is completely empty");
9033 mc->mc_db->md_root = P_INVALID;
9034 mc->mc_db->md_depth = 0;
9035 mc->mc_db->md_leaf_pages = 0;
9036 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
9039 /* Adjust cursors pointing to mp */
9042 mc->mc_flags &= ~C_INITIALIZED;
9044 MDB_cursor *m2, *m3;
9045 MDB_dbi dbi = mc->mc_dbi;
9047 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9048 if (mc->mc_flags & C_SUB)
9049 m3 = &m2->mc_xcursor->mx_cursor;
9052 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
9054 if (m3->mc_pg[0] == mp) {
9057 m3->mc_flags &= ~C_INITIALIZED;
9061 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
9063 DPUTS("collapsing root page!");
9064 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
9067 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
9068 rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
9071 mc->mc_db->md_depth--;
9072 mc->mc_db->md_branch_pages--;
9073 mc->mc_ki[0] = mc->mc_ki[1];
9074 for (i = 1; i<mc->mc_db->md_depth; i++) {
9075 mc->mc_pg[i] = mc->mc_pg[i+1];
9076 mc->mc_ki[i] = mc->mc_ki[i+1];
9079 /* Adjust other cursors pointing to mp */
9080 MDB_cursor *m2, *m3;
9081 MDB_dbi dbi = mc->mc_dbi;
9083 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9084 if (mc->mc_flags & C_SUB)
9085 m3 = &m2->mc_xcursor->mx_cursor;
9088 if (m3 == mc) continue;
9089 if (!(m3->mc_flags & C_INITIALIZED))
9091 if (m3->mc_pg[0] == mp) {
9092 for (i=0; i<mc->mc_db->md_depth; i++) {
9093 m3->mc_pg[i] = m3->mc_pg[i+1];
9094 m3->mc_ki[i] = m3->mc_ki[i+1];
9102 DPUTS("root page doesn't need rebalancing");
9106 /* The parent (branch page) must have at least 2 pointers,
9107 * otherwise the tree is invalid.
9109 ptop = mc->mc_top-1;
9110 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
9112 /* Leaf page fill factor is below the threshold.
9113 * Try to move keys from left or right neighbor, or
9114 * merge with a neighbor page.
9119 mdb_cursor_copy(mc, &mn);
9120 mn.mc_xcursor = NULL;
9122 oldki = mc->mc_ki[mc->mc_top];
9123 if (mc->mc_ki[ptop] == 0) {
9124 /* We're the leftmost leaf in our parent.
9126 DPUTS("reading right neighbor");
9128 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
9129 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
9132 mn.mc_ki[mn.mc_top] = 0;
9133 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
9136 /* There is at least one neighbor to the left.
9138 DPUTS("reading left neighbor");
9140 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
9141 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
9144 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
9145 mc->mc_ki[mc->mc_top] = 0;
9149 DPRINTF(("found neighbor page %"Yu" (%u keys, %.1f%% full)",
9150 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
9151 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
9153 /* If the neighbor page is above threshold and has enough keys,
9154 * move one key from it. Otherwise we should try to merge them.
9155 * (A branch page must never have less than 2 keys.)
9157 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
9158 rc = mdb_node_move(&mn, mc, fromleft);
9160 /* if we inserted on left, bump position up */
9165 rc = mdb_page_merge(&mn, mc);
9167 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
9168 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
9169 /* We want mdb_rebalance to find mn when doing fixups */
9170 WITH_CURSOR_TRACKING(mn,
9171 rc = mdb_page_merge(mc, &mn));
9172 mdb_cursor_copy(&mn, mc);
9174 mc->mc_flags &= ~C_EOF;
9176 mc->mc_ki[mc->mc_top] = oldki;
9180 /** Complete a delete operation started by #mdb_cursor_del(). */
9182 mdb_cursor_del0(MDB_cursor *mc)
9188 MDB_cursor *m2, *m3;
9189 MDB_dbi dbi = mc->mc_dbi;
9191 ki = mc->mc_ki[mc->mc_top];
9192 mp = mc->mc_pg[mc->mc_top];
9193 mdb_node_del(mc, mc->mc_db->md_pad);
9194 mc->mc_db->md_entries--;
9196 /* Adjust other cursors pointing to mp */
9197 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9198 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9199 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9201 if (m3 == mc || m3->mc_snum < mc->mc_snum)
9203 if (m3->mc_pg[mc->mc_top] == mp) {
9204 if (m3->mc_ki[mc->mc_top] == ki) {
9205 m3->mc_flags |= C_DEL;
9206 if (mc->mc_db->md_flags & MDB_DUPSORT) {
9207 /* Sub-cursor referred into dataset which is gone */
9208 m3->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
9211 } else if (m3->mc_ki[mc->mc_top] > ki) {
9212 m3->mc_ki[mc->mc_top]--;
9214 if (XCURSOR_INITED(m3))
9215 XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9219 rc = mdb_rebalance(mc);
9221 if (rc == MDB_SUCCESS) {
9222 /* DB is totally empty now, just bail out.
9223 * Other cursors adjustments were already done
9224 * by mdb_rebalance and aren't needed here.
9229 mp = mc->mc_pg[mc->mc_top];
9230 nkeys = NUMKEYS(mp);
9232 /* Adjust other cursors pointing to mp */
9233 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
9234 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9235 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9237 if (m3->mc_snum < mc->mc_snum)
9239 if (m3->mc_pg[mc->mc_top] == mp) {
9240 /* if m3 points past last node in page, find next sibling */
9241 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
9242 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9243 rc = mdb_cursor_sibling(m3, 1);
9244 if (rc == MDB_NOTFOUND) {
9245 m3->mc_flags |= C_EOF;
9250 if (mc->mc_db->md_flags & MDB_DUPSORT) {
9251 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
9252 /* If this node is a fake page, it needs to be reinited
9253 * because its data has moved. But just reset mc_pg[0]
9254 * if the xcursor is already live.
9256 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) {
9257 if (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)
9258 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
9260 mdb_xcursor_init1(m3, node);
9266 mc->mc_flags |= C_DEL;
9270 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9275 mdb_del(MDB_txn *txn, MDB_dbi dbi,
9276 MDB_val *key, MDB_val *data)
9278 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9281 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9282 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9284 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
9285 /* must ignore any data */
9289 return mdb_del0(txn, dbi, key, data, 0);
9293 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
9294 MDB_val *key, MDB_val *data, unsigned flags)
9299 MDB_val rdata, *xdata;
9303 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
9305 mdb_cursor_init(&mc, txn, dbi, &mx);
9314 flags |= MDB_NODUPDATA;
9316 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
9318 /* let mdb_page_split know about this cursor if needed:
9319 * delete will trigger a rebalance; if it needs to move
9320 * a node from one page to another, it will have to
9321 * update the parent's separator key(s). If the new sepkey
9322 * is larger than the current one, the parent page may
9323 * run out of space, triggering a split. We need this
9324 * cursor to be consistent until the end of the rebalance.
9326 mc.mc_next = txn->mt_cursors[dbi];
9327 txn->mt_cursors[dbi] = &mc;
9328 rc = mdb_cursor_del(&mc, flags);
9329 txn->mt_cursors[dbi] = mc.mc_next;
9334 /** Split a page and insert a new node.
9335 * Set #MDB_TXN_ERROR on failure.
9336 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
9337 * The cursor will be updated to point to the actual page and index where
9338 * the node got inserted after the split.
9339 * @param[in] newkey The key for the newly inserted node.
9340 * @param[in] newdata The data for the newly inserted node.
9341 * @param[in] newpgno The page number, if the new node is a branch node.
9342 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
9343 * @return 0 on success, non-zero on failure.
9346 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
9347 unsigned int nflags)
9350 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
9353 int i, j, split_indx, nkeys, pmax;
9354 MDB_env *env = mc->mc_txn->mt_env;
9356 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
9357 MDB_page *copy = NULL;
9358 MDB_page *mp, *rp, *pp;
9363 mp = mc->mc_pg[mc->mc_top];
9364 newindx = mc->mc_ki[mc->mc_top];
9365 nkeys = NUMKEYS(mp);
9367 DPRINTF(("-----> splitting %s page %"Yu" and adding [%s] at index %i/%i",
9368 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
9369 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
9371 /* Create a right sibling. */
9372 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
9374 rp->mp_pad = mp->mp_pad;
9375 DPRINTF(("new right sibling: page %"Yu, rp->mp_pgno));
9377 /* Usually when splitting the root page, the cursor
9378 * height is 1. But when called from mdb_update_key,
9379 * the cursor height may be greater because it walks
9380 * up the stack while finding the branch slot to update.
9382 if (mc->mc_top < 1) {
9383 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
9385 /* shift current top to make room for new parent */
9386 for (i=mc->mc_snum; i>0; i--) {
9387 mc->mc_pg[i] = mc->mc_pg[i-1];
9388 mc->mc_ki[i] = mc->mc_ki[i-1];
9392 mc->mc_db->md_root = pp->mp_pgno;
9393 DPRINTF(("root split! new root = %"Yu, pp->mp_pgno));
9394 new_root = mc->mc_db->md_depth++;
9396 /* Add left (implicit) pointer. */
9397 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
9398 /* undo the pre-push */
9399 mc->mc_pg[0] = mc->mc_pg[1];
9400 mc->mc_ki[0] = mc->mc_ki[1];
9401 mc->mc_db->md_root = mp->mp_pgno;
9402 mc->mc_db->md_depth--;
9409 ptop = mc->mc_top-1;
9410 DPRINTF(("parent branch page is %"Yu, mc->mc_pg[ptop]->mp_pgno));
9413 mdb_cursor_copy(mc, &mn);
9414 mn.mc_xcursor = NULL;
9415 mn.mc_pg[mn.mc_top] = rp;
9416 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
9418 if (nflags & MDB_APPEND) {
9419 mn.mc_ki[mn.mc_top] = 0;
9421 split_indx = newindx;
9425 split_indx = (nkeys+1) / 2;
9430 unsigned int lsize, rsize, ksize;
9431 /* Move half of the keys to the right sibling */
9432 x = mc->mc_ki[mc->mc_top] - split_indx;
9433 ksize = mc->mc_db->md_pad;
9434 split = LEAF2KEY(mp, split_indx, ksize);
9435 rsize = (nkeys - split_indx) * ksize;
9436 lsize = (nkeys - split_indx) * sizeof(indx_t);
9437 mp->mp_lower -= lsize;
9438 rp->mp_lower += lsize;
9439 mp->mp_upper += rsize - lsize;
9440 rp->mp_upper -= rsize - lsize;
9441 sepkey.mv_size = ksize;
9442 if (newindx == split_indx) {
9443 sepkey.mv_data = newkey->mv_data;
9445 sepkey.mv_data = split;
9448 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
9449 memcpy(rp->mp_ptrs, split, rsize);
9450 sepkey.mv_data = rp->mp_ptrs;
9451 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
9452 memcpy(ins, newkey->mv_data, ksize);
9453 mp->mp_lower += sizeof(indx_t);
9454 mp->mp_upper -= ksize - sizeof(indx_t);
9457 memcpy(rp->mp_ptrs, split, x * ksize);
9458 ins = LEAF2KEY(rp, x, ksize);
9459 memcpy(ins, newkey->mv_data, ksize);
9460 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
9461 rp->mp_lower += sizeof(indx_t);
9462 rp->mp_upper -= ksize - sizeof(indx_t);
9463 mc->mc_ki[mc->mc_top] = x;
9466 int psize, nsize, k;
9467 /* Maximum free space in an empty page */
9468 pmax = env->me_psize - PAGEHDRSZ;
9470 nsize = mdb_leaf_size(env, newkey, newdata);
9472 nsize = mdb_branch_size(env, newkey);
9473 nsize = EVEN(nsize);
9475 /* grab a page to hold a temporary copy */
9476 copy = mdb_page_malloc(mc->mc_txn, 1);
9481 copy->mp_pgno = mp->mp_pgno;
9482 copy->mp_flags = mp->mp_flags;
9483 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
9484 copy->mp_upper = env->me_psize - PAGEBASE;
9486 /* prepare to insert */
9487 for (i=0, j=0; i<nkeys; i++) {
9489 copy->mp_ptrs[j++] = 0;
9491 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
9494 /* When items are relatively large the split point needs
9495 * to be checked, because being off-by-one will make the
9496 * difference between success or failure in mdb_node_add.
9498 * It's also relevant if a page happens to be laid out
9499 * such that one half of its nodes are all "small" and
9500 * the other half of its nodes are "large." If the new
9501 * item is also "large" and falls on the half with
9502 * "large" nodes, it also may not fit.
9504 * As a final tweak, if the new item goes on the last
9505 * spot on the page (and thus, onto the new page), bias
9506 * the split so the new page is emptier than the old page.
9507 * This yields better packing during sequential inserts.
9509 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
9510 /* Find split point */
9512 if (newindx <= split_indx || newindx >= nkeys) {
9514 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
9519 for (; i!=k; i+=j) {
9524 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9525 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
9527 if (F_ISSET(node->mn_flags, F_BIGDATA))
9528 psize += sizeof(pgno_t);
9530 psize += NODEDSZ(node);
9532 psize = EVEN(psize);
9534 if (psize > pmax || i == k-j) {
9535 split_indx = i + (j<0);
9540 if (split_indx == newindx) {
9541 sepkey.mv_size = newkey->mv_size;
9542 sepkey.mv_data = newkey->mv_data;
9544 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
9545 sepkey.mv_size = node->mn_ksize;
9546 sepkey.mv_data = NODEKEY(node);
9551 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
9553 /* Copy separator key to the parent.
9555 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
9556 int snum = mc->mc_snum;
9560 /* We want other splits to find mn when doing fixups */
9561 WITH_CURSOR_TRACKING(mn,
9562 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
9567 if (mc->mc_snum > snum) {
9570 /* Right page might now have changed parent.
9571 * Check if left page also changed parent.
9573 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9574 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9575 for (i=0; i<ptop; i++) {
9576 mc->mc_pg[i] = mn.mc_pg[i];
9577 mc->mc_ki[i] = mn.mc_ki[i];
9579 mc->mc_pg[ptop] = mn.mc_pg[ptop];
9580 if (mn.mc_ki[ptop]) {
9581 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
9583 /* find right page's left sibling */
9584 mc->mc_ki[ptop] = mn.mc_ki[ptop];
9585 rc = mdb_cursor_sibling(mc, 0);
9590 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
9593 if (rc != MDB_SUCCESS) {
9594 if (rc == MDB_NOTFOUND) /* improper mdb_cursor_sibling() result */
9598 if (nflags & MDB_APPEND) {
9599 mc->mc_pg[mc->mc_top] = rp;
9600 mc->mc_ki[mc->mc_top] = 0;
9601 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
9604 for (i=0; i<mc->mc_top; i++)
9605 mc->mc_ki[i] = mn.mc_ki[i];
9606 } else if (!IS_LEAF2(mp)) {
9608 mc->mc_pg[mc->mc_top] = rp;
9613 rkey.mv_data = newkey->mv_data;
9614 rkey.mv_size = newkey->mv_size;
9620 /* Update index for the new key. */
9621 mc->mc_ki[mc->mc_top] = j;
9623 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9624 rkey.mv_data = NODEKEY(node);
9625 rkey.mv_size = node->mn_ksize;
9627 xdata.mv_data = NODEDATA(node);
9628 xdata.mv_size = NODEDSZ(node);
9631 pgno = NODEPGNO(node);
9632 flags = node->mn_flags;
9635 if (!IS_LEAF(mp) && j == 0) {
9636 /* First branch index doesn't need key data. */
9640 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
9646 mc->mc_pg[mc->mc_top] = copy;
9651 } while (i != split_indx);
9653 nkeys = NUMKEYS(copy);
9654 for (i=0; i<nkeys; i++)
9655 mp->mp_ptrs[i] = copy->mp_ptrs[i];
9656 mp->mp_lower = copy->mp_lower;
9657 mp->mp_upper = copy->mp_upper;
9658 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
9659 env->me_psize - copy->mp_upper - PAGEBASE);
9661 /* reset back to original page */
9662 if (newindx < split_indx) {
9663 mc->mc_pg[mc->mc_top] = mp;
9665 mc->mc_pg[mc->mc_top] = rp;
9667 /* Make sure mc_ki is still valid.
9669 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9670 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9671 for (i=0; i<=ptop; i++) {
9672 mc->mc_pg[i] = mn.mc_pg[i];
9673 mc->mc_ki[i] = mn.mc_ki[i];
9677 if (nflags & MDB_RESERVE) {
9678 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
9679 if (!(node->mn_flags & F_BIGDATA))
9680 newdata->mv_data = NODEDATA(node);
9683 if (newindx >= split_indx) {
9684 mc->mc_pg[mc->mc_top] = rp;
9686 /* Make sure mc_ki is still valid.
9688 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9689 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9690 for (i=0; i<=ptop; i++) {
9691 mc->mc_pg[i] = mn.mc_pg[i];
9692 mc->mc_ki[i] = mn.mc_ki[i];
9699 /* Adjust other cursors pointing to mp */
9700 MDB_cursor *m2, *m3;
9701 MDB_dbi dbi = mc->mc_dbi;
9702 nkeys = NUMKEYS(mp);
9704 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9705 if (mc->mc_flags & C_SUB)
9706 m3 = &m2->mc_xcursor->mx_cursor;
9711 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9715 /* sub cursors may be on different DB */
9716 if (m3->mc_pg[0] != mp)
9719 for (k=new_root; k>=0; k--) {
9720 m3->mc_ki[k+1] = m3->mc_ki[k];
9721 m3->mc_pg[k+1] = m3->mc_pg[k];
9723 if (m3->mc_ki[0] >= nkeys) {
9728 m3->mc_pg[0] = mc->mc_pg[0];
9732 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
9733 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
9734 m3->mc_ki[mc->mc_top]++;
9735 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9736 m3->mc_pg[mc->mc_top] = rp;
9737 m3->mc_ki[mc->mc_top] -= nkeys;
9738 for (i=0; i<mc->mc_top; i++) {
9739 m3->mc_ki[i] = mn.mc_ki[i];
9740 m3->mc_pg[i] = mn.mc_pg[i];
9743 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
9744 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
9747 if (XCURSOR_INITED(m3) && IS_LEAF(mp))
9748 XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9751 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
9754 if (copy) /* tmp page */
9755 mdb_page_free(env, copy);
9757 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9762 mdb_put(MDB_txn *txn, MDB_dbi dbi,
9763 MDB_val *key, MDB_val *data, unsigned int flags)
9769 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9772 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
9775 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9776 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9778 mdb_cursor_init(&mc, txn, dbi, &mx);
9779 mc.mc_next = txn->mt_cursors[dbi];
9780 txn->mt_cursors[dbi] = &mc;
9781 rc = mdb_cursor_put(&mc, key, data, flags);
9782 txn->mt_cursors[dbi] = mc.mc_next;
9787 #define MDB_WBUF (1024*1024)
9789 #define MDB_EOF 0x10 /**< #mdb_env_copyfd1() is done reading */
9791 /** State needed for a double-buffering compacting copy. */
9792 typedef struct mdb_copy {
9795 pthread_mutex_t mc_mutex;
9796 pthread_cond_t mc_cond; /**< Condition variable for #mc_new */
9801 pgno_t mc_next_pgno;
9803 int mc_toggle; /**< Buffer number in provider */
9804 int mc_new; /**< (0-2 buffers to write) | (#MDB_EOF at end) */
9805 /** Error code. Never cleared if set. Both threads can set nonzero
9806 * to fail the copy. Not mutex-protected, LMDB expects atomic int.
9808 volatile int mc_error;
9811 /** Dedicated writer thread for compacting copy. */
9812 static THREAD_RET ESECT CALL_CONV
9813 mdb_env_copythr(void *arg)
9817 int toggle = 0, wsize, rc;
9820 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9823 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9827 sigaddset(&set, SIGPIPE);
9828 if ((rc = pthread_sigmask(SIG_BLOCK, &set, NULL)) != 0)
9833 pthread_mutex_lock(&my->mc_mutex);
9836 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9837 if (my->mc_new == 0 + MDB_EOF) /* 0 buffers, just EOF */
9839 wsize = my->mc_wlen[toggle];
9840 ptr = my->mc_wbuf[toggle];
9843 while (wsize > 0 && !my->mc_error) {
9844 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
9847 #if defined(SIGPIPE) && !defined(_WIN32)
9849 /* Collect the pending SIGPIPE, otherwise at least OS X
9850 * gives it to the process on thread-exit (ITS#8504).
9853 sigwait(&set, &tmp);
9857 } else if (len > 0) {
9870 /* If there's an overflow page tail, write it too */
9871 if (my->mc_olen[toggle]) {
9872 wsize = my->mc_olen[toggle];
9873 ptr = my->mc_over[toggle];
9874 my->mc_olen[toggle] = 0;
9877 my->mc_wlen[toggle] = 0;
9879 /* Return the empty buffer to provider */
9881 pthread_cond_signal(&my->mc_cond);
9883 pthread_mutex_unlock(&my->mc_mutex);
9884 return (THREAD_RET)0;
9888 /** Give buffer and/or #MDB_EOF to writer thread, await unused buffer.
9890 * @param[in] my control structure.
9891 * @param[in] adjust (1 to hand off 1 buffer) | (MDB_EOF when ending).
9894 mdb_env_cthr_toggle(mdb_copy *my, int adjust)
9896 pthread_mutex_lock(&my->mc_mutex);
9897 my->mc_new += adjust;
9898 pthread_cond_signal(&my->mc_cond);
9899 while (my->mc_new & 2) /* both buffers in use */
9900 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9901 pthread_mutex_unlock(&my->mc_mutex);
9903 my->mc_toggle ^= (adjust & 1);
9904 /* Both threads reset mc_wlen, to be safe from threading errors */
9905 my->mc_wlen[my->mc_toggle] = 0;
9906 return my->mc_error;
9909 /** Depth-first tree traversal for compacting copy.
9910 * @param[in] my control structure.
9911 * @param[in,out] pg database root.
9912 * @param[in] flags includes #F_DUPDATA if it is a sorted-duplicate sub-DB.
9915 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
9917 MDB_cursor mc = {0};
9919 MDB_page *mo, *mp, *leaf;
9924 /* Empty DB, nothing to do */
9925 if (*pg == P_INVALID)
9929 mc.mc_txn = my->mc_txn;
9930 mc.mc_flags = my->mc_txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
9932 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
9935 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
9939 /* Make cursor pages writable */
9940 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
9944 for (i=0; i<mc.mc_top; i++) {
9945 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
9946 mc.mc_pg[i] = (MDB_page *)ptr;
9947 ptr += my->mc_env->me_psize;
9950 /* This is writable space for a leaf page. Usually not needed. */
9951 leaf = (MDB_page *)ptr;
9953 toggle = my->mc_toggle;
9954 while (mc.mc_snum > 0) {
9956 mp = mc.mc_pg[mc.mc_top];
9960 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
9961 for (i=0; i<n; i++) {
9962 ni = NODEPTR(mp, i);
9963 if (ni->mn_flags & F_BIGDATA) {
9967 /* Need writable leaf */
9969 mc.mc_pg[mc.mc_top] = leaf;
9970 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9972 ni = NODEPTR(mp, i);
9975 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9976 memcpy(NODEDATA(ni), &my->mc_next_pgno, sizeof(pgno_t));
9977 rc = mdb_page_get(&mc, pg, &omp, NULL);
9980 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9981 rc = mdb_env_cthr_toggle(my, 1);
9984 toggle = my->mc_toggle;
9986 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9987 memcpy(mo, omp, my->mc_env->me_psize);
9988 mo->mp_pgno = my->mc_next_pgno;
9989 my->mc_next_pgno += omp->mp_pages;
9990 my->mc_wlen[toggle] += my->mc_env->me_psize;
9991 if (omp->mp_pages > 1) {
9992 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
9993 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
9994 rc = mdb_env_cthr_toggle(my, 1);
9997 toggle = my->mc_toggle;
9999 } else if (ni->mn_flags & F_SUBDATA) {
10002 /* Need writable leaf */
10004 mc.mc_pg[mc.mc_top] = leaf;
10005 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
10007 ni = NODEPTR(mp, i);
10010 memcpy(&db, NODEDATA(ni), sizeof(db));
10011 my->mc_toggle = toggle;
10012 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
10015 toggle = my->mc_toggle;
10016 memcpy(NODEDATA(ni), &db, sizeof(db));
10021 mc.mc_ki[mc.mc_top]++;
10022 if (mc.mc_ki[mc.mc_top] < n) {
10025 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
10027 rc = mdb_page_get(&mc, pg, &mp, NULL);
10032 mc.mc_ki[mc.mc_top] = 0;
10033 if (IS_BRANCH(mp)) {
10034 /* Whenever we advance to a sibling branch page,
10035 * we must proceed all the way down to its first leaf.
10037 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
10040 mc.mc_pg[mc.mc_top] = mp;
10044 if (my->mc_wlen[toggle] >= MDB_WBUF) {
10045 rc = mdb_env_cthr_toggle(my, 1);
10048 toggle = my->mc_toggle;
10050 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
10051 mdb_page_copy(mo, mp, my->mc_env->me_psize);
10052 mo->mp_pgno = my->mc_next_pgno++;
10053 my->mc_wlen[toggle] += my->mc_env->me_psize;
10055 /* Update parent if there is one */
10056 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
10057 SETPGNO(ni, mo->mp_pgno);
10058 mdb_cursor_pop(&mc);
10060 /* Otherwise we're done */
10070 /** Copy environment with compaction. */
10072 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
10077 MDB_txn *txn = NULL;
10079 pgno_t root, new_root;
10080 int rc = MDB_SUCCESS;
10083 if (!(my.mc_mutex = CreateMutex(NULL, FALSE, NULL)) ||
10084 !(my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL))) {
10088 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
10089 if (my.mc_wbuf[0] == NULL) {
10090 /* _aligned_malloc() sets errno, but we use Windows error codes */
10091 rc = ERROR_NOT_ENOUGH_MEMORY;
10095 if ((rc = pthread_mutex_init(&my.mc_mutex, NULL)) != 0)
10097 if ((rc = pthread_cond_init(&my.mc_cond, NULL)) != 0)
10099 #ifdef HAVE_MEMALIGN
10100 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
10101 if (my.mc_wbuf[0] == NULL) {
10108 if ((rc = posix_memalign(&p, env->me_os_psize, MDB_WBUF*2)) != 0)
10114 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
10115 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
10116 my.mc_next_pgno = NUM_METAS;
10119 rc = THREAD_CREATE(thr, mdb_env_copythr, &my);
10123 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10127 mp = (MDB_page *)my.mc_wbuf[0];
10128 memset(mp, 0, NUM_METAS * env->me_psize);
10130 mp->mp_flags = P_META;
10131 mm = (MDB_meta *)METADATA(mp);
10132 mdb_env_init_meta0(env, mm);
10133 mm->mm_address = env->me_metas[0]->mm_address;
10135 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
10137 mp->mp_flags = P_META;
10138 *(MDB_meta *)METADATA(mp) = *mm;
10139 mm = (MDB_meta *)METADATA(mp);
10141 /* Set metapage 1 with current main DB */
10142 root = new_root = txn->mt_dbs[MAIN_DBI].md_root;
10143 if (root != P_INVALID) {
10144 /* Count free pages + freeDB pages. Subtract from last_pg
10145 * to find the new last_pg, which also becomes the new root.
10147 MDB_ID freecount = 0;
10150 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
10151 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
10152 freecount += *(MDB_ID *)data.mv_data;
10153 if (rc != MDB_NOTFOUND)
10155 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
10156 txn->mt_dbs[FREE_DBI].md_leaf_pages +
10157 txn->mt_dbs[FREE_DBI].md_overflow_pages;
10159 new_root = txn->mt_next_pgno - 1 - freecount;
10160 mm->mm_last_pg = new_root;
10161 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
10162 mm->mm_dbs[MAIN_DBI].md_root = new_root;
10164 /* When the DB is empty, handle it specially to
10165 * fix any breakage like page leaks from ITS#8174.
10167 mm->mm_dbs[MAIN_DBI].md_flags = txn->mt_dbs[MAIN_DBI].md_flags;
10169 if (root != P_INVALID || mm->mm_dbs[MAIN_DBI].md_flags) {
10170 mm->mm_txnid = 1; /* use metapage 1 */
10173 my.mc_wlen[0] = env->me_psize * NUM_METAS;
10175 rc = mdb_env_cwalk(&my, &root, 0);
10176 if (rc == MDB_SUCCESS && root != new_root) {
10177 rc = MDB_INCOMPATIBLE; /* page leak or corrupt DB */
10183 mdb_env_cthr_toggle(&my, 1 | MDB_EOF);
10184 rc = THREAD_FINISH(thr);
10185 mdb_txn_abort(txn);
10189 if (my.mc_wbuf[0]) _aligned_free(my.mc_wbuf[0]);
10190 if (my.mc_cond) CloseHandle(my.mc_cond);
10191 if (my.mc_mutex) CloseHandle(my.mc_mutex);
10193 free(my.mc_wbuf[0]);
10194 pthread_cond_destroy(&my.mc_cond);
10196 pthread_mutex_destroy(&my.mc_mutex);
10198 return rc ? rc : my.mc_error;
10201 /** Copy environment as-is. */
10203 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
10205 MDB_txn *txn = NULL;
10206 mdb_mutexref_t wmutex = NULL;
10208 mdb_size_t wsize, w3;
10212 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
10216 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
10219 /* Do the lock/unlock of the reader mutex before starting the
10220 * write txn. Otherwise other read txns could block writers.
10222 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10226 if (env->me_txns) {
10227 /* We must start the actual read txn after blocking writers */
10228 mdb_txn_end(txn, MDB_END_RESET_TMP);
10230 /* Temporarily block writers until we snapshot the meta pages */
10231 wmutex = env->me_wmutex;
10232 if (LOCK_MUTEX(rc, env, wmutex))
10235 rc = mdb_txn_renew0(txn);
10237 UNLOCK_MUTEX(wmutex);
10242 wsize = env->me_psize * NUM_METAS;
10246 DO_WRITE(rc, fd, ptr, w2, len);
10250 } else if (len > 0) {
10256 /* Non-blocking or async handles are not supported */
10262 UNLOCK_MUTEX(wmutex);
10267 w3 = txn->mt_next_pgno * env->me_psize;
10269 mdb_size_t fsize = 0;
10270 if ((rc = mdb_fsize(env->me_fd, &fsize)))
10275 wsize = w3 - wsize;
10276 while (wsize > 0) {
10277 if (wsize > MAX_WRITE)
10281 DO_WRITE(rc, fd, ptr, w2, len);
10285 } else if (len > 0) {
10297 mdb_txn_abort(txn);
10302 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
10304 if (flags & MDB_CP_COMPACT)
10305 return mdb_env_copyfd1(env, fd);
10307 return mdb_env_copyfd0(env, fd);
10311 mdb_env_copyfd(MDB_env *env, HANDLE fd)
10313 return mdb_env_copyfd2(env, fd, 0);
10317 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
10321 HANDLE newfd = INVALID_HANDLE_VALUE;
10323 rc = mdb_fname_init(path, env->me_flags | MDB_NOLOCK, &fname);
10324 if (rc == MDB_SUCCESS) {
10325 rc = mdb_fopen(env, &fname, MDB_O_COPY, 0666, &newfd);
10326 mdb_fname_destroy(fname);
10328 if (rc == MDB_SUCCESS) {
10329 rc = mdb_env_copyfd2(env, newfd, flags);
10330 if (close(newfd) < 0 && rc == MDB_SUCCESS)
10337 mdb_env_copy(MDB_env *env, const char *path)
10339 return mdb_env_copy2(env, path, 0);
10343 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
10345 if (flag & ~CHANGEABLE)
10348 env->me_flags |= flag;
10350 env->me_flags &= ~flag;
10351 return MDB_SUCCESS;
10355 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
10360 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
10361 return MDB_SUCCESS;
10365 mdb_env_set_userctx(MDB_env *env, void *ctx)
10369 env->me_userctx = ctx;
10370 return MDB_SUCCESS;
10374 mdb_env_get_userctx(MDB_env *env)
10376 return env ? env->me_userctx : NULL;
10380 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
10385 env->me_assert_func = func;
10387 return MDB_SUCCESS;
10391 mdb_env_get_path(MDB_env *env, const char **arg)
10396 *arg = env->me_path;
10397 return MDB_SUCCESS;
10401 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
10407 return MDB_SUCCESS;
10410 /** Common code for #mdb_stat() and #mdb_env_stat().
10411 * @param[in] env the environment to operate in.
10412 * @param[in] db the #MDB_db record containing the stats to return.
10413 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
10414 * @return 0, this function always succeeds.
10417 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
10419 arg->ms_psize = env->me_psize;
10420 arg->ms_depth = db->md_depth;
10421 arg->ms_branch_pages = db->md_branch_pages;
10422 arg->ms_leaf_pages = db->md_leaf_pages;
10423 arg->ms_overflow_pages = db->md_overflow_pages;
10424 arg->ms_entries = db->md_entries;
10426 return MDB_SUCCESS;
10430 mdb_env_stat(MDB_env *env, MDB_stat *arg)
10434 if (env == NULL || arg == NULL)
10437 meta = mdb_env_pick_meta(env);
10439 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
10443 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
10447 if (env == NULL || arg == NULL)
10450 meta = mdb_env_pick_meta(env);
10451 arg->me_mapaddr = meta->mm_address;
10452 arg->me_last_pgno = meta->mm_last_pg;
10453 arg->me_last_txnid = meta->mm_txnid;
10455 arg->me_mapsize = env->me_mapsize;
10456 arg->me_maxreaders = env->me_maxreaders;
10457 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
10458 return MDB_SUCCESS;
10461 /** Set the default comparison functions for a database.
10462 * Called immediately after a database is opened to set the defaults.
10463 * The user can then override them with #mdb_set_compare() or
10464 * #mdb_set_dupsort().
10465 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
10466 * @param[in] dbi A database handle returned by #mdb_dbi_open()
10469 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
10471 uint16_t f = txn->mt_dbs[dbi].md_flags;
10473 txn->mt_dbxs[dbi].md_cmp =
10474 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
10475 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
10477 txn->mt_dbxs[dbi].md_dcmp =
10478 !(f & MDB_DUPSORT) ? 0 :
10479 ((f & MDB_INTEGERDUP)
10480 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
10481 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
10484 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
10490 int rc, dbflag, exact;
10491 unsigned int unused = 0, seq;
10495 if (flags & ~VALID_FLAGS)
10497 if (txn->mt_flags & MDB_TXN_BLOCKED)
10498 return MDB_BAD_TXN;
10503 if (flags & PERSISTENT_FLAGS) {
10504 uint16_t f2 = flags & PERSISTENT_FLAGS;
10505 /* make sure flag changes get committed */
10506 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
10507 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
10508 txn->mt_flags |= MDB_TXN_DIRTY;
10511 mdb_default_cmp(txn, MAIN_DBI);
10512 return MDB_SUCCESS;
10515 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
10516 mdb_default_cmp(txn, MAIN_DBI);
10519 /* Is the DB already open? */
10520 len = strlen(name);
10521 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
10522 if (!txn->mt_dbxs[i].md_name.mv_size) {
10523 /* Remember this free slot */
10524 if (!unused) unused = i;
10527 if (len == txn->mt_dbxs[i].md_name.mv_size &&
10528 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
10530 return MDB_SUCCESS;
10534 /* If no free slot and max hit, fail */
10535 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
10536 return MDB_DBS_FULL;
10538 /* Cannot mix named databases with some mainDB flags */
10539 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
10540 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
10542 /* Find the DB info */
10543 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
10546 key.mv_data = (void *)name;
10547 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
10548 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
10549 if (rc == MDB_SUCCESS) {
10550 /* make sure this is actually a DB */
10551 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
10552 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
10553 return MDB_INCOMPATIBLE;
10554 } else if (! (rc == MDB_NOTFOUND && (flags & MDB_CREATE))) {
10558 /* Done here so we cannot fail after creating a new DB */
10559 if ((namedup = strdup(name)) == NULL)
10563 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
10564 data.mv_size = sizeof(MDB_db);
10565 data.mv_data = &dummy;
10566 memset(&dummy, 0, sizeof(dummy));
10567 dummy.md_root = P_INVALID;
10568 dummy.md_flags = flags & PERSISTENT_FLAGS;
10569 WITH_CURSOR_TRACKING(mc,
10570 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA));
10571 dbflag |= DB_DIRTY;
10577 /* Got info, register DBI in this txn */
10578 unsigned int slot = unused ? unused : txn->mt_numdbs;
10579 txn->mt_dbxs[slot].md_name.mv_data = namedup;
10580 txn->mt_dbxs[slot].md_name.mv_size = len;
10581 txn->mt_dbxs[slot].md_rel = NULL;
10582 txn->mt_dbflags[slot] = dbflag;
10583 /* txn-> and env-> are the same in read txns, use
10584 * tmp variable to avoid undefined assignment
10586 seq = ++txn->mt_env->me_dbiseqs[slot];
10587 txn->mt_dbiseqs[slot] = seq;
10589 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
10591 mdb_default_cmp(txn, slot);
10601 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
10603 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
10606 if (txn->mt_flags & MDB_TXN_BLOCKED)
10607 return MDB_BAD_TXN;
10609 if (txn->mt_dbflags[dbi] & DB_STALE) {
10612 /* Stale, must read the DB's root. cursor_init does it for us. */
10613 mdb_cursor_init(&mc, txn, dbi, &mx);
10615 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
10618 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
10621 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
10623 ptr = env->me_dbxs[dbi].md_name.mv_data;
10624 /* If there was no name, this was already closed */
10626 env->me_dbxs[dbi].md_name.mv_data = NULL;
10627 env->me_dbxs[dbi].md_name.mv_size = 0;
10628 env->me_dbflags[dbi] = 0;
10629 env->me_dbiseqs[dbi]++;
10634 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
10636 /* We could return the flags for the FREE_DBI too but what's the point? */
10637 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10639 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
10640 return MDB_SUCCESS;
10643 /** Add all the DB's pages to the free list.
10644 * @param[in] mc Cursor on the DB to free.
10645 * @param[in] subs non-Zero to check for sub-DBs in this DB.
10646 * @return 0 on success, non-zero on failure.
10649 mdb_drop0(MDB_cursor *mc, int subs)
10653 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
10654 if (rc == MDB_SUCCESS) {
10655 MDB_txn *txn = mc->mc_txn;
10660 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
10661 * This also avoids any P_LEAF2 pages, which have no nodes.
10662 * Also if the DB doesn't have sub-DBs and has no overflow
10663 * pages, omit scanning leaves.
10665 if ((mc->mc_flags & C_SUB) ||
10666 (!subs && !mc->mc_db->md_overflow_pages))
10667 mdb_cursor_pop(mc);
10669 mdb_cursor_copy(mc, &mx);
10671 /* bump refcount for mx's pages */
10672 for (i=0; i<mc->mc_snum; i++)
10673 mdb_page_get(&mx, mc->mc_pg[i]->mp_pgno, &mx.mc_pg[i], NULL);
10675 while (mc->mc_snum > 0) {
10676 MDB_page *mp = mc->mc_pg[mc->mc_top];
10677 unsigned n = NUMKEYS(mp);
10679 for (i=0; i<n; i++) {
10680 ni = NODEPTR(mp, i);
10681 if (ni->mn_flags & F_BIGDATA) {
10684 memcpy(&pg, NODEDATA(ni), sizeof(pg));
10685 rc = mdb_page_get(mc, pg, &omp, NULL);
10688 mdb_cassert(mc, IS_OVERFLOW(omp));
10689 rc = mdb_midl_append_range(&txn->mt_free_pgs,
10690 pg, omp->mp_pages);
10693 mc->mc_db->md_overflow_pages -= omp->mp_pages;
10694 if (!mc->mc_db->md_overflow_pages && !subs)
10696 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
10697 mdb_xcursor_init1(mc, ni);
10698 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
10703 if (!subs && !mc->mc_db->md_overflow_pages)
10706 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
10708 for (i=0; i<n; i++) {
10710 ni = NODEPTR(mp, i);
10713 mdb_midl_xappend(txn->mt_free_pgs, pg);
10718 mc->mc_ki[mc->mc_top] = i;
10719 rc = mdb_cursor_sibling(mc, 1);
10721 if (rc != MDB_NOTFOUND)
10723 /* no more siblings, go back to beginning
10724 * of previous level.
10727 mdb_cursor_pop(mc);
10729 for (i=1; i<mc->mc_snum; i++) {
10731 mc->mc_pg[i] = mx.mc_pg[i];
10736 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
10739 txn->mt_flags |= MDB_TXN_ERROR;
10740 /* drop refcount for mx's pages */
10741 MDB_CURSOR_UNREF(&mx, 0);
10742 } else if (rc == MDB_NOTFOUND) {
10745 mc->mc_flags &= ~C_INITIALIZED;
10749 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
10751 MDB_cursor *mc, *m2;
10754 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10757 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
10760 if (TXN_DBI_CHANGED(txn, dbi))
10761 return MDB_BAD_DBI;
10763 rc = mdb_cursor_open(txn, dbi, &mc);
10767 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
10768 /* Invalidate the dropped DB's cursors */
10769 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
10770 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
10774 /* Can't delete the main DB */
10775 if (del && dbi >= CORE_DBS) {
10776 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
10778 txn->mt_dbflags[dbi] = DB_STALE;
10779 mdb_dbi_close(txn->mt_env, dbi);
10781 txn->mt_flags |= MDB_TXN_ERROR;
10784 /* reset the DB record, mark it dirty */
10785 txn->mt_dbflags[dbi] |= DB_DIRTY;
10786 txn->mt_dbs[dbi].md_depth = 0;
10787 txn->mt_dbs[dbi].md_branch_pages = 0;
10788 txn->mt_dbs[dbi].md_leaf_pages = 0;
10789 txn->mt_dbs[dbi].md_overflow_pages = 0;
10790 txn->mt_dbs[dbi].md_entries = 0;
10791 txn->mt_dbs[dbi].md_root = P_INVALID;
10793 txn->mt_flags |= MDB_TXN_DIRTY;
10796 mdb_cursor_close(mc);
10800 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10802 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10805 txn->mt_dbxs[dbi].md_cmp = cmp;
10806 return MDB_SUCCESS;
10809 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10811 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10814 txn->mt_dbxs[dbi].md_dcmp = cmp;
10815 return MDB_SUCCESS;
10818 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
10820 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10823 txn->mt_dbxs[dbi].md_rel = rel;
10824 return MDB_SUCCESS;
10827 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
10829 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10832 txn->mt_dbxs[dbi].md_relctx = ctx;
10833 return MDB_SUCCESS;
10837 mdb_env_get_maxkeysize(MDB_env *env)
10839 return ENV_MAXKEY(env);
10843 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
10845 unsigned int i, rdrs;
10848 int rc = 0, first = 1;
10852 if (!env->me_txns) {
10853 return func("(no reader locks)\n", ctx);
10855 rdrs = env->me_txns->mti_numreaders;
10856 mr = env->me_txns->mti_readers;
10857 for (i=0; i<rdrs; i++) {
10858 if (mr[i].mr_pid) {
10859 txnid_t txnid = mr[i].mr_txnid;
10860 sprintf(buf, txnid == (txnid_t)-1 ?
10861 "%10d %"Z"x -\n" : "%10d %"Z"x %"Yu"\n",
10862 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
10865 rc = func(" pid thread txnid\n", ctx);
10869 rc = func(buf, ctx);
10875 rc = func("(no active readers)\n", ctx);
10880 /** Insert pid into list if not already present.
10881 * return -1 if already present.
10884 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
10886 /* binary search of pid in list */
10888 unsigned cursor = 1;
10890 unsigned n = ids[0];
10893 unsigned pivot = n >> 1;
10894 cursor = base + pivot + 1;
10895 val = pid - ids[cursor];
10900 } else if ( val > 0 ) {
10905 /* found, so it's a duplicate */
10914 for (n = ids[0]; n > cursor; n--)
10921 mdb_reader_check(MDB_env *env, int *dead)
10927 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
10930 /** As #mdb_reader_check(). \b rlocked is set if caller locked #me_rmutex. */
10932 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
10934 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
10935 unsigned int i, j, rdrs;
10937 MDB_PID_T *pids, pid;
10938 int rc = MDB_SUCCESS, count = 0;
10940 rdrs = env->me_txns->mti_numreaders;
10941 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
10945 mr = env->me_txns->mti_readers;
10946 for (i=0; i<rdrs; i++) {
10947 pid = mr[i].mr_pid;
10948 if (pid && pid != env->me_pid) {
10949 if (mdb_pid_insert(pids, pid) == 0) {
10950 if (!mdb_reader_pid(env, Pidcheck, pid)) {
10951 /* Stale reader found */
10954 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
10955 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
10957 rdrs = 0; /* the above checked all readers */
10959 /* Recheck, a new process may have reused pid */
10960 if (mdb_reader_pid(env, Pidcheck, pid))
10964 for (; j<rdrs; j++)
10965 if (mr[j].mr_pid == pid) {
10966 DPRINTF(("clear stale reader pid %u txn %"Yd,
10967 (unsigned) pid, mr[j].mr_txnid));
10972 UNLOCK_MUTEX(rmutex);
10983 #ifdef MDB_ROBUST_SUPPORTED
10984 /** Handle #LOCK_MUTEX0() failure.
10985 * Try to repair the lock file if the mutex owner died.
10986 * @param[in] env the environment handle
10987 * @param[in] mutex LOCK_MUTEX0() mutex
10988 * @param[in] rc LOCK_MUTEX0() error (nonzero)
10989 * @return 0 on success with the mutex locked, or an error code on failure.
10992 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10997 if (rc == MDB_OWNERDEAD) {
10998 /* We own the mutex. Clean up after dead previous owner. */
11000 rlocked = (mutex == env->me_rmutex);
11002 /* Keep mti_txnid updated, otherwise next writer can
11003 * overwrite data which latest meta page refers to.
11005 meta = mdb_env_pick_meta(env);
11006 env->me_txns->mti_txnid = meta->mm_txnid;
11007 /* env is hosed if the dead thread was ours */
11009 env->me_flags |= MDB_FATAL_ERROR;
11010 env->me_txn = NULL;
11014 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
11015 (rc ? "this process' env is hosed" : "recovering")));
11016 rc2 = mdb_reader_check0(env, rlocked, NULL);
11018 rc2 = mdb_mutex_consistent(mutex);
11019 if (rc || (rc = rc2)) {
11020 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
11021 UNLOCK_MUTEX(mutex);
11027 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
11032 #endif /* MDB_ROBUST_SUPPORTED */
11034 #if defined(_WIN32)
11035 /** Convert \b src to new wchar_t[] string with room for \b xtra extra chars */
11037 utf8_to_utf16(const char *src, MDB_name *dst, int xtra)
11040 wchar_t *result = NULL;
11041 for (;;) { /* malloc result, then fill it in */
11042 need = MultiByteToWideChar(CP_UTF8, 0, src, -1, result, need);
11049 result = malloc(sizeof(wchar_t) * (need + xtra));
11054 dst->mn_alloced = 1;
11055 dst->mn_len = need - 1;
11056 dst->mn_val = result;
11057 return MDB_SUCCESS;
11060 #endif /* defined(_WIN32) */