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-2016 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(__WIN64__)
39 #define _FILE_OFFSET_BITS 64
44 #include <wchar.h> /* get wcscpy() */
46 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
47 * as int64 which is wrong. MSVC doesn't define it at all, so just
51 #define MDB_THR_T DWORD
52 #include <sys/types.h>
55 # include <sys/param.h>
57 # define LITTLE_ENDIAN 1234
58 # define BIG_ENDIAN 4321
59 # define BYTE_ORDER LITTLE_ENDIAN
61 # define SSIZE_MAX INT_MAX
65 #include <sys/types.h>
67 #define MDB_PID_T pid_t
68 #define MDB_THR_T pthread_t
69 #include <sys/param.h>
72 #ifdef HAVE_SYS_FILE_H
78 #if defined(__mips) && defined(__linux)
79 /* MIPS has cache coherency issues, requires explicit cache control */
80 #include <asm/cachectl.h>
81 extern int cacheflush(char *addr, int nbytes, int cache);
82 #define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
84 #define CACHEFLUSH(addr, bytes, cache)
87 #if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
88 /** fdatasync is broken on ext3/ext4fs on older kernels, see
89 * description in #mdb_env_open2 comments. You can safely
90 * define MDB_FDATASYNC_WORKS if this code will only be run
91 * on kernels 3.6 and newer.
93 #define BROKEN_FDATASYNC
107 typedef SSIZE_T ssize_t;
112 #if defined(__sun) || defined(ANDROID)
113 /* Most platforms have posix_memalign, older may only have memalign */
114 #define HAVE_MEMALIGN 1
118 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
119 #include <netinet/in.h>
120 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
123 #if defined(__APPLE__) || defined (BSD)
124 # define MDB_USE_POSIX_SEM 1
125 # define MDB_FDATASYNC fsync
126 #elif defined(ANDROID)
127 # define MDB_FDATASYNC fsync
133 #ifdef MDB_USE_POSIX_SEM
134 # define MDB_USE_HASH 1
135 #include <semaphore.h>
137 #define MDB_USE_POSIX_MUTEX 1
141 #if defined(_WIN32) + defined(MDB_USE_POSIX_SEM) \
142 + defined(MDB_USE_POSIX_MUTEX) != 1
143 # error "Ambiguous shared-lock implementation"
147 #include <valgrind/memcheck.h>
148 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
149 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
150 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
151 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
152 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
154 #define VGMEMP_CREATE(h,r,z)
155 #define VGMEMP_ALLOC(h,a,s)
156 #define VGMEMP_FREE(h,a)
157 #define VGMEMP_DESTROY(h)
158 #define VGMEMP_DEFINED(a,s)
162 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
163 /* Solaris just defines one or the other */
164 # define LITTLE_ENDIAN 1234
165 # define BIG_ENDIAN 4321
166 # ifdef _LITTLE_ENDIAN
167 # define BYTE_ORDER LITTLE_ENDIAN
169 # define BYTE_ORDER BIG_ENDIAN
172 # define BYTE_ORDER __BYTE_ORDER
176 #ifndef LITTLE_ENDIAN
177 #define LITTLE_ENDIAN __LITTLE_ENDIAN
180 #define BIG_ENDIAN __BIG_ENDIAN
183 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
184 #define MISALIGNED_OK 1
190 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
191 # error "Unknown or unsupported endianness (BYTE_ORDER)"
192 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
193 # error "Two's complement, reasonably sized integer types, please"
197 /** Put infrequently used env functions in separate section */
199 # define ESECT __attribute__ ((section("__TEXT,text_env")))
201 # define ESECT __attribute__ ((section("text_env")))
208 #define CALL_CONV WINAPI
213 /** @defgroup internal LMDB Internals
216 /** @defgroup compat Compatibility Macros
217 * A bunch of macros to minimize the amount of platform-specific ifdefs
218 * needed throughout the rest of the code. When the features this library
219 * needs are similar enough to POSIX to be hidden in a one-or-two line
220 * replacement, this macro approach is used.
224 /** Features under development */
229 /** Wrapper around __func__, which is a C99 feature */
230 #if __STDC_VERSION__ >= 199901L
231 # define mdb_func_ __func__
232 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
233 # define mdb_func_ __FUNCTION__
235 /* If a debug message says <mdb_unknown>(), update the #if statements above */
236 # define mdb_func_ "<mdb_unknown>"
239 /* Internal error codes, not exposed outside liblmdb */
240 #define MDB_NO_ROOT (MDB_LAST_ERRCODE + 10)
242 #define MDB_OWNERDEAD ((int) WAIT_ABANDONED)
243 #elif defined(MDB_USE_POSIX_MUTEX) && defined(EOWNERDEAD)
244 #define MDB_OWNERDEAD EOWNERDEAD /**< #LOCK_MUTEX0() result if dead owner */
248 #define GLIBC_VER ((__GLIBC__ << 16 )| __GLIBC_MINOR__)
250 /** Some platforms define the EOWNERDEAD error code
251 * even though they don't support Robust Mutexes.
252 * Compile with -DMDB_USE_ROBUST=0, or use some other
253 * mechanism like -DMDB_USE_POSIX_SEM instead of
254 * -DMDB_USE_POSIX_MUTEX.
255 * (Posix semaphores are not robust.)
257 #ifndef MDB_USE_ROBUST
258 /* Android currently lacks Robust Mutex support. So does glibc < 2.4. */
259 # if defined(MDB_USE_POSIX_MUTEX) && (defined(ANDROID) || \
260 (defined(__GLIBC__) && GLIBC_VER < 0x020004))
261 # define MDB_USE_ROBUST 0
263 # define MDB_USE_ROBUST 1
265 #endif /* !MDB_USE_ROBUST */
267 #if defined(MDB_USE_POSIX_MUTEX) && (MDB_USE_ROBUST)
268 /* glibc < 2.12 only provided _np API */
269 # if (defined(__GLIBC__) && GLIBC_VER < 0x02000c) || \
270 (defined(PTHREAD_MUTEX_ROBUST_NP) && !defined(PTHREAD_MUTEX_ROBUST))
271 # define PTHREAD_MUTEX_ROBUST PTHREAD_MUTEX_ROBUST_NP
272 # define pthread_mutexattr_setrobust(attr, flag) pthread_mutexattr_setrobust_np(attr, flag)
273 # define pthread_mutex_consistent(mutex) pthread_mutex_consistent_np(mutex)
275 #endif /* MDB_USE_POSIX_MUTEX && MDB_USE_ROBUST */
277 #if defined(MDB_OWNERDEAD) && (MDB_USE_ROBUST)
278 #define MDB_ROBUST_SUPPORTED 1
282 #define MDB_USE_HASH 1
283 #define MDB_PIDLOCK 0
284 #define THREAD_RET DWORD
285 #define pthread_t HANDLE
286 #define pthread_mutex_t HANDLE
287 #define pthread_cond_t HANDLE
288 typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
289 #define pthread_key_t DWORD
290 #define pthread_self() GetCurrentThreadId()
291 #define pthread_key_create(x,y) \
292 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
293 #define pthread_key_delete(x) TlsFree(x)
294 #define pthread_getspecific(x) TlsGetValue(x)
295 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
296 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
297 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
298 #define pthread_cond_signal(x) SetEvent(*x)
299 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
300 #define THREAD_CREATE(thr,start,arg) \
301 (((thr) = CreateThread(NULL, 0, start, arg, 0, NULL)) ? 0 : ErrCode())
302 #define THREAD_FINISH(thr) \
303 (WaitForSingleObject(thr, INFINITE) ? ErrCode() : 0)
304 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
305 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
306 #define mdb_mutex_consistent(mutex) 0
307 #define getpid() GetCurrentProcessId()
308 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
309 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
310 #define ErrCode() GetLastError()
311 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
312 #define close(fd) (CloseHandle(fd) ? 0 : -1)
313 #define munmap(ptr,len) UnmapViewOfFile(ptr)
314 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
315 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
317 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
321 #define THREAD_RET void *
322 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
323 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
324 #define Z "z" /**< printf format modifier for size_t */
326 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
327 #define MDB_PIDLOCK 1
329 #ifdef MDB_USE_POSIX_SEM
331 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
332 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
333 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
336 mdb_sem_wait(sem_t *sem)
339 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
343 #else /* MDB_USE_POSIX_MUTEX: */
344 /** Shared mutex/semaphore as it is stored (mdb_mutex_t), and as
345 * local variables keep it (mdb_mutexref_t).
347 * When #mdb_mutexref_t is a pointer declaration and #mdb_mutex_t is
348 * not, then it is array[size 1] so it can be assigned to a pointer.
351 typedef pthread_mutex_t mdb_mutex_t[1], *mdb_mutexref_t;
353 /** Lock the reader or writer mutex.
354 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
356 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
357 /** Unlock the reader or writer mutex.
359 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
360 /** Mark mutex-protected data as repaired, after death of previous owner.
362 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
363 #endif /* MDB_USE_POSIX_SEM */
365 /** Get the error code for the last failed system function.
367 #define ErrCode() errno
369 /** An abstraction for a file handle.
370 * On POSIX systems file handles are small integers. On Windows
371 * they're opaque pointers.
375 /** A value for an invalid file handle.
376 * Mainly used to initialize file variables and signify that they are
379 #define INVALID_HANDLE_VALUE (-1)
381 /** Get the size of a memory page for the system.
382 * This is the basic size that the platform's memory manager uses, and is
383 * fundamental to the use of memory-mapped files.
385 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
388 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
391 #define MNAME_LEN (sizeof(pthread_mutex_t))
396 #ifdef MDB_ROBUST_SUPPORTED
397 /** Lock mutex, handle any error, set rc = result.
398 * Return 0 on success, nonzero (not rc) on error.
400 #define LOCK_MUTEX(rc, env, mutex) \
401 (((rc) = LOCK_MUTEX0(mutex)) && \
402 ((rc) = mdb_mutex_failed(env, mutex, rc)))
403 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
405 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
406 #define mdb_mutex_failed(env, mutex, rc) (rc)
410 /** A flag for opening a file and requesting synchronous data writes.
411 * This is only used when writing a meta page. It's not strictly needed;
412 * we could just do a normal write and then immediately perform a flush.
413 * But if this flag is available it saves us an extra system call.
415 * @note If O_DSYNC is undefined but exists in /usr/include,
416 * preferably set some compiler flag to get the definition.
420 # define MDB_DSYNC O_DSYNC
422 # define MDB_DSYNC O_SYNC
427 /** Function for flushing the data of a file. Define this to fsync
428 * if fdatasync() is not supported.
430 #ifndef MDB_FDATASYNC
431 # define MDB_FDATASYNC fdatasync
435 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
446 /** A page number in the database.
447 * Note that 64 bit page numbers are overkill, since pages themselves
448 * already represent 12-13 bits of addressable memory, and the OS will
449 * always limit applications to a maximum of 63 bits of address space.
451 * @note In the #MDB_node structure, we only store 48 bits of this value,
452 * which thus limits us to only 60 bits of addressable data.
454 typedef MDB_ID pgno_t;
456 /** A transaction ID.
457 * See struct MDB_txn.mt_txnid for details.
459 typedef MDB_ID txnid_t;
461 /** @defgroup debug Debug Macros
465 /** Enable debug output. Needs variable argument macros (a C99 feature).
466 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
467 * read from and written to the database (used for free space management).
473 static int mdb_debug;
474 static txnid_t mdb_debug_start;
476 /** Print a debug message with printf formatting.
477 * Requires double parenthesis around 2 or more args.
479 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
480 # define DPRINTF0(fmt, ...) \
481 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
483 # define DPRINTF(args) ((void) 0)
485 /** Print a debug string.
486 * The string is printed literally, with no format processing.
488 #define DPUTS(arg) DPRINTF(("%s", arg))
489 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
491 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
494 /** @brief The maximum size of a database page.
496 * It is 32k or 64k, since value-PAGEBASE must fit in
497 * #MDB_page.%mp_upper.
499 * LMDB will use database pages < OS pages if needed.
500 * That causes more I/O in write transactions: The OS must
501 * know (read) the whole page before writing a partial page.
503 * Note that we don't currently support Huge pages. On Linux,
504 * regular data files cannot use Huge pages, and in general
505 * Huge pages aren't actually pageable. We rely on the OS
506 * demand-pager to read our data and page it out when memory
507 * pressure from other processes is high. So until OSs have
508 * actual paging support for Huge pages, they're not viable.
510 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
512 /** The minimum number of keys required in a database page.
513 * Setting this to a larger value will place a smaller bound on the
514 * maximum size of a data item. Data items larger than this size will
515 * be pushed into overflow pages instead of being stored directly in
516 * the B-tree node. This value used to default to 4. With a page size
517 * of 4096 bytes that meant that any item larger than 1024 bytes would
518 * go into an overflow page. That also meant that on average 2-3KB of
519 * each overflow page was wasted space. The value cannot be lower than
520 * 2 because then there would no longer be a tree structure. With this
521 * value, items larger than 2KB will go into overflow pages, and on
522 * average only 1KB will be wasted.
524 #define MDB_MINKEYS 2
526 /** A stamp that identifies a file as an LMDB file.
527 * There's nothing special about this value other than that it is easily
528 * recognizable, and it will reflect any byte order mismatches.
530 #define MDB_MAGIC 0xBEEFC0DE
532 /** The version number for a database's datafile format. */
533 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
534 /** The version number for a database's lockfile format. */
535 #define MDB_LOCK_VERSION 1
537 /** @brief The max size of a key we can write, or 0 for computed max.
539 * This macro should normally be left alone or set to 0.
540 * Note that a database with big keys or dupsort data cannot be
541 * reliably modified by a liblmdb which uses a smaller max.
542 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
544 * Other values are allowed, for backwards compat. However:
545 * A value bigger than the computed max can break if you do not
546 * know what you are doing, and liblmdb <= 0.9.10 can break when
547 * modifying a DB with keys/dupsort data bigger than its max.
549 * Data items in an #MDB_DUPSORT database are also limited to
550 * this size, since they're actually keys of a sub-DB. Keys and
551 * #MDB_DUPSORT data items must fit on a node in a regular page.
553 #ifndef MDB_MAXKEYSIZE
554 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
557 /** The maximum size of a key we can write to the environment. */
559 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
561 #define ENV_MAXKEY(env) ((env)->me_maxkey)
564 /** @brief The maximum size of a data item.
566 * We only store a 32 bit value for node sizes.
568 #define MAXDATASIZE 0xffffffffUL
571 /** Key size which fits in a #DKBUF.
574 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
577 * This is used for printing a hex dump of a key's contents.
579 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
580 /** Display a key in hex.
582 * Invoke a function to display a key in hex.
584 #define DKEY(x) mdb_dkey(x, kbuf)
590 /** An invalid page number.
591 * Mainly used to denote an empty tree.
593 #define P_INVALID (~(pgno_t)0)
595 /** Test if the flags \b f are set in a flag word \b w. */
596 #define F_ISSET(w, f) (((w) & (f)) == (f))
598 /** Round \b n up to an even number. */
599 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
601 /** Used for offsets within a single page.
602 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
605 typedef uint16_t indx_t;
607 /** Default size of memory map.
608 * This is certainly too small for any actual applications. Apps should always set
609 * the size explicitly using #mdb_env_set_mapsize().
611 #define DEFAULT_MAPSIZE 1048576
613 /** @defgroup readers Reader Lock Table
614 * Readers don't acquire any locks for their data access. Instead, they
615 * simply record their transaction ID in the reader table. The reader
616 * mutex is needed just to find an empty slot in the reader table. The
617 * slot's address is saved in thread-specific data so that subsequent read
618 * transactions started by the same thread need no further locking to proceed.
620 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
622 * No reader table is used if the database is on a read-only filesystem, or
623 * if #MDB_NOLOCK is set.
625 * Since the database uses multi-version concurrency control, readers don't
626 * actually need any locking. This table is used to keep track of which
627 * readers are using data from which old transactions, so that we'll know
628 * when a particular old transaction is no longer in use. Old transactions
629 * that have discarded any data pages can then have those pages reclaimed
630 * for use by a later write transaction.
632 * The lock table is constructed such that reader slots are aligned with the
633 * processor's cache line size. Any slot is only ever used by one thread.
634 * This alignment guarantees that there will be no contention or cache
635 * thrashing as threads update their own slot info, and also eliminates
636 * any need for locking when accessing a slot.
638 * A writer thread will scan every slot in the table to determine the oldest
639 * outstanding reader transaction. Any freed pages older than this will be
640 * reclaimed by the writer. The writer doesn't use any locks when scanning
641 * this table. This means that there's no guarantee that the writer will
642 * see the most up-to-date reader info, but that's not required for correct
643 * operation - all we need is to know the upper bound on the oldest reader,
644 * we don't care at all about the newest reader. So the only consequence of
645 * reading stale information here is that old pages might hang around a
646 * while longer before being reclaimed. That's actually good anyway, because
647 * the longer we delay reclaiming old pages, the more likely it is that a
648 * string of contiguous pages can be found after coalescing old pages from
649 * many old transactions together.
652 /** Number of slots in the reader table.
653 * This value was chosen somewhat arbitrarily. 126 readers plus a
654 * couple mutexes fit exactly into 8KB on my development machine.
655 * Applications should set the table size using #mdb_env_set_maxreaders().
657 #define DEFAULT_READERS 126
659 /** The size of a CPU cache line in bytes. We want our lock structures
660 * aligned to this size to avoid false cache line sharing in the
662 * This value works for most CPUs. For Itanium this should be 128.
668 /** The information we store in a single slot of the reader table.
669 * In addition to a transaction ID, we also record the process and
670 * thread ID that owns a slot, so that we can detect stale information,
671 * e.g. threads or processes that went away without cleaning up.
672 * @note We currently don't check for stale records. We simply re-init
673 * the table when we know that we're the only process opening the
676 typedef struct MDB_rxbody {
677 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
678 * Multiple readers that start at the same time will probably have the
679 * same ID here. Again, it's not important to exclude them from
680 * anything; all we need to know is which version of the DB they
681 * started from so we can avoid overwriting any data used in that
682 * particular version.
684 volatile txnid_t mrb_txnid;
685 /** The process ID of the process owning this reader txn. */
686 volatile MDB_PID_T mrb_pid;
687 /** The thread ID of the thread owning this txn. */
688 volatile MDB_THR_T mrb_tid;
691 /** The actual reader record, with cacheline padding. */
692 typedef struct MDB_reader {
695 /** shorthand for mrb_txnid */
696 #define mr_txnid mru.mrx.mrb_txnid
697 #define mr_pid mru.mrx.mrb_pid
698 #define mr_tid mru.mrx.mrb_tid
699 /** cache line alignment */
700 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
704 /** The header for the reader table.
705 * The table resides in a memory-mapped file. (This is a different file
706 * than is used for the main database.)
708 * For POSIX the actual mutexes reside in the shared memory of this
709 * mapped file. On Windows, mutexes are named objects allocated by the
710 * kernel; we store the mutex names in this mapped file so that other
711 * processes can grab them. This same approach is also used on
712 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
713 * process-shared POSIX mutexes. For these cases where a named object
714 * is used, the object name is derived from a 64 bit FNV hash of the
715 * environment pathname. As such, naming collisions are extremely
716 * unlikely. If a collision occurs, the results are unpredictable.
718 typedef struct MDB_txbody {
719 /** Stamp identifying this as an LMDB file. It must be set
722 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
724 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
725 char mtb_rmname[MNAME_LEN];
727 /** Mutex protecting access to this table.
728 * This is the reader table lock used with LOCK_MUTEX().
730 mdb_mutex_t mtb_rmutex;
732 /** The ID of the last transaction committed to the database.
733 * This is recorded here only for convenience; the value can always
734 * be determined by reading the main database meta pages.
736 volatile txnid_t mtb_txnid;
737 /** The number of slots that have been used in the reader table.
738 * This always records the maximum count, it is not decremented
739 * when readers release their slots.
741 volatile unsigned mtb_numreaders;
744 /** The actual reader table definition. */
745 typedef struct MDB_txninfo {
748 #define mti_magic mt1.mtb.mtb_magic
749 #define mti_format mt1.mtb.mtb_format
750 #define mti_rmutex mt1.mtb.mtb_rmutex
751 #define mti_rmname mt1.mtb.mtb_rmname
752 #define mti_txnid mt1.mtb.mtb_txnid
753 #define mti_numreaders mt1.mtb.mtb_numreaders
754 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
757 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
758 char mt2_wmname[MNAME_LEN];
759 #define mti_wmname mt2.mt2_wmname
761 mdb_mutex_t mt2_wmutex;
762 #define mti_wmutex mt2.mt2_wmutex
764 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
766 MDB_reader mti_readers[1];
769 /** Lockfile format signature: version, features and field layout */
770 #define MDB_LOCK_FORMAT \
772 ((MDB_LOCK_VERSION) \
773 /* Flags which describe functionality */ \
774 + (((MDB_PIDLOCK) != 0) << 16)))
777 /** Common header for all page types. The page type depends on #mp_flags.
779 * #P_BRANCH and #P_LEAF pages have unsorted '#MDB_node's at the end, with
780 * sorted #mp_ptrs[] entries referring to them. Exception: #P_LEAF2 pages
781 * omit mp_ptrs and pack sorted #MDB_DUPFIXED values after the page header.
783 * #P_OVERFLOW records occupy one or more contiguous pages where only the
784 * first has a page header. They hold the real data of #F_BIGDATA nodes.
786 * #P_SUBP sub-pages are small leaf "pages" with duplicate data.
787 * A node with flag #F_DUPDATA but not #F_SUBDATA contains a sub-page.
788 * (Duplicate data can also go in sub-databases, which use normal pages.)
790 * #P_META pages contain #MDB_meta, the start point of an LMDB snapshot.
792 * Each non-metapage up to #MDB_meta.%mm_last_pg is reachable exactly once
793 * in the snapshot: Either used by a database or listed in a freeDB record.
795 typedef struct MDB_page {
796 #define mp_pgno mp_p.p_pgno
797 #define mp_next mp_p.p_next
799 pgno_t p_pgno; /**< page number */
800 struct MDB_page *p_next; /**< for in-memory list of freed pages */
802 uint16_t mp_pad; /**< key size if this is a LEAF2 page */
803 /** @defgroup mdb_page Page Flags
805 * Flags for the page headers.
808 #define P_BRANCH 0x01 /**< branch page */
809 #define P_LEAF 0x02 /**< leaf page */
810 #define P_OVERFLOW 0x04 /**< overflow page */
811 #define P_META 0x08 /**< meta page */
812 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
813 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
814 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
815 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
816 #define P_KEEP 0x8000 /**< leave this page alone during spill */
818 uint16_t mp_flags; /**< @ref mdb_page */
819 #define mp_lower mp_pb.pb.pb_lower
820 #define mp_upper mp_pb.pb.pb_upper
821 #define mp_pages mp_pb.pb_pages
824 indx_t pb_lower; /**< lower bound of free space */
825 indx_t pb_upper; /**< upper bound of free space */
827 uint32_t pb_pages; /**< number of overflow pages */
829 indx_t mp_ptrs[1]; /**< dynamic size */
832 /** Size of the page header, excluding dynamic data at the end */
833 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
835 /** Address of first usable data byte in a page, after the header */
836 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
838 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
839 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
841 /** Number of nodes on a page */
842 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
844 /** The amount of space remaining in the page */
845 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
847 /** The percentage of space used in the page, in tenths of a percent. */
848 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
849 ((env)->me_psize - PAGEHDRSZ))
850 /** The minimum page fill factor, in tenths of a percent.
851 * Pages emptier than this are candidates for merging.
853 #define FILL_THRESHOLD 250
855 /** Test if a page is a leaf page */
856 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
857 /** Test if a page is a LEAF2 page */
858 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
859 /** Test if a page is a branch page */
860 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
861 /** Test if a page is an overflow page */
862 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
863 /** Test if a page is a sub page */
864 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
866 /** The number of overflow pages needed to store the given size. */
867 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
869 /** Link in #MDB_txn.%mt_loose_pgs list.
870 * Kept outside the page header, which is needed when reusing the page.
872 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
874 /** Header for a single key/data pair within a page.
875 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
876 * We guarantee 2-byte alignment for 'MDB_node's.
878 typedef struct MDB_node {
879 /** lo and hi are used for data size on leaf nodes and for
880 * child pgno on branch nodes. On 64 bit platforms, flags
881 * is also used for pgno. (Branch nodes have no flags).
882 * They are in host byte order in case that lets some
883 * accesses be optimized into a 32-bit word access.
885 #if BYTE_ORDER == LITTLE_ENDIAN
886 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
888 unsigned short mn_hi, mn_lo;
890 /** @defgroup mdb_node Node Flags
892 * Flags for node headers.
895 #define F_BIGDATA 0x01 /**< data put on overflow page */
896 #define F_SUBDATA 0x02 /**< data is a sub-database */
897 #define F_DUPDATA 0x04 /**< data has duplicates */
899 /** valid flags for #mdb_node_add() */
900 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
903 unsigned short mn_flags; /**< @ref mdb_node */
904 unsigned short mn_ksize; /**< key size */
905 char mn_data[1]; /**< key and data are appended here */
908 /** Size of the node header, excluding dynamic data at the end */
909 #define NODESIZE offsetof(MDB_node, mn_data)
911 /** Bit position of top word in page number, for shifting mn_flags */
912 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
914 /** Size of a node in a branch page with a given key.
915 * This is just the node header plus the key, there is no data.
917 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
919 /** Size of a node in a leaf page with a given key and data.
920 * This is node header plus key plus data size.
922 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
924 /** Address of node \b i in page \b p */
925 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
927 /** Address of the key for the node */
928 #define NODEKEY(node) (void *)((node)->mn_data)
930 /** Address of the data for a node */
931 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
933 /** Get the page number pointed to by a branch node */
934 #define NODEPGNO(node) \
935 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
936 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
937 /** Set the page number in a branch node */
938 #define SETPGNO(node,pgno) do { \
939 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
940 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
942 /** Get the size of the data in a leaf node */
943 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
944 /** Set the size of the data for a leaf node */
945 #define SETDSZ(node,size) do { \
946 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
947 /** The size of a key in a node */
948 #define NODEKSZ(node) ((node)->mn_ksize)
950 /** Copy a page number from src to dst */
952 #define COPY_PGNO(dst,src) dst = src
954 #if SIZE_MAX > 4294967295UL
955 #define COPY_PGNO(dst,src) do { \
956 unsigned short *s, *d; \
957 s = (unsigned short *)&(src); \
958 d = (unsigned short *)&(dst); \
965 #define COPY_PGNO(dst,src) do { \
966 unsigned short *s, *d; \
967 s = (unsigned short *)&(src); \
968 d = (unsigned short *)&(dst); \
974 /** The address of a key in a LEAF2 page.
975 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
976 * There are no node headers, keys are stored contiguously.
978 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
980 /** Set the \b node's key into \b keyptr, if requested. */
981 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
982 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
984 /** Set the \b node's key into \b key. */
985 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
987 /** Information about a single database in the environment. */
988 typedef struct MDB_db {
989 uint32_t md_pad; /**< also ksize for LEAF2 pages */
990 uint16_t md_flags; /**< @ref mdb_dbi_open */
991 uint16_t md_depth; /**< depth of this tree */
992 pgno_t md_branch_pages; /**< number of internal pages */
993 pgno_t md_leaf_pages; /**< number of leaf pages */
994 pgno_t md_overflow_pages; /**< number of overflow pages */
995 size_t md_entries; /**< number of data items */
996 pgno_t md_root; /**< the root page of this tree */
999 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
1000 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
1001 /** #mdb_dbi_open() flags */
1002 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
1003 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
1005 /** Handle for the DB used to track free pages. */
1007 /** Handle for the default DB. */
1009 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
1012 /** Number of meta pages - also hardcoded elsewhere */
1015 /** Meta page content.
1016 * A meta page is the start point for accessing a database snapshot.
1017 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
1019 typedef struct MDB_meta {
1020 /** Stamp identifying this as an LMDB file. It must be set
1023 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
1024 uint32_t mm_version;
1025 void *mm_address; /**< address for fixed mapping */
1026 size_t mm_mapsize; /**< size of mmap region */
1027 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
1028 /** The size of pages used in this DB */
1029 #define mm_psize mm_dbs[FREE_DBI].md_pad
1030 /** Any persistent environment flags. @ref mdb_env */
1031 #define mm_flags mm_dbs[FREE_DBI].md_flags
1032 /** Last used page in the datafile.
1033 * Actually the file may be shorter if the freeDB lists the final pages.
1036 volatile txnid_t mm_txnid; /**< txnid that committed this page */
1039 /** Buffer for a stack-allocated meta page.
1040 * The members define size and alignment, and silence type
1041 * aliasing warnings. They are not used directly; that could
1042 * mean incorrectly using several union members in parallel.
1044 typedef union MDB_metabuf {
1047 char mm_pad[PAGEHDRSZ];
1052 /** Auxiliary DB info.
1053 * The information here is mostly static/read-only. There is
1054 * only a single copy of this record in the environment.
1056 typedef struct MDB_dbx {
1057 MDB_val md_name; /**< name of the database */
1058 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1059 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1060 MDB_rel_func *md_rel; /**< user relocate function */
1061 void *md_relctx; /**< user-provided context for md_rel */
1064 /** A database transaction.
1065 * Every operation requires a transaction handle.
1068 MDB_txn *mt_parent; /**< parent of a nested txn */
1069 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1071 pgno_t mt_next_pgno; /**< next unallocated page */
1072 /** The ID of this transaction. IDs are integers incrementing from 1.
1073 * Only committed write transactions increment the ID. If a transaction
1074 * aborts, the ID may be re-used by the next writer.
1077 MDB_env *mt_env; /**< the DB environment */
1078 /** The list of pages that became unused during this transaction.
1080 MDB_IDL mt_free_pgs;
1081 /** The list of loose pages that became unused and may be reused
1082 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1084 MDB_page *mt_loose_pgs;
1085 /** Number of loose pages (#mt_loose_pgs) */
1087 /** The sorted list of dirty pages we temporarily wrote to disk
1088 * because the dirty list was full. page numbers in here are
1089 * shifted left by 1, deleted slots have the LSB set.
1091 MDB_IDL mt_spill_pgs;
1093 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1094 MDB_ID2L dirty_list;
1095 /** For read txns: This thread/txn's reader table slot, or NULL. */
1098 /** Array of records for each DB known in the environment. */
1100 /** Array of MDB_db records for each known DB */
1102 /** Array of sequence numbers for each DB handle */
1103 unsigned int *mt_dbiseqs;
1104 /** @defgroup mt_dbflag Transaction DB Flags
1108 #define DB_DIRTY 0x01 /**< DB was written in this txn */
1109 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1110 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1111 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1112 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1113 #define DB_DUPDATA 0x20 /**< DB is #MDB_DUPSORT data */
1115 /** In write txns, array of cursors for each DB */
1116 MDB_cursor **mt_cursors;
1117 /** Array of flags for each DB */
1118 unsigned char *mt_dbflags;
1119 /** Number of DB records in use, or 0 when the txn is finished.
1120 * This number only ever increments until the txn finishes; we
1121 * don't decrement it when individual DB handles are closed.
1125 /** @defgroup mdb_txn Transaction Flags
1129 /** #mdb_txn_begin() flags */
1130 #define MDB_TXN_BEGIN_FLAGS MDB_RDONLY
1131 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1132 /* internal txn flags */
1133 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1134 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1135 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1136 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1137 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1138 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1139 /** most operations on the txn are currently illegal */
1140 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1142 unsigned int mt_flags; /**< @ref mdb_txn */
1143 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1144 * Includes ancestor txns' dirty pages not hidden by other txns'
1145 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1146 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1148 unsigned int mt_dirty_room;
1151 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1152 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1153 * raise this on a 64 bit machine.
1155 #define CURSOR_STACK 32
1159 /** Cursors are used for all DB operations.
1160 * A cursor holds a path of (page pointer, key index) from the DB
1161 * root to a position in the DB, plus other state. #MDB_DUPSORT
1162 * cursors include an xcursor to the current data item. Write txns
1163 * track their cursors and keep them up to date when data moves.
1164 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1165 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1168 /** Next cursor on this DB in this txn */
1169 MDB_cursor *mc_next;
1170 /** Backup of the original cursor if this cursor is a shadow */
1171 MDB_cursor *mc_backup;
1172 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1173 struct MDB_xcursor *mc_xcursor;
1174 /** The transaction that owns this cursor */
1176 /** The database handle this cursor operates on */
1178 /** The database record for this cursor */
1180 /** The database auxiliary record for this cursor */
1182 /** The @ref mt_dbflag for this database */
1183 unsigned char *mc_dbflag;
1184 unsigned short mc_snum; /**< number of pushed pages */
1185 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1186 /** @defgroup mdb_cursor Cursor Flags
1188 * Cursor state flags.
1191 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1192 #define C_EOF 0x02 /**< No more data */
1193 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1194 #define C_DEL 0x08 /**< last op was a cursor_del */
1195 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1197 unsigned int mc_flags; /**< @ref mdb_cursor */
1198 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1199 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1202 /** Context for sorted-dup records.
1203 * We could have gone to a fully recursive design, with arbitrarily
1204 * deep nesting of sub-databases. But for now we only handle these
1205 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1207 typedef struct MDB_xcursor {
1208 /** A sub-cursor for traversing the Dup DB */
1209 MDB_cursor mx_cursor;
1210 /** The database record for this Dup DB */
1212 /** The auxiliary DB record for this Dup DB */
1214 /** The @ref mt_dbflag for this Dup DB */
1215 unsigned char mx_dbflag;
1218 /** Check if there is an inited xcursor, so #XCURSOR_REFRESH() is proper */
1219 #define XCURSOR_INITED(mc) \
1220 ((mc)->mc_xcursor && ((mc)->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
1222 /** Update sub-page pointer, if any, in \b mc->mc_xcursor. Needed
1223 * when the node which contains the sub-page may have moved. Called
1224 * with \b mp = mc->mc_pg[mc->mc_top], \b ki = mc->mc_ki[mc->mc_top].
1226 #define XCURSOR_REFRESH(mc, mp, ki) do { \
1227 MDB_page *xr_pg = (mp); \
1228 MDB_node *xr_node = NODEPTR(xr_pg, ki); \
1229 if ((xr_node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) \
1230 (mc)->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(xr_node); \
1233 /** State of FreeDB old pages, stored in the MDB_env */
1234 typedef struct MDB_pgstate {
1235 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1236 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1239 /** The database environment. */
1241 HANDLE me_fd; /**< The main data file */
1242 HANDLE me_lfd; /**< The lock file */
1243 HANDLE me_mfd; /**< For writing and syncing the meta pages */
1244 /** Failed to update the meta page. Probably an I/O error. */
1245 #define MDB_FATAL_ERROR 0x80000000U
1246 /** Some fields are initialized. */
1247 #define MDB_ENV_ACTIVE 0x20000000U
1248 /** me_txkey is set */
1249 #define MDB_ENV_TXKEY 0x10000000U
1250 /** fdatasync is unreliable */
1251 #define MDB_FSYNCONLY 0x08000000U
1252 uint32_t me_flags; /**< @ref mdb_env */
1253 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1254 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1255 unsigned int me_maxreaders; /**< size of the reader table */
1256 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1257 volatile int me_close_readers;
1258 MDB_dbi me_numdbs; /**< number of DBs opened */
1259 MDB_dbi me_maxdbs; /**< size of the DB table */
1260 MDB_PID_T me_pid; /**< process ID of this env */
1261 char *me_path; /**< path to the DB files */
1262 char *me_map; /**< the memory map of the data file */
1263 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1264 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1265 void *me_pbuf; /**< scratch area for DUPSORT put() */
1266 MDB_txn *me_txn; /**< current write transaction */
1267 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1268 size_t me_mapsize; /**< size of the data memory map */
1269 off_t me_size; /**< current file size */
1270 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1271 MDB_dbx *me_dbxs; /**< array of static DB info */
1272 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1273 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1274 pthread_key_t me_txkey; /**< thread-key for readers */
1275 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1276 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1277 # define me_pglast me_pgstate.mf_pglast
1278 # define me_pghead me_pgstate.mf_pghead
1279 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1280 /** IDL of pages that became unused in a write txn */
1281 MDB_IDL me_free_pgs;
1282 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1283 MDB_ID2L me_dirty_list;
1284 /** Max number of freelist items that can fit in a single overflow page */
1286 /** Max size of a node on a page */
1287 unsigned int me_nodemax;
1288 #if !(MDB_MAXKEYSIZE)
1289 unsigned int me_maxkey; /**< max size of a key */
1291 int me_live_reader; /**< have liveness lock in reader table */
1293 int me_pidquery; /**< Used in OpenProcess */
1295 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1296 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1297 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1299 mdb_mutex_t me_rmutex;
1300 mdb_mutex_t me_wmutex;
1302 void *me_userctx; /**< User-settable context */
1303 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1306 /** Nested transaction */
1307 typedef struct MDB_ntxn {
1308 MDB_txn mnt_txn; /**< the transaction */
1309 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1312 /** max number of pages to commit in one writev() call */
1313 #define MDB_COMMIT_PAGES 64
1314 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1315 #undef MDB_COMMIT_PAGES
1316 #define MDB_COMMIT_PAGES IOV_MAX
1319 /** max bytes to write in one call */
1320 #define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
1322 /** Check \b txn and \b dbi arguments to a function */
1323 #define TXN_DBI_EXIST(txn, dbi, validity) \
1324 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1326 /** Check for misused \b dbi handles */
1327 #define TXN_DBI_CHANGED(txn, dbi) \
1328 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1330 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1331 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1332 static int mdb_page_touch(MDB_cursor *mc);
1334 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1335 "reset-tmp", "fail-begin", "fail-beginchild"}
1337 /* mdb_txn_end operation number, for logging */
1338 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1339 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1341 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1342 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1343 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1344 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1345 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1347 static int mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
1348 static int mdb_page_search_root(MDB_cursor *mc,
1349 MDB_val *key, int modify);
1350 #define MDB_PS_MODIFY 1
1351 #define MDB_PS_ROOTONLY 2
1352 #define MDB_PS_FIRST 4
1353 #define MDB_PS_LAST 8
1354 static int mdb_page_search(MDB_cursor *mc,
1355 MDB_val *key, int flags);
1356 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1358 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1359 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1360 pgno_t newpgno, unsigned int nflags);
1362 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1363 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1364 static int mdb_env_write_meta(MDB_txn *txn);
1365 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1366 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1368 static void mdb_env_close0(MDB_env *env, int excl);
1370 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1371 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1372 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1373 static void mdb_node_del(MDB_cursor *mc, int ksize);
1374 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1375 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1376 static int mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
1377 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1378 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1380 static int mdb_rebalance(MDB_cursor *mc);
1381 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1383 static void mdb_cursor_pop(MDB_cursor *mc);
1384 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1386 static int mdb_cursor_del0(MDB_cursor *mc);
1387 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1388 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1389 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1390 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1391 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1393 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1394 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1396 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1397 static void mdb_xcursor_init0(MDB_cursor *mc);
1398 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1399 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1401 static int mdb_drop0(MDB_cursor *mc, int subs);
1402 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1403 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1406 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1409 /** Compare two items pointing at size_t's of unknown alignment. */
1410 #ifdef MISALIGNED_OK
1411 # define mdb_cmp_clong mdb_cmp_long
1413 # define mdb_cmp_clong mdb_cmp_cint
1417 static SECURITY_DESCRIPTOR mdb_null_sd;
1418 static SECURITY_ATTRIBUTES mdb_all_sa;
1419 static int mdb_sec_inited;
1422 static int utf8_to_utf16(const char *src, struct MDB_name *dst, int xtra);
1425 /** Return the library version info. */
1427 mdb_version(int *major, int *minor, int *patch)
1429 if (major) *major = MDB_VERSION_MAJOR;
1430 if (minor) *minor = MDB_VERSION_MINOR;
1431 if (patch) *patch = MDB_VERSION_PATCH;
1432 return MDB_VERSION_STRING;
1435 /** Table of descriptions for LMDB @ref errors */
1436 static char *const mdb_errstr[] = {
1437 "MDB_KEYEXIST: Key/data pair already exists",
1438 "MDB_NOTFOUND: No matching key/data pair found",
1439 "MDB_PAGE_NOTFOUND: Requested page not found",
1440 "MDB_CORRUPTED: Located page was wrong type",
1441 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1442 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1443 "MDB_INVALID: File is not an LMDB file",
1444 "MDB_MAP_FULL: Environment mapsize limit reached",
1445 "MDB_DBS_FULL: Environment maxdbs limit reached",
1446 "MDB_READERS_FULL: Environment maxreaders limit reached",
1447 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1448 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1449 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1450 "MDB_PAGE_FULL: Internal error - page has no more space",
1451 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1452 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1453 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1454 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1455 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1456 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1460 mdb_strerror(int err)
1463 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1464 * This works as long as no function between the call to mdb_strerror
1465 * and the actual use of the message uses more than 4K of stack.
1467 #define MSGSIZE 1024
1468 #define PADSIZE 4096
1469 char buf[MSGSIZE+PADSIZE], *ptr = buf;
1473 return ("Successful return: 0");
1475 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1476 i = err - MDB_KEYEXIST;
1477 return mdb_errstr[i];
1481 /* These are the C-runtime error codes we use. The comment indicates
1482 * their numeric value, and the Win32 error they would correspond to
1483 * if the error actually came from a Win32 API. A major mess, we should
1484 * have used LMDB-specific error codes for everything.
1487 case ENOENT: /* 2, FILE_NOT_FOUND */
1488 case EIO: /* 5, ACCESS_DENIED */
1489 case ENOMEM: /* 12, INVALID_ACCESS */
1490 case EACCES: /* 13, INVALID_DATA */
1491 case EBUSY: /* 16, CURRENT_DIRECTORY */
1492 case EINVAL: /* 22, BAD_COMMAND */
1493 case ENOSPC: /* 28, OUT_OF_PAPER */
1494 return strerror(err);
1499 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1500 FORMAT_MESSAGE_IGNORE_INSERTS,
1501 NULL, err, 0, ptr, MSGSIZE, (va_list *)buf+MSGSIZE);
1504 return strerror(err);
1508 /** assert(3) variant in cursor context */
1509 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1510 /** assert(3) variant in transaction context */
1511 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1512 /** assert(3) variant in environment context */
1513 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1516 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1517 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1520 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1521 const char *func, const char *file, int line)
1524 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1525 file, line, expr_txt, func);
1526 if (env->me_assert_func)
1527 env->me_assert_func(env, buf);
1528 fprintf(stderr, "%s\n", buf);
1532 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1536 /** Return the page number of \b mp which may be sub-page, for debug output */
1538 mdb_dbg_pgno(MDB_page *mp)
1541 COPY_PGNO(ret, mp->mp_pgno);
1545 /** Display a key in hexadecimal and return the address of the result.
1546 * @param[in] key the key to display
1547 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1548 * @return The key in hexadecimal form.
1551 mdb_dkey(MDB_val *key, char *buf)
1554 unsigned char *c = key->mv_data;
1560 if (key->mv_size > DKBUF_MAXKEYSIZE)
1561 return "MDB_MAXKEYSIZE";
1562 /* may want to make this a dynamic check: if the key is mostly
1563 * printable characters, print it as-is instead of converting to hex.
1567 for (i=0; i<key->mv_size; i++)
1568 ptr += sprintf(ptr, "%02x", *c++);
1570 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1576 mdb_leafnode_type(MDB_node *n)
1578 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1579 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1580 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1583 /** Display all the keys in the page. */
1585 mdb_page_list(MDB_page *mp)
1587 pgno_t pgno = mdb_dbg_pgno(mp);
1588 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1590 unsigned int i, nkeys, nsize, total = 0;
1594 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1595 case P_BRANCH: type = "Branch page"; break;
1596 case P_LEAF: type = "Leaf page"; break;
1597 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1598 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1599 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1601 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1602 pgno, mp->mp_pages, state);
1605 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1606 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1609 fprintf(stderr, "Bad page %"Z"u flags 0x%X\n", pgno, mp->mp_flags);
1613 nkeys = NUMKEYS(mp);
1614 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1616 for (i=0; i<nkeys; i++) {
1617 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1618 key.mv_size = nsize = mp->mp_pad;
1619 key.mv_data = LEAF2KEY(mp, i, nsize);
1621 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1624 node = NODEPTR(mp, i);
1625 key.mv_size = node->mn_ksize;
1626 key.mv_data = node->mn_data;
1627 nsize = NODESIZE + key.mv_size;
1628 if (IS_BRANCH(mp)) {
1629 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1633 if (F_ISSET(node->mn_flags, F_BIGDATA))
1634 nsize += sizeof(pgno_t);
1636 nsize += NODEDSZ(node);
1638 nsize += sizeof(indx_t);
1639 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1640 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1642 total = EVEN(total);
1644 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1645 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1649 mdb_cursor_chk(MDB_cursor *mc)
1655 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1656 for (i=0; i<mc->mc_top; i++) {
1658 node = NODEPTR(mp, mc->mc_ki[i]);
1659 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1662 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1664 if (XCURSOR_INITED(mc)) {
1665 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1666 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1667 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1675 /** Count all the pages in each DB and in the freelist
1676 * and make sure it matches the actual number of pages
1678 * All named DBs must be open for a correct count.
1680 static void mdb_audit(MDB_txn *txn)
1684 MDB_ID freecount, count;
1689 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1690 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1691 freecount += *(MDB_ID *)data.mv_data;
1692 mdb_tassert(txn, rc == MDB_NOTFOUND);
1695 for (i = 0; i<txn->mt_numdbs; i++) {
1697 if (!(txn->mt_dbflags[i] & DB_VALID))
1699 mdb_cursor_init(&mc, txn, i, &mx);
1700 if (txn->mt_dbs[i].md_root == P_INVALID)
1702 count += txn->mt_dbs[i].md_branch_pages +
1703 txn->mt_dbs[i].md_leaf_pages +
1704 txn->mt_dbs[i].md_overflow_pages;
1705 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1706 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1707 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1710 mp = mc.mc_pg[mc.mc_top];
1711 for (j=0; j<NUMKEYS(mp); j++) {
1712 MDB_node *leaf = NODEPTR(mp, j);
1713 if (leaf->mn_flags & F_SUBDATA) {
1715 memcpy(&db, NODEDATA(leaf), sizeof(db));
1716 count += db.md_branch_pages + db.md_leaf_pages +
1717 db.md_overflow_pages;
1721 mdb_tassert(txn, rc == MDB_NOTFOUND);
1724 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1725 fprintf(stderr, "audit: %"Z"u freecount: %"Z"u count: %"Z"u total: %"Z"u next_pgno: %"Z"u\n",
1726 txn->mt_txnid, freecount, count+NUM_METAS,
1727 freecount+count+NUM_METAS, txn->mt_next_pgno);
1733 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1735 return txn->mt_dbxs[dbi].md_cmp(a, b);
1739 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1741 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1742 #if UINT_MAX < SIZE_MAX
1743 if (dcmp == mdb_cmp_int && a->mv_size == sizeof(size_t))
1744 dcmp = mdb_cmp_clong;
1749 /** Allocate memory for a page.
1750 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1751 * Set #MDB_TXN_ERROR on failure.
1754 mdb_page_malloc(MDB_txn *txn, unsigned num)
1756 MDB_env *env = txn->mt_env;
1757 MDB_page *ret = env->me_dpages;
1758 size_t psize = env->me_psize, sz = psize, off;
1759 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1760 * For a single page alloc, we init everything after the page header.
1761 * For multi-page, we init the final page; if the caller needed that
1762 * many pages they will be filling in at least up to the last page.
1766 VGMEMP_ALLOC(env, ret, sz);
1767 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1768 env->me_dpages = ret->mp_next;
1771 psize -= off = PAGEHDRSZ;
1776 if ((ret = malloc(sz)) != NULL) {
1777 VGMEMP_ALLOC(env, ret, sz);
1778 if (!(env->me_flags & MDB_NOMEMINIT)) {
1779 memset((char *)ret + off, 0, psize);
1783 txn->mt_flags |= MDB_TXN_ERROR;
1787 /** Free a single page.
1788 * Saves single pages to a list, for future reuse.
1789 * (This is not used for multi-page overflow pages.)
1792 mdb_page_free(MDB_env *env, MDB_page *mp)
1794 mp->mp_next = env->me_dpages;
1795 VGMEMP_FREE(env, mp);
1796 env->me_dpages = mp;
1799 /** Free a dirty page */
1801 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1803 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1804 mdb_page_free(env, dp);
1806 /* large pages just get freed directly */
1807 VGMEMP_FREE(env, dp);
1812 /** Return all dirty pages to dpage list */
1814 mdb_dlist_free(MDB_txn *txn)
1816 MDB_env *env = txn->mt_env;
1817 MDB_ID2L dl = txn->mt_u.dirty_list;
1818 unsigned i, n = dl[0].mid;
1820 for (i = 1; i <= n; i++) {
1821 mdb_dpage_free(env, dl[i].mptr);
1826 /** Loosen or free a single page.
1827 * Saves single pages to a list for future reuse
1828 * in this same txn. It has been pulled from the freeDB
1829 * and already resides on the dirty list, but has been
1830 * deleted. Use these pages first before pulling again
1833 * If the page wasn't dirtied in this txn, just add it
1834 * to this txn's free list.
1837 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1840 pgno_t pgno = mp->mp_pgno;
1841 MDB_txn *txn = mc->mc_txn;
1843 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1844 if (txn->mt_parent) {
1845 MDB_ID2 *dl = txn->mt_u.dirty_list;
1846 /* If txn has a parent, make sure the page is in our
1850 unsigned x = mdb_mid2l_search(dl, pgno);
1851 if (x <= dl[0].mid && dl[x].mid == pgno) {
1852 if (mp != dl[x].mptr) { /* bad cursor? */
1853 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1854 txn->mt_flags |= MDB_TXN_ERROR;
1855 return MDB_CORRUPTED;
1862 /* no parent txn, so it's just ours */
1867 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1869 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1870 txn->mt_loose_pgs = mp;
1871 txn->mt_loose_count++;
1872 mp->mp_flags |= P_LOOSE;
1874 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1882 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1883 * @param[in] mc A cursor handle for the current operation.
1884 * @param[in] pflags Flags of the pages to update:
1885 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1886 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1887 * @return 0 on success, non-zero on failure.
1890 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1892 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1893 MDB_txn *txn = mc->mc_txn;
1894 MDB_cursor *m3, *m0 = mc;
1899 int rc = MDB_SUCCESS, level;
1901 /* Mark pages seen by cursors */
1902 if (mc->mc_flags & C_UNTRACK)
1903 mc = NULL; /* will find mc in mt_cursors */
1904 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1905 for (; mc; mc=mc->mc_next) {
1906 if (!(mc->mc_flags & C_INITIALIZED))
1908 for (m3 = mc;; m3 = &mx->mx_cursor) {
1910 for (j=0; j<m3->mc_snum; j++) {
1912 if ((mp->mp_flags & Mask) == pflags)
1913 mp->mp_flags ^= P_KEEP;
1915 mx = m3->mc_xcursor;
1916 /* Proceed to mx if it is at a sub-database */
1917 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1919 if (! (mp && (mp->mp_flags & P_LEAF)))
1921 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1922 if (!(leaf->mn_flags & F_SUBDATA))
1931 /* Mark dirty root pages */
1932 for (i=0; i<txn->mt_numdbs; i++) {
1933 if (txn->mt_dbflags[i] & DB_DIRTY) {
1934 pgno_t pgno = txn->mt_dbs[i].md_root;
1935 if (pgno == P_INVALID)
1937 if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
1939 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1940 dp->mp_flags ^= P_KEEP;
1948 static int mdb_page_flush(MDB_txn *txn, int keep);
1950 /** Spill pages from the dirty list back to disk.
1951 * This is intended to prevent running into #MDB_TXN_FULL situations,
1952 * but note that they may still occur in a few cases:
1953 * 1) our estimate of the txn size could be too small. Currently this
1954 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1955 * 2) child txns may run out of space if their parents dirtied a
1956 * lot of pages and never spilled them. TODO: we probably should do
1957 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1958 * the parent's dirty_room is below a given threshold.
1960 * Otherwise, if not using nested txns, it is expected that apps will
1961 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1962 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1963 * If the txn never references them again, they can be left alone.
1964 * If the txn only reads them, they can be used without any fuss.
1965 * If the txn writes them again, they can be dirtied immediately without
1966 * going thru all of the work of #mdb_page_touch(). Such references are
1967 * handled by #mdb_page_unspill().
1969 * Also note, we never spill DB root pages, nor pages of active cursors,
1970 * because we'll need these back again soon anyway. And in nested txns,
1971 * we can't spill a page in a child txn if it was already spilled in a
1972 * parent txn. That would alter the parent txns' data even though
1973 * the child hasn't committed yet, and we'd have no way to undo it if
1974 * the child aborted.
1976 * @param[in] m0 cursor A cursor handle identifying the transaction and
1977 * database for which we are checking space.
1978 * @param[in] key For a put operation, the key being stored.
1979 * @param[in] data For a put operation, the data being stored.
1980 * @return 0 on success, non-zero on failure.
1983 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1985 MDB_txn *txn = m0->mc_txn;
1987 MDB_ID2L dl = txn->mt_u.dirty_list;
1988 unsigned int i, j, need;
1991 if (m0->mc_flags & C_SUB)
1994 /* Estimate how much space this op will take */
1995 i = m0->mc_db->md_depth;
1996 /* Named DBs also dirty the main DB */
1997 if (m0->mc_dbi >= CORE_DBS)
1998 i += txn->mt_dbs[MAIN_DBI].md_depth;
1999 /* For puts, roughly factor in the key+data size */
2001 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
2002 i += i; /* double it for good measure */
2005 if (txn->mt_dirty_room > i)
2008 if (!txn->mt_spill_pgs) {
2009 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
2010 if (!txn->mt_spill_pgs)
2013 /* purge deleted slots */
2014 MDB_IDL sl = txn->mt_spill_pgs;
2015 unsigned int num = sl[0];
2017 for (i=1; i<=num; i++) {
2024 /* Preserve pages which may soon be dirtied again */
2025 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2028 /* Less aggressive spill - we originally spilled the entire dirty list,
2029 * with a few exceptions for cursor pages and DB root pages. But this
2030 * turns out to be a lot of wasted effort because in a large txn many
2031 * of those pages will need to be used again. So now we spill only 1/8th
2032 * of the dirty pages. Testing revealed this to be a good tradeoff,
2033 * better than 1/2, 1/4, or 1/10.
2035 if (need < MDB_IDL_UM_MAX / 8)
2036 need = MDB_IDL_UM_MAX / 8;
2038 /* Save the page IDs of all the pages we're flushing */
2039 /* flush from the tail forward, this saves a lot of shifting later on. */
2040 for (i=dl[0].mid; i && need; i--) {
2041 MDB_ID pn = dl[i].mid << 1;
2043 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2045 /* Can't spill twice, make sure it's not already in a parent's
2048 if (txn->mt_parent) {
2050 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2051 if (tx2->mt_spill_pgs) {
2052 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2053 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2054 dp->mp_flags |= P_KEEP;
2062 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2066 mdb_midl_sort(txn->mt_spill_pgs);
2068 /* Flush the spilled part of dirty list */
2069 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2072 /* Reset any dirty pages we kept that page_flush didn't see */
2073 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2076 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2080 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2082 mdb_find_oldest(MDB_txn *txn)
2085 txnid_t mr, oldest = txn->mt_txnid - 1;
2086 if (txn->mt_env->me_txns) {
2087 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2088 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2099 /** Add a page to the txn's dirty list */
2101 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2104 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2106 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2107 insert = mdb_mid2l_append;
2109 insert = mdb_mid2l_insert;
2111 mid.mid = mp->mp_pgno;
2113 rc = insert(txn->mt_u.dirty_list, &mid);
2114 mdb_tassert(txn, rc == 0);
2115 txn->mt_dirty_room--;
2118 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2119 * me_pghead and mt_next_pgno. Set #MDB_TXN_ERROR on failure.
2121 * If there are free pages available from older transactions, they
2122 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2123 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2124 * and move me_pglast to say which records were consumed. Only this
2125 * function can create me_pghead and move me_pglast/mt_next_pgno.
2126 * @param[in] mc cursor A cursor handle identifying the transaction and
2127 * database for which we are allocating.
2128 * @param[in] num the number of pages to allocate.
2129 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2130 * will always be satisfied by a single contiguous chunk of memory.
2131 * @return 0 on success, non-zero on failure.
2134 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2136 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2137 /* Get at most <Max_retries> more freeDB records once me_pghead
2138 * has enough pages. If not enough, use new pages from the map.
2139 * If <Paranoid> and mc is updating the freeDB, only get new
2140 * records if me_pghead is empty. Then the freelist cannot play
2141 * catch-up with itself by growing while trying to save it.
2143 enum { Paranoid = 1, Max_retries = 500 };
2145 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2147 int rc, retry = num * 60;
2148 MDB_txn *txn = mc->mc_txn;
2149 MDB_env *env = txn->mt_env;
2150 pgno_t pgno, *mop = env->me_pghead;
2151 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2153 txnid_t oldest = 0, last;
2158 /* If there are any loose pages, just use them */
2159 if (num == 1 && txn->mt_loose_pgs) {
2160 np = txn->mt_loose_pgs;
2161 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2162 txn->mt_loose_count--;
2163 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
2171 /* If our dirty list is already full, we can't do anything */
2172 if (txn->mt_dirty_room == 0) {
2177 for (op = MDB_FIRST;; op = MDB_NEXT) {
2182 /* Seek a big enough contiguous page range. Prefer
2183 * pages at the tail, just truncating the list.
2189 if (mop[i-n2] == pgno+n2)
2196 if (op == MDB_FIRST) { /* 1st iteration */
2197 /* Prepare to fetch more and coalesce */
2198 last = env->me_pglast;
2199 oldest = env->me_pgoldest;
2200 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2203 key.mv_data = &last; /* will look up last+1 */
2204 key.mv_size = sizeof(last);
2206 if (Paranoid && mc->mc_dbi == FREE_DBI)
2209 if (Paranoid && retry < 0 && mop_len)
2213 /* Do not fetch more if the record will be too recent */
2214 if (oldest <= last) {
2216 oldest = mdb_find_oldest(txn);
2217 env->me_pgoldest = oldest;
2223 rc = mdb_cursor_get(&m2, &key, NULL, op);
2225 if (rc == MDB_NOTFOUND)
2229 last = *(txnid_t*)key.mv_data;
2230 if (oldest <= last) {
2232 oldest = mdb_find_oldest(txn);
2233 env->me_pgoldest = oldest;
2239 np = m2.mc_pg[m2.mc_top];
2240 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2241 if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
2244 idl = (MDB_ID *) data.mv_data;
2247 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2252 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2254 mop = env->me_pghead;
2256 env->me_pglast = last;
2258 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2259 last, txn->mt_dbs[FREE_DBI].md_root, i));
2261 DPRINTF(("IDL %"Z"u", idl[j]));
2263 /* Merge in descending sorted order */
2264 mdb_midl_xmerge(mop, idl);
2268 /* Use new pages from the map when nothing suitable in the freeDB */
2270 pgno = txn->mt_next_pgno;
2271 if (pgno + num >= env->me_maxpg) {
2272 DPUTS("DB size maxed out");
2278 if (env->me_flags & MDB_WRITEMAP) {
2279 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2281 if (!(np = mdb_page_malloc(txn, num))) {
2287 mop[0] = mop_len -= num;
2288 /* Move any stragglers down */
2289 for (j = i-num; j < mop_len; )
2290 mop[++j] = mop[++i];
2292 txn->mt_next_pgno = pgno + num;
2295 mdb_page_dirty(txn, np);
2301 txn->mt_flags |= MDB_TXN_ERROR;
2305 /** Copy the used portions of a non-overflow page.
2306 * @param[in] dst page to copy into
2307 * @param[in] src page to copy from
2308 * @param[in] psize size of a page
2311 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2313 enum { Align = sizeof(pgno_t) };
2314 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2316 /* If page isn't full, just copy the used portion. Adjust
2317 * alignment so memcpy may copy words instead of bytes.
2319 if ((unused &= -Align) && !IS_LEAF2(src)) {
2320 upper = (upper + PAGEBASE) & -Align;
2321 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2322 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2325 memcpy(dst, src, psize - unused);
2329 /** Pull a page off the txn's spill list, if present.
2330 * If a page being referenced was spilled to disk in this txn, bring
2331 * it back and make it dirty/writable again.
2332 * @param[in] txn the transaction handle.
2333 * @param[in] mp the page being referenced. It must not be dirty.
2334 * @param[out] ret the writable page, if any. ret is unchanged if
2335 * mp wasn't spilled.
2338 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2340 MDB_env *env = txn->mt_env;
2343 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2345 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2346 if (!tx2->mt_spill_pgs)
2348 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2349 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2352 if (txn->mt_dirty_room == 0)
2353 return MDB_TXN_FULL;
2354 if (IS_OVERFLOW(mp))
2358 if (env->me_flags & MDB_WRITEMAP) {
2361 np = mdb_page_malloc(txn, num);
2365 memcpy(np, mp, num * env->me_psize);
2367 mdb_page_copy(np, mp, env->me_psize);
2370 /* If in current txn, this page is no longer spilled.
2371 * If it happens to be the last page, truncate the spill list.
2372 * Otherwise mark it as deleted by setting the LSB.
2374 if (x == txn->mt_spill_pgs[0])
2375 txn->mt_spill_pgs[0]--;
2377 txn->mt_spill_pgs[x] |= 1;
2378 } /* otherwise, if belonging to a parent txn, the
2379 * page remains spilled until child commits
2382 mdb_page_dirty(txn, np);
2383 np->mp_flags |= P_DIRTY;
2391 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2392 * Set #MDB_TXN_ERROR on failure.
2393 * @param[in] mc cursor pointing to the page to be touched
2394 * @return 0 on success, non-zero on failure.
2397 mdb_page_touch(MDB_cursor *mc)
2399 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2400 MDB_txn *txn = mc->mc_txn;
2401 MDB_cursor *m2, *m3;
2405 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2406 if (txn->mt_flags & MDB_TXN_SPILLS) {
2408 rc = mdb_page_unspill(txn, mp, &np);
2414 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2415 (rc = mdb_page_alloc(mc, 1, &np)))
2418 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2419 mp->mp_pgno, pgno));
2420 mdb_cassert(mc, mp->mp_pgno != pgno);
2421 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2422 /* Update the parent page, if any, to point to the new page */
2424 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2425 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2426 SETPGNO(node, pgno);
2428 mc->mc_db->md_root = pgno;
2430 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2431 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2433 /* If txn has a parent, make sure the page is in our
2437 unsigned x = mdb_mid2l_search(dl, pgno);
2438 if (x <= dl[0].mid && dl[x].mid == pgno) {
2439 if (mp != dl[x].mptr) { /* bad cursor? */
2440 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2441 txn->mt_flags |= MDB_TXN_ERROR;
2442 return MDB_CORRUPTED;
2447 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2449 np = mdb_page_malloc(txn, 1);
2454 rc = mdb_mid2l_insert(dl, &mid);
2455 mdb_cassert(mc, rc == 0);
2460 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2462 np->mp_flags |= P_DIRTY;
2465 /* Adjust cursors pointing to mp */
2466 mc->mc_pg[mc->mc_top] = np;
2467 m2 = txn->mt_cursors[mc->mc_dbi];
2468 if (mc->mc_flags & C_SUB) {
2469 for (; m2; m2=m2->mc_next) {
2470 m3 = &m2->mc_xcursor->mx_cursor;
2471 if (m3->mc_snum < mc->mc_snum) continue;
2472 if (m3->mc_pg[mc->mc_top] == mp)
2473 m3->mc_pg[mc->mc_top] = np;
2476 for (; m2; m2=m2->mc_next) {
2477 if (m2->mc_snum < mc->mc_snum) continue;
2478 if (m2 == mc) continue;
2479 if (m2->mc_pg[mc->mc_top] == mp) {
2480 m2->mc_pg[mc->mc_top] = np;
2481 if (XCURSOR_INITED(m2) && IS_LEAF(np))
2482 XCURSOR_REFRESH(m2, np, m2->mc_ki[mc->mc_top]);
2489 txn->mt_flags |= MDB_TXN_ERROR;
2494 mdb_env_sync(MDB_env *env, int force)
2497 if (env->me_flags & MDB_RDONLY)
2499 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2500 if (env->me_flags & MDB_WRITEMAP) {
2501 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2502 ? MS_ASYNC : MS_SYNC;
2503 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2506 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2510 #ifdef BROKEN_FDATASYNC
2511 if (env->me_flags & MDB_FSYNCONLY) {
2512 if (fsync(env->me_fd))
2516 if (MDB_FDATASYNC(env->me_fd))
2523 /** Back up parent txn's cursors, then grab the originals for tracking */
2525 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2527 MDB_cursor *mc, *bk;
2532 for (i = src->mt_numdbs; --i >= 0; ) {
2533 if ((mc = src->mt_cursors[i]) != NULL) {
2534 size = sizeof(MDB_cursor);
2536 size += sizeof(MDB_xcursor);
2537 for (; mc; mc = bk->mc_next) {
2543 mc->mc_db = &dst->mt_dbs[i];
2544 /* Kill pointers into src to reduce abuse: The
2545 * user may not use mc until dst ends. But we need a valid
2546 * txn pointer here for cursor fixups to keep working.
2549 mc->mc_dbflag = &dst->mt_dbflags[i];
2550 if ((mx = mc->mc_xcursor) != NULL) {
2551 *(MDB_xcursor *)(bk+1) = *mx;
2552 mx->mx_cursor.mc_txn = dst;
2554 mc->mc_next = dst->mt_cursors[i];
2555 dst->mt_cursors[i] = mc;
2562 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2563 * @param[in] txn the transaction handle.
2564 * @param[in] merge true to keep changes to parent cursors, false to revert.
2565 * @return 0 on success, non-zero on failure.
2568 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2570 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2574 for (i = txn->mt_numdbs; --i >= 0; ) {
2575 for (mc = cursors[i]; mc; mc = next) {
2577 if ((bk = mc->mc_backup) != NULL) {
2579 /* Commit changes to parent txn */
2580 mc->mc_next = bk->mc_next;
2581 mc->mc_backup = bk->mc_backup;
2582 mc->mc_txn = bk->mc_txn;
2583 mc->mc_db = bk->mc_db;
2584 mc->mc_dbflag = bk->mc_dbflag;
2585 if ((mx = mc->mc_xcursor) != NULL)
2586 mx->mx_cursor.mc_txn = bk->mc_txn;
2588 /* Abort nested txn */
2590 if ((mx = mc->mc_xcursor) != NULL)
2591 *mx = *(MDB_xcursor *)(bk+1);
2595 /* Only malloced cursors are permanently tracked. */
2602 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2608 Pidset = F_SETLK, Pidcheck = F_GETLK
2612 /** Set or check a pid lock. Set returns 0 on success.
2613 * Check returns 0 if the process is certainly dead, nonzero if it may
2614 * be alive (the lock exists or an error happened so we do not know).
2616 * On Windows Pidset is a no-op, we merely check for the existence
2617 * of the process with the given pid. On POSIX we use a single byte
2618 * lock on the lockfile, set at an offset equal to the pid.
2621 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2623 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2626 if (op == Pidcheck) {
2627 h = OpenProcess(env->me_pidquery, FALSE, pid);
2628 /* No documented "no such process" code, but other program use this: */
2630 return ErrCode() != ERROR_INVALID_PARAMETER;
2631 /* A process exists until all handles to it close. Has it exited? */
2632 ret = WaitForSingleObject(h, 0) != 0;
2639 struct flock lock_info;
2640 memset(&lock_info, 0, sizeof(lock_info));
2641 lock_info.l_type = F_WRLCK;
2642 lock_info.l_whence = SEEK_SET;
2643 lock_info.l_start = pid;
2644 lock_info.l_len = 1;
2645 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2646 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2648 } else if ((rc = ErrCode()) == EINTR) {
2656 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2657 * @param[in] txn the transaction handle to initialize
2658 * @return 0 on success, non-zero on failure.
2661 mdb_txn_renew0(MDB_txn *txn)
2663 MDB_env *env = txn->mt_env;
2664 MDB_txninfo *ti = env->me_txns;
2666 unsigned int i, nr, flags = txn->mt_flags;
2668 int rc, new_notls = 0;
2670 if ((flags &= MDB_TXN_RDONLY) != 0) {
2672 meta = mdb_env_pick_meta(env);
2673 txn->mt_txnid = meta->mm_txnid;
2674 txn->mt_u.reader = NULL;
2676 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2677 pthread_getspecific(env->me_txkey);
2679 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2680 return MDB_BAD_RSLOT;
2682 MDB_PID_T pid = env->me_pid;
2683 MDB_THR_T tid = pthread_self();
2684 mdb_mutexref_t rmutex = env->me_rmutex;
2686 if (!env->me_live_reader) {
2687 rc = mdb_reader_pid(env, Pidset, pid);
2690 env->me_live_reader = 1;
2693 if (LOCK_MUTEX(rc, env, rmutex))
2695 nr = ti->mti_numreaders;
2696 for (i=0; i<nr; i++)
2697 if (ti->mti_readers[i].mr_pid == 0)
2699 if (i == env->me_maxreaders) {
2700 UNLOCK_MUTEX(rmutex);
2701 return MDB_READERS_FULL;
2703 r = &ti->mti_readers[i];
2704 /* Claim the reader slot, carefully since other code
2705 * uses the reader table un-mutexed: First reset the
2706 * slot, next publish it in mti_numreaders. After
2707 * that, it is safe for mdb_env_close() to touch it.
2708 * When it will be closed, we can finally claim it.
2711 r->mr_txnid = (txnid_t)-1;
2714 ti->mti_numreaders = ++nr;
2715 env->me_close_readers = nr;
2717 UNLOCK_MUTEX(rmutex);
2719 new_notls = (env->me_flags & MDB_NOTLS);
2720 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2725 do /* LY: Retry on a race, ITS#7970. */
2726 r->mr_txnid = ti->mti_txnid;
2727 while(r->mr_txnid != ti->mti_txnid);
2728 txn->mt_txnid = r->mr_txnid;
2729 txn->mt_u.reader = r;
2730 meta = env->me_metas[txn->mt_txnid & 1];
2734 /* Not yet touching txn == env->me_txn0, it may be active */
2736 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2738 txn->mt_txnid = ti->mti_txnid;
2739 meta = env->me_metas[txn->mt_txnid & 1];
2741 meta = mdb_env_pick_meta(env);
2742 txn->mt_txnid = meta->mm_txnid;
2746 if (txn->mt_txnid == mdb_debug_start)
2749 txn->mt_child = NULL;
2750 txn->mt_loose_pgs = NULL;
2751 txn->mt_loose_count = 0;
2752 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2753 txn->mt_u.dirty_list = env->me_dirty_list;
2754 txn->mt_u.dirty_list[0].mid = 0;
2755 txn->mt_free_pgs = env->me_free_pgs;
2756 txn->mt_free_pgs[0] = 0;
2757 txn->mt_spill_pgs = NULL;
2759 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2762 /* Copy the DB info and flags */
2763 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
2765 /* Moved to here to avoid a data race in read TXNs */
2766 txn->mt_next_pgno = meta->mm_last_pg+1;
2768 txn->mt_flags = flags;
2771 txn->mt_numdbs = env->me_numdbs;
2772 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
2773 x = env->me_dbflags[i];
2774 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2775 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
2777 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
2778 txn->mt_dbflags[FREE_DBI] = DB_VALID;
2780 if (env->me_flags & MDB_FATAL_ERROR) {
2781 DPUTS("environment had fatal error, must shutdown!");
2783 } else if (env->me_maxpg < txn->mt_next_pgno) {
2784 rc = MDB_MAP_RESIZED;
2788 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
2793 mdb_txn_renew(MDB_txn *txn)
2797 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
2800 rc = mdb_txn_renew0(txn);
2801 if (rc == MDB_SUCCESS) {
2802 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2803 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2804 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2810 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2814 int rc, size, tsize;
2816 flags &= MDB_TXN_BEGIN_FLAGS;
2817 flags |= env->me_flags & MDB_WRITEMAP;
2819 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
2823 /* Nested transactions: Max 1 child, write txns only, no writemap */
2824 flags |= parent->mt_flags;
2825 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
2826 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2828 /* Child txns save MDB_pgstate and use own copy of cursors */
2829 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
2830 size += tsize = sizeof(MDB_ntxn);
2831 } else if (flags & MDB_RDONLY) {
2832 size = env->me_maxdbs * (sizeof(MDB_db)+1);
2833 size += tsize = sizeof(MDB_txn);
2835 /* Reuse preallocated write txn. However, do not touch it until
2836 * mdb_txn_renew0() succeeds, since it currently may be active.
2841 if ((txn = calloc(1, size)) == NULL) {
2842 DPRINTF(("calloc: %s", strerror(errno)));
2845 txn->mt_dbxs = env->me_dbxs; /* static */
2846 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2847 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
2848 txn->mt_flags = flags;
2853 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2854 txn->mt_dbiseqs = parent->mt_dbiseqs;
2855 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2856 if (!txn->mt_u.dirty_list ||
2857 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2859 free(txn->mt_u.dirty_list);
2863 txn->mt_txnid = parent->mt_txnid;
2864 txn->mt_dirty_room = parent->mt_dirty_room;
2865 txn->mt_u.dirty_list[0].mid = 0;
2866 txn->mt_spill_pgs = NULL;
2867 txn->mt_next_pgno = parent->mt_next_pgno;
2868 parent->mt_flags |= MDB_TXN_HAS_CHILD;
2869 parent->mt_child = txn;
2870 txn->mt_parent = parent;
2871 txn->mt_numdbs = parent->mt_numdbs;
2872 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2873 /* Copy parent's mt_dbflags, but clear DB_NEW */
2874 for (i=0; i<txn->mt_numdbs; i++)
2875 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2877 ntxn = (MDB_ntxn *)txn;
2878 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2879 if (env->me_pghead) {
2880 size = MDB_IDL_SIZEOF(env->me_pghead);
2881 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2883 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2888 rc = mdb_cursor_shadow(parent, txn);
2890 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
2891 } else { /* MDB_RDONLY */
2892 txn->mt_dbiseqs = env->me_dbiseqs;
2894 rc = mdb_txn_renew0(txn);
2897 if (txn != env->me_txn0)
2900 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
2902 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2903 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
2904 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2911 mdb_txn_env(MDB_txn *txn)
2913 if(!txn) return NULL;
2918 mdb_txn_id(MDB_txn *txn)
2921 return txn->mt_txnid;
2924 /** Export or close DBI handles opened in this txn. */
2926 mdb_dbis_update(MDB_txn *txn, int keep)
2929 MDB_dbi n = txn->mt_numdbs;
2930 MDB_env *env = txn->mt_env;
2931 unsigned char *tdbflags = txn->mt_dbflags;
2933 for (i = n; --i >= CORE_DBS;) {
2934 if (tdbflags[i] & DB_NEW) {
2936 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2938 char *ptr = env->me_dbxs[i].md_name.mv_data;
2940 env->me_dbxs[i].md_name.mv_data = NULL;
2941 env->me_dbxs[i].md_name.mv_size = 0;
2942 env->me_dbflags[i] = 0;
2943 env->me_dbiseqs[i]++;
2949 if (keep && env->me_numdbs < n)
2953 /** End a transaction, except successful commit of a nested transaction.
2954 * May be called twice for readonly txns: First reset it, then abort.
2955 * @param[in] txn the transaction handle to end
2956 * @param[in] mode why and how to end the transaction
2959 mdb_txn_end(MDB_txn *txn, unsigned mode)
2961 MDB_env *env = txn->mt_env;
2963 static const char *const names[] = MDB_END_NAMES;
2966 /* Export or close DBI handles opened in this txn */
2967 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
2969 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2970 names[mode & MDB_END_OPMASK],
2971 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2972 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2974 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2975 if (txn->mt_u.reader) {
2976 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2977 if (!(env->me_flags & MDB_NOTLS)) {
2978 txn->mt_u.reader = NULL; /* txn does not own reader */
2979 } else if (mode & MDB_END_SLOT) {
2980 txn->mt_u.reader->mr_pid = 0;
2981 txn->mt_u.reader = NULL;
2982 } /* else txn owns the slot until it does MDB_END_SLOT */
2984 txn->mt_numdbs = 0; /* prevent further DBI activity */
2985 txn->mt_flags |= MDB_TXN_FINISHED;
2987 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
2988 pgno_t *pghead = env->me_pghead;
2990 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
2991 mdb_cursors_close(txn, 0);
2992 if (!(env->me_flags & MDB_WRITEMAP)) {
2993 mdb_dlist_free(txn);
2997 txn->mt_flags = MDB_TXN_FINISHED;
2999 if (!txn->mt_parent) {
3000 mdb_midl_shrink(&txn->mt_free_pgs);
3001 env->me_free_pgs = txn->mt_free_pgs;
3003 env->me_pghead = NULL;
3007 mode = 0; /* txn == env->me_txn0, do not free() it */
3009 /* The writer mutex was locked in mdb_txn_begin. */
3011 UNLOCK_MUTEX(env->me_wmutex);
3013 txn->mt_parent->mt_child = NULL;
3014 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
3015 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
3016 mdb_midl_free(txn->mt_free_pgs);
3017 mdb_midl_free(txn->mt_spill_pgs);
3018 free(txn->mt_u.dirty_list);
3021 mdb_midl_free(pghead);
3024 if (mode & MDB_END_FREE)
3029 mdb_txn_reset(MDB_txn *txn)
3034 /* This call is only valid for read-only txns */
3035 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3038 mdb_txn_end(txn, MDB_END_RESET);
3042 mdb_txn_abort(MDB_txn *txn)
3048 mdb_txn_abort(txn->mt_child);
3050 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3053 /** Save the freelist as of this transaction to the freeDB.
3054 * This changes the freelist. Keep trying until it stabilizes.
3057 mdb_freelist_save(MDB_txn *txn)
3059 /* env->me_pghead[] can grow and shrink during this call.
3060 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3061 * Page numbers cannot disappear from txn->mt_free_pgs[].
3064 MDB_env *env = txn->mt_env;
3065 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3066 txnid_t pglast = 0, head_id = 0;
3067 pgno_t freecnt = 0, *free_pgs, *mop;
3068 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3070 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3072 if (env->me_pghead) {
3073 /* Make sure first page of freeDB is touched and on freelist */
3074 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3075 if (rc && rc != MDB_NOTFOUND)
3079 if (!env->me_pghead && txn->mt_loose_pgs) {
3080 /* Put loose page numbers in mt_free_pgs, since
3081 * we may be unable to return them to me_pghead.
3083 MDB_page *mp = txn->mt_loose_pgs;
3084 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3086 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3087 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3088 txn->mt_loose_pgs = NULL;
3089 txn->mt_loose_count = 0;
3092 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3093 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3094 ? SSIZE_MAX : maxfree_1pg;
3097 /* Come back here after each Put() in case freelist changed */
3102 /* If using records from freeDB which we have not yet
3103 * deleted, delete them and any we reserved for me_pghead.
3105 while (pglast < env->me_pglast) {
3106 rc = mdb_cursor_first(&mc, &key, NULL);
3109 pglast = head_id = *(txnid_t *)key.mv_data;
3110 total_room = head_room = 0;
3111 mdb_tassert(txn, pglast <= env->me_pglast);
3112 rc = mdb_cursor_del(&mc, 0);
3117 /* Save the IDL of pages freed by this txn, to a single record */
3118 if (freecnt < txn->mt_free_pgs[0]) {
3120 /* Make sure last page of freeDB is touched and on freelist */
3121 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3122 if (rc && rc != MDB_NOTFOUND)
3125 free_pgs = txn->mt_free_pgs;
3126 /* Write to last page of freeDB */
3127 key.mv_size = sizeof(txn->mt_txnid);
3128 key.mv_data = &txn->mt_txnid;
3130 freecnt = free_pgs[0];
3131 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3132 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3135 /* Retry if mt_free_pgs[] grew during the Put() */
3136 free_pgs = txn->mt_free_pgs;
3137 } while (freecnt < free_pgs[0]);
3138 mdb_midl_sort(free_pgs);
3139 memcpy(data.mv_data, free_pgs, data.mv_size);
3142 unsigned int i = free_pgs[0];
3143 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
3144 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3146 DPRINTF(("IDL %"Z"u", free_pgs[i]));
3152 mop = env->me_pghead;
3153 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3155 /* Reserve records for me_pghead[]. Split it if multi-page,
3156 * to avoid searching freeDB for a page range. Use keys in
3157 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3159 if (total_room >= mop_len) {
3160 if (total_room == mop_len || --more < 0)
3162 } else if (head_room >= maxfree_1pg && head_id > 1) {
3163 /* Keep current record (overflow page), add a new one */
3167 /* (Re)write {key = head_id, IDL length = head_room} */
3168 total_room -= head_room;
3169 head_room = mop_len - total_room;
3170 if (head_room > maxfree_1pg && head_id > 1) {
3171 /* Overflow multi-page for part of me_pghead */
3172 head_room /= head_id; /* amortize page sizes */
3173 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3174 } else if (head_room < 0) {
3175 /* Rare case, not bothering to delete this record */
3178 key.mv_size = sizeof(head_id);
3179 key.mv_data = &head_id;
3180 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3181 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3184 /* IDL is initially empty, zero out at least the length */
3185 pgs = (pgno_t *)data.mv_data;
3186 j = head_room > clean_limit ? head_room : 0;
3190 total_room += head_room;
3193 /* Return loose page numbers to me_pghead, though usually none are
3194 * left at this point. The pages themselves remain in dirty_list.
3196 if (txn->mt_loose_pgs) {
3197 MDB_page *mp = txn->mt_loose_pgs;
3198 unsigned count = txn->mt_loose_count;
3200 /* Room for loose pages + temp IDL with same */
3201 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3203 mop = env->me_pghead;
3204 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3205 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3206 loose[ ++count ] = mp->mp_pgno;
3208 mdb_midl_sort(loose);
3209 mdb_midl_xmerge(mop, loose);
3210 txn->mt_loose_pgs = NULL;
3211 txn->mt_loose_count = 0;
3215 /* Fill in the reserved me_pghead records */
3221 rc = mdb_cursor_first(&mc, &key, &data);
3222 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3223 txnid_t id = *(txnid_t *)key.mv_data;
3224 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3227 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3229 if (len > mop_len) {
3231 data.mv_size = (len + 1) * sizeof(MDB_ID);
3233 data.mv_data = mop -= len;
3236 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3238 if (rc || !(mop_len -= len))
3245 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3246 * @param[in] txn the transaction that's being committed
3247 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3248 * @return 0 on success, non-zero on failure.
3251 mdb_page_flush(MDB_txn *txn, int keep)
3253 MDB_env *env = txn->mt_env;
3254 MDB_ID2L dl = txn->mt_u.dirty_list;
3255 unsigned psize = env->me_psize, j;
3256 int i, pagecount = dl[0].mid, rc;
3257 size_t size = 0, pos = 0;
3259 MDB_page *dp = NULL;
3263 struct iovec iov[MDB_COMMIT_PAGES];
3264 ssize_t wpos = 0, wsize = 0, wres;
3265 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3271 if (env->me_flags & MDB_WRITEMAP) {
3272 /* Clear dirty flags */
3273 while (++i <= pagecount) {
3275 /* Don't flush this page yet */
3276 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3277 dp->mp_flags &= ~P_KEEP;
3281 dp->mp_flags &= ~P_DIRTY;
3286 /* Write the pages */
3288 if (++i <= pagecount) {
3290 /* Don't flush this page yet */
3291 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3292 dp->mp_flags &= ~P_KEEP;
3297 /* clear dirty flag */
3298 dp->mp_flags &= ~P_DIRTY;
3301 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3306 /* Windows actually supports scatter/gather I/O, but only on
3307 * unbuffered file handles. Since we're relying on the OS page
3308 * cache for all our data, that's self-defeating. So we just
3309 * write pages one at a time. We use the ov structure to set
3310 * the write offset, to at least save the overhead of a Seek
3313 DPRINTF(("committing page %"Z"u", pgno));
3314 memset(&ov, 0, sizeof(ov));
3315 ov.Offset = pos & 0xffffffff;
3316 ov.OffsetHigh = pos >> 16 >> 16;
3317 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3319 DPRINTF(("WriteFile: %d", rc));
3323 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3324 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3327 /* Write previous page(s) */
3328 #ifdef MDB_USE_PWRITEV
3329 wres = pwritev(env->me_fd, iov, n, wpos);
3332 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3335 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3339 DPRINTF(("lseek: %s", strerror(rc)));
3342 wres = writev(env->me_fd, iov, n);
3345 if (wres != wsize) {
3350 DPRINTF(("Write error: %s", strerror(rc)));
3352 rc = EIO; /* TODO: Use which error code? */
3353 DPUTS("short write, filesystem full?");
3364 DPRINTF(("committing page %"Z"u", pgno));
3365 next_pos = pos + size;
3366 iov[n].iov_len = size;
3367 iov[n].iov_base = (char *)dp;
3373 /* MIPS has cache coherency issues, this is a no-op everywhere else
3374 * Note: for any size >= on-chip cache size, entire on-chip cache is
3377 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3379 for (i = keep; ++i <= pagecount; ) {
3381 /* This is a page we skipped above */
3384 dl[j].mid = dp->mp_pgno;
3387 mdb_dpage_free(env, dp);
3392 txn->mt_dirty_room += i - j;
3398 mdb_txn_commit(MDB_txn *txn)
3401 unsigned int i, end_mode;
3407 /* mdb_txn_end() mode for a commit which writes nothing */
3408 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3410 if (txn->mt_child) {
3411 rc = mdb_txn_commit(txn->mt_child);
3418 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3422 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3423 DPUTS("txn has failed/finished, can't commit");
3425 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3430 if (txn->mt_parent) {
3431 MDB_txn *parent = txn->mt_parent;
3435 unsigned x, y, len, ps_len;
3437 /* Append our free list to parent's */
3438 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3441 mdb_midl_free(txn->mt_free_pgs);
3442 /* Failures after this must either undo the changes
3443 * to the parent or set MDB_TXN_ERROR in the parent.
3446 parent->mt_next_pgno = txn->mt_next_pgno;
3447 parent->mt_flags = txn->mt_flags;
3449 /* Merge our cursors into parent's and close them */
3450 mdb_cursors_close(txn, 1);
3452 /* Update parent's DB table. */
3453 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3454 parent->mt_numdbs = txn->mt_numdbs;
3455 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3456 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3457 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3458 /* preserve parent's DB_NEW status */
3459 x = parent->mt_dbflags[i] & DB_NEW;
3460 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3463 dst = parent->mt_u.dirty_list;
3464 src = txn->mt_u.dirty_list;
3465 /* Remove anything in our dirty list from parent's spill list */
3466 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3468 pspill[0] = (pgno_t)-1;
3469 /* Mark our dirty pages as deleted in parent spill list */
3470 for (i=0, len=src[0].mid; ++i <= len; ) {
3471 MDB_ID pn = src[i].mid << 1;
3472 while (pn > pspill[x])
3474 if (pn == pspill[x]) {
3479 /* Squash deleted pagenums if we deleted any */
3480 for (x=y; ++x <= ps_len; )
3481 if (!(pspill[x] & 1))
3482 pspill[++y] = pspill[x];
3486 /* Remove anything in our spill list from parent's dirty list */
3487 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3488 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3489 MDB_ID pn = txn->mt_spill_pgs[i];
3491 continue; /* deleted spillpg */
3493 y = mdb_mid2l_search(dst, pn);
3494 if (y <= dst[0].mid && dst[y].mid == pn) {
3496 while (y < dst[0].mid) {
3505 /* Find len = length of merging our dirty list with parent's */
3507 dst[0].mid = 0; /* simplify loops */
3508 if (parent->mt_parent) {
3509 len = x + src[0].mid;
3510 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3511 for (i = x; y && i; y--) {
3512 pgno_t yp = src[y].mid;
3513 while (yp < dst[i].mid)
3515 if (yp == dst[i].mid) {
3520 } else { /* Simplify the above for single-ancestor case */
3521 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3523 /* Merge our dirty list with parent's */
3525 for (i = len; y; dst[i--] = src[y--]) {
3526 pgno_t yp = src[y].mid;
3527 while (yp < dst[x].mid)
3528 dst[i--] = dst[x--];
3529 if (yp == dst[x].mid)
3530 free(dst[x--].mptr);
3532 mdb_tassert(txn, i == x);
3534 free(txn->mt_u.dirty_list);
3535 parent->mt_dirty_room = txn->mt_dirty_room;
3536 if (txn->mt_spill_pgs) {
3537 if (parent->mt_spill_pgs) {
3538 /* TODO: Prevent failure here, so parent does not fail */
3539 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3541 parent->mt_flags |= MDB_TXN_ERROR;
3542 mdb_midl_free(txn->mt_spill_pgs);
3543 mdb_midl_sort(parent->mt_spill_pgs);
3545 parent->mt_spill_pgs = txn->mt_spill_pgs;
3549 /* Append our loose page list to parent's */
3550 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3552 *lp = txn->mt_loose_pgs;
3553 parent->mt_loose_count += txn->mt_loose_count;
3555 parent->mt_child = NULL;
3556 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3561 if (txn != env->me_txn) {
3562 DPUTS("attempt to commit unknown transaction");
3567 mdb_cursors_close(txn, 0);
3569 if (!txn->mt_u.dirty_list[0].mid &&
3570 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3573 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3574 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3576 /* Update DB root pointers */
3577 if (txn->mt_numdbs > CORE_DBS) {
3581 data.mv_size = sizeof(MDB_db);
3583 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3584 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3585 if (txn->mt_dbflags[i] & DB_DIRTY) {
3586 if (TXN_DBI_CHANGED(txn, i)) {
3590 data.mv_data = &txn->mt_dbs[i];
3591 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3599 rc = mdb_freelist_save(txn);
3603 mdb_midl_free(env->me_pghead);
3604 env->me_pghead = NULL;
3605 mdb_midl_shrink(&txn->mt_free_pgs);
3611 if ((rc = mdb_page_flush(txn, 0)) ||
3612 (rc = mdb_env_sync(env, 0)) ||
3613 (rc = mdb_env_write_meta(txn)))
3615 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3618 mdb_txn_end(txn, end_mode);
3626 /** Read the environment parameters of a DB environment before
3627 * mapping it into memory.
3628 * @param[in] env the environment handle
3629 * @param[out] meta address of where to store the meta information
3630 * @return 0 on success, non-zero on failure.
3633 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3639 enum { Size = sizeof(pbuf) };
3641 /* We don't know the page size yet, so use a minimum value.
3642 * Read both meta pages so we can use the latest one.
3645 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3649 memset(&ov, 0, sizeof(ov));
3651 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3652 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3655 rc = pread(env->me_fd, &pbuf, Size, off);
3658 if (rc == 0 && off == 0)
3660 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3661 DPRINTF(("read: %s", mdb_strerror(rc)));
3665 p = (MDB_page *)&pbuf;
3667 if (!F_ISSET(p->mp_flags, P_META)) {
3668 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3673 if (m->mm_magic != MDB_MAGIC) {
3674 DPUTS("meta has invalid magic");
3678 if (m->mm_version != MDB_DATA_VERSION) {
3679 DPRINTF(("database is version %u, expected version %u",
3680 m->mm_version, MDB_DATA_VERSION));
3681 return MDB_VERSION_MISMATCH;
3684 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3690 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3692 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3694 meta->mm_magic = MDB_MAGIC;
3695 meta->mm_version = MDB_DATA_VERSION;
3696 meta->mm_mapsize = env->me_mapsize;
3697 meta->mm_psize = env->me_psize;
3698 meta->mm_last_pg = NUM_METAS-1;
3699 meta->mm_flags = env->me_flags & 0xffff;
3700 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3701 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3702 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3705 /** Write the environment parameters of a freshly created DB environment.
3706 * @param[in] env the environment handle
3707 * @param[in] meta the #MDB_meta to write
3708 * @return 0 on success, non-zero on failure.
3711 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3719 memset(&ov, 0, sizeof(ov));
3720 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3722 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3725 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3726 len = pwrite(fd, ptr, size, pos); \
3727 if (len == -1 && ErrCode() == EINTR) continue; \
3728 rc = (len >= 0); break; } while(1)
3731 DPUTS("writing new meta page");
3733 psize = env->me_psize;
3735 p = calloc(NUM_METAS, psize);
3740 p->mp_flags = P_META;
3741 *(MDB_meta *)METADATA(p) = *meta;
3743 q = (MDB_page *)((char *)p + psize);
3745 q->mp_flags = P_META;
3746 *(MDB_meta *)METADATA(q) = *meta;
3748 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
3751 else if ((unsigned) len == psize * NUM_METAS)
3759 /** Update the environment info to commit a transaction.
3760 * @param[in] txn the transaction that's being committed
3761 * @return 0 on success, non-zero on failure.
3764 mdb_env_write_meta(MDB_txn *txn)
3767 MDB_meta meta, metab, *mp;
3771 int rc, len, toggle;
3780 toggle = txn->mt_txnid & 1;
3781 DPRINTF(("writing meta page %d for root page %"Z"u",
3782 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3785 flags = env->me_flags;
3786 mp = env->me_metas[toggle];
3787 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3788 /* Persist any increases of mapsize config */
3789 if (mapsize < env->me_mapsize)
3790 mapsize = env->me_mapsize;
3792 if (flags & MDB_WRITEMAP) {
3793 mp->mm_mapsize = mapsize;
3794 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3795 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3796 mp->mm_last_pg = txn->mt_next_pgno - 1;
3797 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
3798 !(defined(__i386__) || defined(__x86_64__))
3799 /* LY: issue a memory barrier, if not x86. ITS#7969 */
3800 __sync_synchronize();
3802 mp->mm_txnid = txn->mt_txnid;
3803 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3804 unsigned meta_size = env->me_psize;
3805 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3806 ptr = (char *)mp - PAGEHDRSZ;
3807 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3808 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
3812 if (MDB_MSYNC(ptr, meta_size, rc)) {
3819 metab.mm_txnid = mp->mm_txnid;
3820 metab.mm_last_pg = mp->mm_last_pg;
3822 meta.mm_mapsize = mapsize;
3823 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3824 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3825 meta.mm_last_pg = txn->mt_next_pgno - 1;
3826 meta.mm_txnid = txn->mt_txnid;
3828 off = offsetof(MDB_meta, mm_mapsize);
3829 ptr = (char *)&meta + off;
3830 len = sizeof(MDB_meta) - off;
3831 off += (char *)mp - env->me_map;
3833 /* Write to the SYNC fd unless MDB_NOSYNC/MDB_NOMETASYNC.
3834 * (me_mfd goes to the same file as me_fd, but writing to it
3835 * also syncs to disk. Avoids a separate fdatasync() call.)
3837 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
3840 memset(&ov, 0, sizeof(ov));
3842 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3847 rc = pwrite(mfd, ptr, len, off);
3850 rc = rc < 0 ? ErrCode() : EIO;
3855 DPUTS("write failed, disk error?");
3856 /* On a failure, the pagecache still contains the new data.
3857 * Write some old data back, to prevent it from being used.
3858 * Use the non-SYNC fd; we know it will fail anyway.
3860 meta.mm_last_pg = metab.mm_last_pg;
3861 meta.mm_txnid = metab.mm_txnid;
3863 memset(&ov, 0, sizeof(ov));
3865 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3867 r2 = pwrite(env->me_fd, ptr, len, off);
3868 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3871 env->me_flags |= MDB_FATAL_ERROR;
3874 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3875 CACHEFLUSH(env->me_map + off, len, DCACHE);
3877 /* Memory ordering issues are irrelevant; since the entire writer
3878 * is wrapped by wmutex, all of these changes will become visible
3879 * after the wmutex is unlocked. Since the DB is multi-version,
3880 * readers will get consistent data regardless of how fresh or
3881 * how stale their view of these values is.
3884 env->me_txns->mti_txnid = txn->mt_txnid;
3889 /** Check both meta pages to see which one is newer.
3890 * @param[in] env the environment handle
3891 * @return newest #MDB_meta.
3894 mdb_env_pick_meta(const MDB_env *env)
3896 MDB_meta *const *metas = env->me_metas;
3897 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
3901 mdb_env_create(MDB_env **env)
3905 e = calloc(1, sizeof(MDB_env));
3909 e->me_maxreaders = DEFAULT_READERS;
3910 e->me_maxdbs = e->me_numdbs = CORE_DBS;
3911 e->me_fd = INVALID_HANDLE_VALUE;
3912 e->me_lfd = INVALID_HANDLE_VALUE;
3913 e->me_mfd = INVALID_HANDLE_VALUE;
3914 #ifdef MDB_USE_POSIX_SEM
3915 e->me_rmutex = SEM_FAILED;
3916 e->me_wmutex = SEM_FAILED;
3918 e->me_pid = getpid();
3919 GET_PAGESIZE(e->me_os_psize);
3920 VGMEMP_CREATE(e,0,0);
3926 mdb_env_map(MDB_env *env, void *addr)
3929 unsigned int flags = env->me_flags;
3933 LONG sizelo, sizehi;
3936 if (flags & MDB_RDONLY) {
3937 /* Don't set explicit map size, use whatever exists */
3942 msize = env->me_mapsize;
3943 sizelo = msize & 0xffffffff;
3944 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3946 /* Windows won't create mappings for zero length files.
3947 * and won't map more than the file size.
3948 * Just set the maxsize right now.
3950 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3951 || !SetEndOfFile(env->me_fd)
3952 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3956 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3957 PAGE_READWRITE : PAGE_READONLY,
3958 sizehi, sizelo, NULL);
3961 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3962 FILE_MAP_WRITE : FILE_MAP_READ,
3964 rc = env->me_map ? 0 : ErrCode();
3969 int prot = PROT_READ;
3970 if (flags & MDB_WRITEMAP) {
3972 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3975 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3977 if (env->me_map == MAP_FAILED) {
3982 if (flags & MDB_NORDAHEAD) {
3983 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3985 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3987 #ifdef POSIX_MADV_RANDOM
3988 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3989 #endif /* POSIX_MADV_RANDOM */
3990 #endif /* MADV_RANDOM */
3994 /* Can happen because the address argument to mmap() is just a
3995 * hint. mmap() can pick another, e.g. if the range is in use.
3996 * The MAP_FIXED flag would prevent that, but then mmap could
3997 * instead unmap existing pages to make room for the new map.
3999 if (addr && env->me_map != addr)
4000 return EBUSY; /* TODO: Make a new MDB_* error code? */
4002 p = (MDB_page *)env->me_map;
4003 env->me_metas[0] = METADATA(p);
4004 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
4010 mdb_env_set_mapsize(MDB_env *env, size_t size)
4012 /* If env is already open, caller is responsible for making
4013 * sure there are no active txns.
4021 meta = mdb_env_pick_meta(env);
4023 size = meta->mm_mapsize;
4025 /* Silently round up to minimum if the size is too small */
4026 size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
4030 munmap(env->me_map, env->me_mapsize);
4031 env->me_mapsize = size;
4032 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4033 rc = mdb_env_map(env, old);
4037 env->me_mapsize = size;
4039 env->me_maxpg = env->me_mapsize / env->me_psize;
4044 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4048 env->me_maxdbs = dbs + CORE_DBS;
4053 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4055 if (env->me_map || readers < 1)
4057 env->me_maxreaders = readers;
4062 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4064 if (!env || !readers)
4066 *readers = env->me_maxreaders;
4071 mdb_fsize(HANDLE fd, size_t *size)
4074 LARGE_INTEGER fsize;
4076 if (!GetFileSizeEx(fd, &fsize))
4079 *size = fsize.QuadPart;
4093 typedef wchar_t mdb_nchar_t;
4094 # define MDB_NAME(str) L##str
4095 # define mdb_name_cpy wcscpy
4097 /** Character type for file names: char on Unix, wchar_t on Windows */
4098 typedef char mdb_nchar_t;
4099 # define MDB_NAME(str) str /**< #mdb_nchar_t[] string literal */
4100 # define mdb_name_cpy strcpy /**< Copy name (#mdb_nchar_t string) */
4103 /** Filename - string of #mdb_nchar_t[] */
4104 typedef struct MDB_name {
4105 int mn_len; /**< Length */
4106 int mn_alloced; /**< True if #mn_val was malloced */
4107 mdb_nchar_t *mn_val; /**< Contents */
4110 /** Filename suffixes [datafile,lockfile][without,with MDB_NOSUBDIR] */
4111 static const mdb_nchar_t *const mdb_suffixes[2][2] = {
4112 { MDB_NAME("/data.mdb"), MDB_NAME("") },
4113 { MDB_NAME("/lock.mdb"), MDB_NAME("-lock") }
4116 #define MDB_SUFFLEN 9 /**< Max string length in #mdb_suffixes[] */
4118 /** Set up filename + scratch area for filename suffix, for opening files.
4119 * It should be freed with #mdb_fname_destroy().
4120 * On Windows, paths are converted from char *UTF-8 to wchar_t *UTF-16.
4122 * @param[in] path Pathname for #mdb_env_open().
4123 * @param[in] envflags Whether a subdir and/or lockfile will be used.
4124 * @param[out] fname Resulting filename, with room for a suffix if necessary.
4127 mdb_fname_init(const char *path, unsigned envflags, MDB_name *fname)
4129 int no_suffix = F_ISSET(envflags, MDB_NOSUBDIR|MDB_NOLOCK);
4130 fname->mn_alloced = 0;
4132 return utf8_to_utf16(path, fname, no_suffix ? 0 : MDB_SUFFLEN);
4134 fname->mn_len = strlen(path);
4136 fname->mn_val = (char *) path;
4137 else if ((fname->mn_val = malloc(fname->mn_len + MDB_SUFFLEN+1)) != NULL) {
4138 fname->mn_alloced = 1;
4139 strcpy(fname->mn_val, path);
4147 /** Destroy \b fname from #mdb_fname_init() */
4148 #define mdb_fname_destroy(fname) \
4149 do { if ((fname).mn_alloced) free((fname).mn_val); } while (0)
4151 #ifdef O_CLOEXEC /* POSIX.1-2008: Set FD_CLOEXEC atomically at open() */
4152 # define MDB_CLOEXEC O_CLOEXEC
4154 # define MDB_CLOEXEC 0
4157 /** File type, access mode etc. for #mdb_fopen() */
4158 enum mdb_fopen_type {
4160 MDB_O_RDONLY, MDB_O_RDWR, MDB_O_META, MDB_O_COPY, MDB_O_LOCKS
4162 /* A comment in mdb_fopen() explains some O_* flag choices. */
4163 MDB_O_RDONLY= O_RDONLY, /**< for RDONLY me_fd */
4164 MDB_O_RDWR = O_RDWR |O_CREAT, /**< for me_fd */
4165 MDB_O_META = O_WRONLY|MDB_DSYNC |MDB_CLOEXEC, /**< for me_mfd */
4166 MDB_O_COPY = O_WRONLY|O_CREAT|O_EXCL|MDB_CLOEXEC, /**< for #mdb_env_copy() */
4167 /** Bitmask for open() flags in enum #mdb_fopen_type. The other bits
4168 * distinguish otherwise-equal MDB_O_* constants from each other.
4170 MDB_O_MASK = MDB_O_RDWR|MDB_CLOEXEC | MDB_O_RDONLY|MDB_O_META|MDB_O_COPY,
4171 MDB_O_LOCKS = MDB_O_RDWR|MDB_CLOEXEC | ((MDB_O_MASK+1) & ~MDB_O_MASK) /**< for me_lfd */
4175 /** Open an LMDB file.
4176 * @param[in] env The LMDB environment.
4177 * @param[in,out] fname Path from from #mdb_fname_init(). A suffix is
4178 * appended if necessary to create the filename, without changing mn_len.
4179 * @param[in] which Determines file type, access mode, etc.
4180 * @param[in] mode The Unix permissions for the file, if we create it.
4181 * @param[out] res Resulting file handle.
4182 * @return 0 on success, non-zero on failure.
4185 mdb_fopen(const MDB_env *env, MDB_name *fname,
4186 enum mdb_fopen_type which, mdb_mode_t mode,
4189 int rc = MDB_SUCCESS;
4192 DWORD acc, share, disp, attrs;
4197 if (fname->mn_alloced) /* modifiable copy */
4198 mdb_name_cpy(fname->mn_val + fname->mn_len,
4199 mdb_suffixes[which==MDB_O_LOCKS][F_ISSET(env->me_flags, MDB_NOSUBDIR)]);
4201 /* The directory must already exist. Usually the file need not.
4202 * MDB_O_META requires the file because we already created it using
4203 * MDB_O_RDWR. MDB_O_COPY must not overwrite an existing file.
4205 * With MDB_O_COPY we do not want the OS to cache the writes, since
4206 * the source data is already in the OS cache.
4208 * The lockfile needs FD_CLOEXEC (close file descriptor on exec*())
4209 * to avoid the flock() issues noted under Caveats in lmdb.h.
4210 * Also set it for other filehandles which the user cannot get at
4211 * and close himself, which he may need after fork(). I.e. all but
4212 * me_fd, which programs do use via mdb_env_get_fd().
4216 acc = GENERIC_READ|GENERIC_WRITE;
4217 share = FILE_SHARE_READ|FILE_SHARE_WRITE;
4219 attrs = FILE_ATTRIBUTE_NORMAL;
4221 case MDB_O_RDONLY: /* read-only datafile */
4223 disp = OPEN_EXISTING;
4225 case MDB_O_META: /* for writing metapages */
4226 acc = GENERIC_WRITE;
4227 disp = OPEN_EXISTING;
4228 attrs = FILE_ATTRIBUTE_NORMAL|FILE_FLAG_WRITE_THROUGH;
4230 case MDB_O_COPY: /* mdb_env_copy() & co */
4231 acc = GENERIC_WRITE;
4234 attrs = FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH;
4236 default: break; /* silence gcc -Wswitch (not all enum values handled) */
4238 fd = CreateFileW(fname->mn_val, acc, share, NULL, disp, attrs, NULL);
4240 fd = open(fname->mn_val, which & MDB_O_MASK, mode);
4243 if (fd == INVALID_HANDLE_VALUE)
4247 if (which != MDB_O_RDONLY && which != MDB_O_RDWR) {
4248 /* Set CLOEXEC if we could not pass it to open() */
4249 if (!MDB_CLOEXEC && (flags = fcntl(fd, F_GETFD)) != -1)
4250 (void) fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
4252 if (which == MDB_O_COPY && env->me_psize >= env->me_os_psize) {
4253 /* This may require buffer alignment. There is no portable
4254 * way to ask how much, so we require OS pagesize alignment.
4256 # ifdef F_NOCACHE /* __APPLE__ */
4257 (void) fcntl(fd, F_NOCACHE, 1);
4258 # elif defined O_DIRECT
4259 /* open(...O_DIRECT...) would break on filesystems without
4260 * O_DIRECT support (ITS#7682). Try to set it here instead.
4262 if ((flags = fcntl(fd, F_GETFL)) != -1)
4263 (void) fcntl(fd, F_SETFL, flags | O_DIRECT);
4267 #endif /* !_WIN32 */
4274 #ifdef BROKEN_FDATASYNC
4275 #include <sys/utsname.h>
4276 #include <sys/vfs.h>
4279 /** Further setup required for opening an LMDB environment
4282 mdb_env_open2(MDB_env *env)
4284 unsigned int flags = env->me_flags;
4285 int i, newenv = 0, rc;
4289 /* See if we should use QueryLimited */
4291 if ((rc & 0xff) > 5)
4292 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4294 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4297 #ifdef BROKEN_FDATASYNC
4298 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4299 * https://lkml.org/lkml/2012/9/3/83
4300 * Kernels after 3.6-rc6 are known good.
4301 * https://lkml.org/lkml/2012/9/10/556
4302 * See if the DB is on ext3/ext4, then check for new enough kernel
4303 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4308 fstatfs(env->me_fd, &st);
4309 while (st.f_type == 0xEF53) {
4313 if (uts.release[0] < '3') {
4314 if (!strncmp(uts.release, "2.6.32.", 7)) {
4315 i = atoi(uts.release+7);
4317 break; /* 2.6.32.60 and newer is OK */
4318 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4319 i = atoi(uts.release+7);
4321 break; /* 2.6.34.15 and newer is OK */
4323 } else if (uts.release[0] == '3') {
4324 i = atoi(uts.release+2);
4326 break; /* 3.6 and newer is OK */
4328 i = atoi(uts.release+4);
4330 break; /* 3.5.4 and newer is OK */
4331 } else if (i == 2) {
4332 i = atoi(uts.release+4);
4334 break; /* 3.2.30 and newer is OK */
4336 } else { /* 4.x and newer is OK */
4339 env->me_flags |= MDB_FSYNCONLY;
4345 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4348 DPUTS("new mdbenv");
4350 env->me_psize = env->me_os_psize;
4351 if (env->me_psize > MAX_PAGESIZE)
4352 env->me_psize = MAX_PAGESIZE;
4353 memset(&meta, 0, sizeof(meta));
4354 mdb_env_init_meta0(env, &meta);
4355 meta.mm_mapsize = DEFAULT_MAPSIZE;
4357 env->me_psize = meta.mm_psize;
4360 /* Was a mapsize configured? */
4361 if (!env->me_mapsize) {
4362 env->me_mapsize = meta.mm_mapsize;
4365 /* Make sure mapsize >= committed data size. Even when using
4366 * mm_mapsize, which could be broken in old files (ITS#7789).
4368 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4369 if (env->me_mapsize < minsize)
4370 env->me_mapsize = minsize;
4372 meta.mm_mapsize = env->me_mapsize;
4374 if (newenv && !(flags & MDB_FIXEDMAP)) {
4375 /* mdb_env_map() may grow the datafile. Write the metapages
4376 * first, so the file will be valid if initialization fails.
4377 * Except with FIXEDMAP, since we do not yet know mm_address.
4378 * We could fill in mm_address later, but then a different
4379 * program might end up doing that - one with a memory layout
4380 * and map address which does not suit the main program.
4382 rc = mdb_env_init_meta(env, &meta);
4388 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4393 if (flags & MDB_FIXEDMAP)
4394 meta.mm_address = env->me_map;
4395 i = mdb_env_init_meta(env, &meta);
4396 if (i != MDB_SUCCESS) {
4401 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4402 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4404 #if !(MDB_MAXKEYSIZE)
4405 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4407 env->me_maxpg = env->me_mapsize / env->me_psize;
4411 MDB_meta *meta = mdb_env_pick_meta(env);
4412 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4414 DPRINTF(("opened database version %u, pagesize %u",
4415 meta->mm_version, env->me_psize));
4416 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4417 DPRINTF(("depth: %u", db->md_depth));
4418 DPRINTF(("entries: %"Z"u", db->md_entries));
4419 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
4420 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
4421 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
4422 DPRINTF(("root: %"Z"u", db->md_root));
4430 /** Release a reader thread's slot in the reader lock table.
4431 * This function is called automatically when a thread exits.
4432 * @param[in] ptr This points to the slot in the reader lock table.
4435 mdb_env_reader_dest(void *ptr)
4437 MDB_reader *reader = ptr;
4440 if (reader->mr_pid == getpid()) /* catch pthread_exit() in child process */
4442 /* We omit the mutex, so do this atomically (i.e. skip mr_txnid) */
4447 /** Junk for arranging thread-specific callbacks on Windows. This is
4448 * necessarily platform and compiler-specific. Windows supports up
4449 * to 1088 keys. Let's assume nobody opens more than 64 environments
4450 * in a single process, for now. They can override this if needed.
4452 #ifndef MAX_TLS_KEYS
4453 #define MAX_TLS_KEYS 64
4455 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4456 static int mdb_tls_nkeys;
4458 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4462 case DLL_PROCESS_ATTACH: break;
4463 case DLL_THREAD_ATTACH: break;
4464 case DLL_THREAD_DETACH:
4465 for (i=0; i<mdb_tls_nkeys; i++) {
4466 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4468 mdb_env_reader_dest(r);
4472 case DLL_PROCESS_DETACH: break;
4477 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4479 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4483 /* Force some symbol references.
4484 * _tls_used forces the linker to create the TLS directory if not already done
4485 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4487 #pragma comment(linker, "/INCLUDE:_tls_used")
4488 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4489 #pragma const_seg(".CRT$XLB")
4490 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4491 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4494 #pragma comment(linker, "/INCLUDE:__tls_used")
4495 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4496 #pragma data_seg(".CRT$XLB")
4497 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4499 #endif /* WIN 32/64 */
4500 #endif /* !__GNUC__ */
4503 /** Downgrade the exclusive lock on the region back to shared */
4505 mdb_env_share_locks(MDB_env *env, int *excl)
4508 MDB_meta *meta = mdb_env_pick_meta(env);
4510 env->me_txns->mti_txnid = meta->mm_txnid;
4515 /* First acquire a shared lock. The Unlock will
4516 * then release the existing exclusive lock.
4518 memset(&ov, 0, sizeof(ov));
4519 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4522 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4528 struct flock lock_info;
4529 /* The shared lock replaces the existing lock */
4530 memset((void *)&lock_info, 0, sizeof(lock_info));
4531 lock_info.l_type = F_RDLCK;
4532 lock_info.l_whence = SEEK_SET;
4533 lock_info.l_start = 0;
4534 lock_info.l_len = 1;
4535 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4536 (rc = ErrCode()) == EINTR) ;
4537 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4544 /** Try to get exclusive lock, otherwise shared.
4545 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4548 mdb_env_excl_lock(MDB_env *env, int *excl)
4552 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4556 memset(&ov, 0, sizeof(ov));
4557 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4564 struct flock lock_info;
4565 memset((void *)&lock_info, 0, sizeof(lock_info));
4566 lock_info.l_type = F_WRLCK;
4567 lock_info.l_whence = SEEK_SET;
4568 lock_info.l_start = 0;
4569 lock_info.l_len = 1;
4570 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4571 (rc = ErrCode()) == EINTR) ;
4575 # ifndef MDB_USE_POSIX_MUTEX
4576 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4579 lock_info.l_type = F_RDLCK;
4580 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4581 (rc = ErrCode()) == EINTR) ;
4591 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4593 * @(#) $Revision: 5.1 $
4594 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4595 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4597 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4601 * Please do not copyright this code. This code is in the public domain.
4603 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4604 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4605 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4606 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4607 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4608 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4609 * PERFORMANCE OF THIS SOFTWARE.
4612 * chongo <Landon Curt Noll> /\oo/\
4613 * http://www.isthe.com/chongo/
4615 * Share and Enjoy! :-)
4618 typedef unsigned long long mdb_hash_t;
4619 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4621 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4622 * @param[in] val value to hash
4623 * @param[in] hval initial value for hash
4624 * @return 64 bit hash
4626 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4627 * hval arg on the first call.
4630 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4632 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4633 unsigned char *end = s + val->mv_size;
4635 * FNV-1a hash each octet of the string
4638 /* xor the bottom with the current octet */
4639 hval ^= (mdb_hash_t)*s++;
4641 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4642 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4643 (hval << 7) + (hval << 8) + (hval << 40);
4645 /* return our new hash value */
4649 /** Hash the string and output the encoded hash.
4650 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4651 * very short name limits. We don't care about the encoding being reversible,
4652 * we just want to preserve as many bits of the input as possible in a
4653 * small printable string.
4654 * @param[in] str string to hash
4655 * @param[out] encbuf an array of 11 chars to hold the hash
4657 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4660 mdb_pack85(unsigned long l, char *out)
4664 for (i=0; i<5; i++) {
4665 *out++ = mdb_a85[l % 85];
4671 mdb_hash_enc(MDB_val *val, char *encbuf)
4673 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4675 mdb_pack85(h, encbuf);
4676 mdb_pack85(h>>32, encbuf+5);
4681 /** Open and/or initialize the lock region for the environment.
4682 * @param[in] env The LMDB environment.
4683 * @param[in] fname Filename + scratch area, from #mdb_fname_init().
4684 * @param[in] mode The Unix permissions for the file, if we create it.
4685 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4686 * @return 0 on success, non-zero on failure.
4689 mdb_env_setup_locks(MDB_env *env, MDB_name *fname, int mode, int *excl)
4692 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4694 # define MDB_ERRCODE_ROFS EROFS
4699 rc = mdb_fopen(env, fname, MDB_O_LOCKS, mode, &env->me_lfd);
4701 /* Omit lockfile if read-only env on read-only filesystem */
4702 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4708 if (!(env->me_flags & MDB_NOTLS)) {
4709 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4712 env->me_flags |= MDB_ENV_TXKEY;
4714 /* Windows TLS callbacks need help finding their TLS info. */
4715 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4719 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4723 /* Try to get exclusive lock. If we succeed, then
4724 * nobody is using the lock region and we should initialize it.
4726 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4729 size = GetFileSize(env->me_lfd, NULL);
4731 size = lseek(env->me_lfd, 0, SEEK_END);
4732 if (size == -1) goto fail_errno;
4734 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4735 if (size < rsize && *excl > 0) {
4737 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4738 || !SetEndOfFile(env->me_lfd))
4741 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4745 size = rsize - sizeof(MDB_txninfo);
4746 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4751 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4753 if (!mh) goto fail_errno;
4754 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4756 if (!env->me_txns) goto fail_errno;
4758 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4760 if (m == MAP_FAILED) goto fail_errno;
4766 BY_HANDLE_FILE_INFORMATION stbuf;
4775 if (!mdb_sec_inited) {
4776 InitializeSecurityDescriptor(&mdb_null_sd,
4777 SECURITY_DESCRIPTOR_REVISION);
4778 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4779 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4780 mdb_all_sa.bInheritHandle = FALSE;
4781 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4784 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4785 idbuf.volume = stbuf.dwVolumeSerialNumber;
4786 idbuf.nhigh = stbuf.nFileIndexHigh;
4787 idbuf.nlow = stbuf.nFileIndexLow;
4788 val.mv_data = &idbuf;
4789 val.mv_size = sizeof(idbuf);
4790 mdb_hash_enc(&val, encbuf);
4791 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4792 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4793 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4794 if (!env->me_rmutex) goto fail_errno;
4795 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4796 if (!env->me_wmutex) goto fail_errno;
4797 #elif defined(MDB_USE_POSIX_SEM)
4806 #if defined(__NetBSD__)
4807 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4809 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4810 idbuf.dev = stbuf.st_dev;
4811 idbuf.ino = stbuf.st_ino;
4812 val.mv_data = &idbuf;
4813 val.mv_size = sizeof(idbuf);
4814 mdb_hash_enc(&val, encbuf);
4815 #ifdef MDB_SHORT_SEMNAMES
4816 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4818 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4819 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4820 /* Clean up after a previous run, if needed: Try to
4821 * remove both semaphores before doing anything else.
4823 sem_unlink(env->me_txns->mti_rmname);
4824 sem_unlink(env->me_txns->mti_wmname);
4825 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4826 O_CREAT|O_EXCL, mode, 1);
4827 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4828 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4829 O_CREAT|O_EXCL, mode, 1);
4830 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4831 #else /* MDB_USE_POSIX_MUTEX: */
4832 pthread_mutexattr_t mattr;
4834 /* Solaris needs this before initing a robust mutex. Otherwise
4835 * it may skip the init and return EBUSY "seems someone already
4836 * inited" or EINVAL "it was inited differently".
4838 memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
4839 memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
4841 if ((rc = pthread_mutexattr_init(&mattr)))
4844 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
4845 #ifdef MDB_ROBUST_SUPPORTED
4846 if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
4848 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
4849 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
4850 pthread_mutexattr_destroy(&mattr);
4853 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4855 env->me_txns->mti_magic = MDB_MAGIC;
4856 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4857 env->me_txns->mti_txnid = 0;
4858 env->me_txns->mti_numreaders = 0;
4861 if (env->me_txns->mti_magic != MDB_MAGIC) {
4862 DPUTS("lock region has invalid magic");
4866 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4867 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4868 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4869 rc = MDB_VERSION_MISMATCH;
4873 if (rc && rc != EACCES && rc != EAGAIN) {
4877 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4878 if (!env->me_rmutex) goto fail_errno;
4879 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4880 if (!env->me_wmutex) goto fail_errno;
4881 #elif defined(MDB_USE_POSIX_SEM)
4882 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4883 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4884 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4885 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4896 /** Only a subset of the @ref mdb_env flags can be changed
4897 * at runtime. Changing other flags requires closing the
4898 * environment and re-opening it with the new flags.
4900 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4901 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
4902 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4904 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4905 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4909 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4914 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4917 flags |= env->me_flags;
4919 rc = mdb_fname_init(path, flags, &fname);
4923 if (flags & MDB_RDONLY) {
4924 /* silently ignore WRITEMAP when we're only getting read access */
4925 flags &= ~MDB_WRITEMAP;
4927 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4928 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4931 env->me_flags = flags |= MDB_ENV_ACTIVE;
4935 env->me_path = strdup(path);
4936 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4937 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4938 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4939 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4943 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
4945 /* For RDONLY, get lockfile after we know datafile exists */
4946 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4947 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
4952 rc = mdb_fopen(env, &fname,
4953 (flags & MDB_RDONLY) ? MDB_O_RDONLY : MDB_O_RDWR,
4958 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4959 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
4964 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4965 if (!(flags & (MDB_RDONLY|MDB_WRITEMAP))) {
4966 /* Synchronous fd for meta writes. Needed even with
4967 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4969 rc = mdb_fopen(env, &fname, MDB_O_META, mode, &env->me_mfd);
4973 DPRINTF(("opened dbenv %p", (void *) env));
4975 rc = mdb_env_share_locks(env, &excl);
4979 if (!(flags & MDB_RDONLY)) {
4981 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
4982 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
4983 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
4984 (txn = calloc(1, size)))
4986 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
4987 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
4988 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
4989 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
4991 txn->mt_dbxs = env->me_dbxs;
4992 txn->mt_flags = MDB_TXN_FINISHED;
5002 mdb_env_close0(env, excl);
5004 mdb_fname_destroy(fname);
5008 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
5010 mdb_env_close0(MDB_env *env, int excl)
5014 if (!(env->me_flags & MDB_ENV_ACTIVE))
5017 /* Doing this here since me_dbxs may not exist during mdb_env_close */
5019 for (i = env->me_maxdbs; --i >= CORE_DBS; )
5020 free(env->me_dbxs[i].md_name.mv_data);
5025 free(env->me_dbiseqs);
5026 free(env->me_dbflags);
5028 free(env->me_dirty_list);
5030 mdb_midl_free(env->me_free_pgs);
5032 if (env->me_flags & MDB_ENV_TXKEY) {
5033 pthread_key_delete(env->me_txkey);
5035 /* Delete our key from the global list */
5036 for (i=0; i<mdb_tls_nkeys; i++)
5037 if (mdb_tls_keys[i] == env->me_txkey) {
5038 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
5046 munmap(env->me_map, env->me_mapsize);
5048 if (env->me_mfd != INVALID_HANDLE_VALUE)
5049 (void) close(env->me_mfd);
5050 if (env->me_fd != INVALID_HANDLE_VALUE)
5051 (void) close(env->me_fd);
5053 MDB_PID_T pid = env->me_pid;
5054 /* Clearing readers is done in this function because
5055 * me_txkey with its destructor must be disabled first.
5057 * We skip the the reader mutex, so we touch only
5058 * data owned by this process (me_close_readers and
5059 * our readers), and clear each reader atomically.
5061 for (i = env->me_close_readers; --i >= 0; )
5062 if (env->me_txns->mti_readers[i].mr_pid == pid)
5063 env->me_txns->mti_readers[i].mr_pid = 0;
5065 if (env->me_rmutex) {
5066 CloseHandle(env->me_rmutex);
5067 if (env->me_wmutex) CloseHandle(env->me_wmutex);
5069 /* Windows automatically destroys the mutexes when
5070 * the last handle closes.
5072 #elif defined(MDB_USE_POSIX_SEM)
5073 if (env->me_rmutex != SEM_FAILED) {
5074 sem_close(env->me_rmutex);
5075 if (env->me_wmutex != SEM_FAILED)
5076 sem_close(env->me_wmutex);
5077 /* If we have the filelock: If we are the
5078 * only remaining user, clean up semaphores.
5081 mdb_env_excl_lock(env, &excl);
5083 sem_unlink(env->me_txns->mti_rmname);
5084 sem_unlink(env->me_txns->mti_wmname);
5088 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
5090 if (env->me_lfd != INVALID_HANDLE_VALUE) {
5093 /* Unlock the lockfile. Windows would have unlocked it
5094 * after closing anyway, but not necessarily at once.
5096 UnlockFile(env->me_lfd, 0, 0, 1, 0);
5099 (void) close(env->me_lfd);
5102 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
5106 mdb_env_close(MDB_env *env)
5113 VGMEMP_DESTROY(env);
5114 while ((dp = env->me_dpages) != NULL) {
5115 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5116 env->me_dpages = dp->mp_next;
5120 mdb_env_close0(env, 0);
5124 /** Compare two items pointing at aligned size_t's */
5126 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5128 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
5129 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
5132 /** Compare two items pointing at aligned unsigned int's.
5134 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5135 * but #mdb_cmp_clong() is called instead if the data type is size_t.
5138 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5140 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5141 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5144 /** Compare two items pointing at unsigned ints of unknown alignment.
5145 * Nodes and keys are guaranteed to be 2-byte aligned.
5148 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5150 #if BYTE_ORDER == LITTLE_ENDIAN
5151 unsigned short *u, *c;
5154 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5155 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5158 } while(!x && u > (unsigned short *)a->mv_data);
5161 unsigned short *u, *c, *end;
5164 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5165 u = (unsigned short *)a->mv_data;
5166 c = (unsigned short *)b->mv_data;
5169 } while(!x && u < end);
5174 /** Compare two items lexically */
5176 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5183 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5189 diff = memcmp(a->mv_data, b->mv_data, len);
5190 return diff ? diff : len_diff<0 ? -1 : len_diff;
5193 /** Compare two items in reverse byte order */
5195 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5197 const unsigned char *p1, *p2, *p1_lim;
5201 p1_lim = (const unsigned char *)a->mv_data;
5202 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5203 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5205 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5211 while (p1 > p1_lim) {
5212 diff = *--p1 - *--p2;
5216 return len_diff<0 ? -1 : len_diff;
5219 /** Search for key within a page, using binary search.
5220 * Returns the smallest entry larger or equal to the key.
5221 * If exactp is non-null, stores whether the found entry was an exact match
5222 * in *exactp (1 or 0).
5223 * Updates the cursor index with the index of the found entry.
5224 * If no entry larger or equal to the key is found, returns NULL.
5227 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5229 unsigned int i = 0, nkeys;
5232 MDB_page *mp = mc->mc_pg[mc->mc_top];
5233 MDB_node *node = NULL;
5238 nkeys = NUMKEYS(mp);
5240 DPRINTF(("searching %u keys in %s %spage %"Z"u",
5241 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5244 low = IS_LEAF(mp) ? 0 : 1;
5246 cmp = mc->mc_dbx->md_cmp;
5248 /* Branch pages have no data, so if using integer keys,
5249 * alignment is guaranteed. Use faster mdb_cmp_int.
5251 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5252 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
5259 nodekey.mv_size = mc->mc_db->md_pad;
5260 node = NODEPTR(mp, 0); /* fake */
5261 while (low <= high) {
5262 i = (low + high) >> 1;
5263 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5264 rc = cmp(key, &nodekey);
5265 DPRINTF(("found leaf index %u [%s], rc = %i",
5266 i, DKEY(&nodekey), rc));
5275 while (low <= high) {
5276 i = (low + high) >> 1;
5278 node = NODEPTR(mp, i);
5279 nodekey.mv_size = NODEKSZ(node);
5280 nodekey.mv_data = NODEKEY(node);
5282 rc = cmp(key, &nodekey);
5285 DPRINTF(("found leaf index %u [%s], rc = %i",
5286 i, DKEY(&nodekey), rc));
5288 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
5289 i, DKEY(&nodekey), NODEPGNO(node), rc));
5300 if (rc > 0) { /* Found entry is less than the key. */
5301 i++; /* Skip to get the smallest entry larger than key. */
5303 node = NODEPTR(mp, i);
5306 *exactp = (rc == 0 && nkeys > 0);
5307 /* store the key index */
5308 mc->mc_ki[mc->mc_top] = i;
5310 /* There is no entry larger or equal to the key. */
5313 /* nodeptr is fake for LEAF2 */
5319 mdb_cursor_adjust(MDB_cursor *mc, func)
5323 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5324 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5331 /** Pop a page off the top of the cursor's stack. */
5333 mdb_cursor_pop(MDB_cursor *mc)
5336 DPRINTF(("popping page %"Z"u off db %d cursor %p",
5337 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5343 mc->mc_flags &= ~C_INITIALIZED;
5348 /** Push a page onto the top of the cursor's stack.
5349 * Set #MDB_TXN_ERROR on failure.
5352 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5354 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
5355 DDBI(mc), (void *) mc));
5357 if (mc->mc_snum >= CURSOR_STACK) {
5358 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5359 return MDB_CURSOR_FULL;
5362 mc->mc_top = mc->mc_snum++;
5363 mc->mc_pg[mc->mc_top] = mp;
5364 mc->mc_ki[mc->mc_top] = 0;
5369 /** Find the address of the page corresponding to a given page number.
5370 * Set #MDB_TXN_ERROR on failure.
5371 * @param[in] mc the cursor accessing the page.
5372 * @param[in] pgno the page number for the page to retrieve.
5373 * @param[out] ret address of a pointer where the page's address will be stored.
5374 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5375 * @return 0 on success, non-zero on failure.
5378 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
5380 MDB_txn *txn = mc->mc_txn;
5381 MDB_env *env = txn->mt_env;
5385 if (! (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_WRITEMAP))) {
5389 MDB_ID2L dl = tx2->mt_u.dirty_list;
5391 /* Spilled pages were dirtied in this txn and flushed
5392 * because the dirty list got full. Bring this page
5393 * back in from the map (but don't unspill it here,
5394 * leave that unless page_touch happens again).
5396 if (tx2->mt_spill_pgs) {
5397 MDB_ID pn = pgno << 1;
5398 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5399 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5400 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5405 unsigned x = mdb_mid2l_search(dl, pgno);
5406 if (x <= dl[0].mid && dl[x].mid == pgno) {
5412 } while ((tx2 = tx2->mt_parent) != NULL);
5415 if (pgno < txn->mt_next_pgno) {
5417 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5419 DPRINTF(("page %"Z"u not found", pgno));
5420 txn->mt_flags |= MDB_TXN_ERROR;
5421 return MDB_PAGE_NOTFOUND;
5431 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
5432 * The cursor is at the root page, set up the rest of it.
5435 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
5437 MDB_page *mp = mc->mc_pg[mc->mc_top];
5441 while (IS_BRANCH(mp)) {
5445 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
5446 /* Don't assert on branch pages in the FreeDB. We can get here
5447 * while in the process of rebalancing a FreeDB branch page; we must
5448 * let that proceed. ITS#8336
5450 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
5451 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
5453 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
5455 if (flags & MDB_PS_LAST)
5456 i = NUMKEYS(mp) - 1;
5459 node = mdb_node_search(mc, key, &exact);
5461 i = NUMKEYS(mp) - 1;
5463 i = mc->mc_ki[mc->mc_top];
5465 mdb_cassert(mc, i > 0);
5469 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
5472 mdb_cassert(mc, i < NUMKEYS(mp));
5473 node = NODEPTR(mp, i);
5475 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
5478 mc->mc_ki[mc->mc_top] = i;
5479 if ((rc = mdb_cursor_push(mc, mp)))
5482 if (flags & MDB_PS_MODIFY) {
5483 if ((rc = mdb_page_touch(mc)) != 0)
5485 mp = mc->mc_pg[mc->mc_top];
5490 DPRINTF(("internal error, index points to a %02X page!?",
5492 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5493 return MDB_CORRUPTED;
5496 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
5497 key ? DKEY(key) : "null"));
5498 mc->mc_flags |= C_INITIALIZED;
5499 mc->mc_flags &= ~C_EOF;
5504 /** Search for the lowest key under the current branch page.
5505 * This just bypasses a NUMKEYS check in the current page
5506 * before calling mdb_page_search_root(), because the callers
5507 * are all in situations where the current page is known to
5511 mdb_page_search_lowest(MDB_cursor *mc)
5513 MDB_page *mp = mc->mc_pg[mc->mc_top];
5514 MDB_node *node = NODEPTR(mp, 0);
5517 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
5520 mc->mc_ki[mc->mc_top] = 0;
5521 if ((rc = mdb_cursor_push(mc, mp)))
5523 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5526 /** Search for the page a given key should be in.
5527 * Push it and its parent pages on the cursor stack.
5528 * @param[in,out] mc the cursor for this operation.
5529 * @param[in] key the key to search for, or NULL for first/last page.
5530 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5531 * are touched (updated with new page numbers).
5532 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5533 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5534 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5535 * @return 0 on success, non-zero on failure.
5538 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5543 /* Make sure the txn is still viable, then find the root from
5544 * the txn's db table and set it as the root of the cursor's stack.
5546 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
5547 DPUTS("transaction may not be used now");
5550 /* Make sure we're using an up-to-date root */
5551 if (*mc->mc_dbflag & DB_STALE) {
5553 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5555 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5556 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5563 MDB_node *leaf = mdb_node_search(&mc2,
5564 &mc->mc_dbx->md_name, &exact);
5566 return MDB_NOTFOUND;
5567 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
5568 return MDB_INCOMPATIBLE; /* not a named DB */
5569 rc = mdb_node_read(&mc2, leaf, &data);
5572 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5574 /* The txn may not know this DBI, or another process may
5575 * have dropped and recreated the DB with other flags.
5577 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5578 return MDB_INCOMPATIBLE;
5579 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5581 *mc->mc_dbflag &= ~DB_STALE;
5583 root = mc->mc_db->md_root;
5585 if (root == P_INVALID) { /* Tree is empty. */
5586 DPUTS("tree is empty");
5587 return MDB_NOTFOUND;
5591 mdb_cassert(mc, root > 1);
5592 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5593 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
5599 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5600 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5602 if (flags & MDB_PS_MODIFY) {
5603 if ((rc = mdb_page_touch(mc)))
5607 if (flags & MDB_PS_ROOTONLY)
5610 return mdb_page_search_root(mc, key, flags);
5614 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5616 MDB_txn *txn = mc->mc_txn;
5617 pgno_t pg = mp->mp_pgno;
5618 unsigned x = 0, ovpages = mp->mp_pages;
5619 MDB_env *env = txn->mt_env;
5620 MDB_IDL sl = txn->mt_spill_pgs;
5621 MDB_ID pn = pg << 1;
5624 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5625 /* If the page is dirty or on the spill list we just acquired it,
5626 * so we should give it back to our current free list, if any.
5627 * Otherwise put it onto the list of pages we freed in this txn.
5629 * Won't create me_pghead: me_pglast must be inited along with it.
5630 * Unsupported in nested txns: They would need to hide the page
5631 * range in ancestor txns' dirty and spilled lists.
5633 if (env->me_pghead &&
5635 ((mp->mp_flags & P_DIRTY) ||
5636 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5640 MDB_ID2 *dl, ix, iy;
5641 rc = mdb_midl_need(&env->me_pghead, ovpages);
5644 if (!(mp->mp_flags & P_DIRTY)) {
5645 /* This page is no longer spilled */
5652 /* Remove from dirty list */
5653 dl = txn->mt_u.dirty_list;
5655 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5661 mdb_cassert(mc, x > 1);
5663 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5664 txn->mt_flags |= MDB_TXN_ERROR;
5665 return MDB_CORRUPTED;
5668 txn->mt_dirty_room++;
5669 if (!(env->me_flags & MDB_WRITEMAP))
5670 mdb_dpage_free(env, mp);
5672 /* Insert in me_pghead */
5673 mop = env->me_pghead;
5674 j = mop[0] + ovpages;
5675 for (i = mop[0]; i && mop[i] < pg; i--)
5681 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5685 mc->mc_db->md_overflow_pages -= ovpages;
5689 /** Return the data associated with a given node.
5690 * @param[in] mc The cursor for this operation.
5691 * @param[in] leaf The node being read.
5692 * @param[out] data Updated to point to the node's data.
5693 * @return 0 on success, non-zero on failure.
5696 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
5698 MDB_page *omp; /* overflow page */
5702 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5703 data->mv_size = NODEDSZ(leaf);
5704 data->mv_data = NODEDATA(leaf);
5708 /* Read overflow data.
5710 data->mv_size = NODEDSZ(leaf);
5711 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5712 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
5713 DPRINTF(("read overflow page %"Z"u failed", pgno));
5716 data->mv_data = METADATA(omp);
5722 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5723 MDB_val *key, MDB_val *data)
5730 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5732 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
5735 if (txn->mt_flags & MDB_TXN_BLOCKED)
5738 mdb_cursor_init(&mc, txn, dbi, &mx);
5739 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5742 /** Find a sibling for a page.
5743 * Replaces the page at the top of the cursor's stack with the
5744 * specified sibling, if one exists.
5745 * @param[in] mc The cursor for this operation.
5746 * @param[in] move_right Non-zero if the right sibling is requested,
5747 * otherwise the left sibling.
5748 * @return 0 on success, non-zero on failure.
5751 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5757 if (mc->mc_snum < 2) {
5758 return MDB_NOTFOUND; /* root has no siblings */
5762 DPRINTF(("parent page is page %"Z"u, index %u",
5763 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5765 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5766 : (mc->mc_ki[mc->mc_top] == 0)) {
5767 DPRINTF(("no more keys left, moving to %s sibling",
5768 move_right ? "right" : "left"));
5769 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5770 /* undo cursor_pop before returning */
5777 mc->mc_ki[mc->mc_top]++;
5779 mc->mc_ki[mc->mc_top]--;
5780 DPRINTF(("just moving to %s index key %u",
5781 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5783 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5785 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5786 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
5787 /* mc will be inconsistent if caller does mc_snum++ as above */
5788 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5792 mdb_cursor_push(mc, mp);
5794 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5799 /** Move the cursor to the next data item. */
5801 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5807 if ((mc->mc_flags & C_EOF) ||
5808 ((mc->mc_flags & C_DEL) && op == MDB_NEXT_DUP)) {
5809 return MDB_NOTFOUND;
5811 if (!(mc->mc_flags & C_INITIALIZED))
5812 return mdb_cursor_first(mc, key, data);
5814 mp = mc->mc_pg[mc->mc_top];
5816 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5817 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5818 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5819 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5820 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5821 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5822 if (rc == MDB_SUCCESS)
5823 MDB_GET_KEY(leaf, key);
5828 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5829 if (op == MDB_NEXT_DUP)
5830 return MDB_NOTFOUND;
5834 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5835 mdb_dbg_pgno(mp), (void *) mc));
5836 if (mc->mc_flags & C_DEL) {
5837 mc->mc_flags ^= C_DEL;
5841 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5842 DPUTS("=====> move to next sibling page");
5843 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5844 mc->mc_flags |= C_EOF;
5847 mp = mc->mc_pg[mc->mc_top];
5848 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5850 mc->mc_ki[mc->mc_top]++;
5853 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5854 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5857 key->mv_size = mc->mc_db->md_pad;
5858 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5862 mdb_cassert(mc, IS_LEAF(mp));
5863 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5865 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5866 mdb_xcursor_init1(mc, leaf);
5869 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
5872 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5873 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5874 if (rc != MDB_SUCCESS)
5879 MDB_GET_KEY(leaf, key);
5883 /** Move the cursor to the previous data item. */
5885 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5891 if (!(mc->mc_flags & C_INITIALIZED)) {
5892 rc = mdb_cursor_last(mc, key, data);
5895 mc->mc_ki[mc->mc_top]++;
5898 mp = mc->mc_pg[mc->mc_top];
5900 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5901 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5902 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5903 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5904 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5905 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5906 if (rc == MDB_SUCCESS) {
5907 MDB_GET_KEY(leaf, key);
5908 mc->mc_flags &= ~C_EOF;
5914 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5915 if (op == MDB_PREV_DUP)
5916 return MDB_NOTFOUND;
5920 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5921 mdb_dbg_pgno(mp), (void *) mc));
5923 mc->mc_flags &= ~(C_EOF|C_DEL);
5925 if (mc->mc_ki[mc->mc_top] == 0) {
5926 DPUTS("=====> move to prev sibling page");
5927 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5930 mp = mc->mc_pg[mc->mc_top];
5931 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5932 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5934 mc->mc_ki[mc->mc_top]--;
5936 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5937 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5940 key->mv_size = mc->mc_db->md_pad;
5941 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5945 mdb_cassert(mc, IS_LEAF(mp));
5946 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5948 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5949 mdb_xcursor_init1(mc, leaf);
5952 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
5955 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5956 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5957 if (rc != MDB_SUCCESS)
5962 MDB_GET_KEY(leaf, key);
5966 /** Set the cursor on a specific data item. */
5968 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5969 MDB_cursor_op op, int *exactp)
5973 MDB_node *leaf = NULL;
5976 if (key->mv_size == 0)
5977 return MDB_BAD_VALSIZE;
5980 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5982 /* See if we're already on the right page */
5983 if (mc->mc_flags & C_INITIALIZED) {
5986 mp = mc->mc_pg[mc->mc_top];
5988 mc->mc_ki[mc->mc_top] = 0;
5989 return MDB_NOTFOUND;
5991 if (mp->mp_flags & P_LEAF2) {
5992 nodekey.mv_size = mc->mc_db->md_pad;
5993 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5995 leaf = NODEPTR(mp, 0);
5996 MDB_GET_KEY2(leaf, nodekey);
5998 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6000 /* Probably happens rarely, but first node on the page
6001 * was the one we wanted.
6003 mc->mc_ki[mc->mc_top] = 0;
6010 unsigned int nkeys = NUMKEYS(mp);
6012 if (mp->mp_flags & P_LEAF2) {
6013 nodekey.mv_data = LEAF2KEY(mp,
6014 nkeys-1, nodekey.mv_size);
6016 leaf = NODEPTR(mp, nkeys-1);
6017 MDB_GET_KEY2(leaf, nodekey);
6019 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6021 /* last node was the one we wanted */
6022 mc->mc_ki[mc->mc_top] = nkeys-1;
6028 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
6029 /* This is definitely the right page, skip search_page */
6030 if (mp->mp_flags & P_LEAF2) {
6031 nodekey.mv_data = LEAF2KEY(mp,
6032 mc->mc_ki[mc->mc_top], nodekey.mv_size);
6034 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6035 MDB_GET_KEY2(leaf, nodekey);
6037 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6039 /* current node was the one we wanted */
6046 mc->mc_flags &= ~C_EOF;
6050 /* If any parents have right-sibs, search.
6051 * Otherwise, there's nothing further.
6053 for (i=0; i<mc->mc_top; i++)
6055 NUMKEYS(mc->mc_pg[i])-1)
6057 if (i == mc->mc_top) {
6058 /* There are no other pages */
6059 mc->mc_ki[mc->mc_top] = nkeys;
6060 return MDB_NOTFOUND;
6064 /* There are no other pages */
6065 mc->mc_ki[mc->mc_top] = 0;
6066 if (op == MDB_SET_RANGE && !exactp) {
6070 return MDB_NOTFOUND;
6076 rc = mdb_page_search(mc, key, 0);
6077 if (rc != MDB_SUCCESS)
6080 mp = mc->mc_pg[mc->mc_top];
6081 mdb_cassert(mc, IS_LEAF(mp));
6084 leaf = mdb_node_search(mc, key, exactp);
6085 if (exactp != NULL && !*exactp) {
6086 /* MDB_SET specified and not an exact match. */
6087 return MDB_NOTFOUND;
6091 DPUTS("===> inexact leaf not found, goto sibling");
6092 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6093 mc->mc_flags |= C_EOF;
6094 return rc; /* no entries matched */
6096 mp = mc->mc_pg[mc->mc_top];
6097 mdb_cassert(mc, IS_LEAF(mp));
6098 leaf = NODEPTR(mp, 0);
6102 mc->mc_flags |= C_INITIALIZED;
6103 mc->mc_flags &= ~C_EOF;
6106 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
6107 key->mv_size = mc->mc_db->md_pad;
6108 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6113 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6114 mdb_xcursor_init1(mc, leaf);
6117 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6118 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
6119 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6122 if (op == MDB_GET_BOTH) {
6128 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
6129 if (rc != MDB_SUCCESS)
6132 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
6135 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
6137 dcmp = mc->mc_dbx->md_dcmp;
6138 #if UINT_MAX < SIZE_MAX
6139 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6140 dcmp = mdb_cmp_clong;
6142 rc = dcmp(data, &olddata);
6144 if (op == MDB_GET_BOTH || rc > 0)
6145 return MDB_NOTFOUND;
6152 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6153 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6158 /* The key already matches in all other cases */
6159 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6160 MDB_GET_KEY(leaf, key);
6161 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6166 /** Move the cursor to the first item in the database. */
6168 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6174 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6176 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6177 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6178 if (rc != MDB_SUCCESS)
6181 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6183 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6184 mc->mc_flags |= C_INITIALIZED;
6185 mc->mc_flags &= ~C_EOF;
6187 mc->mc_ki[mc->mc_top] = 0;
6189 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6190 key->mv_size = mc->mc_db->md_pad;
6191 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
6196 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6197 mdb_xcursor_init1(mc, leaf);
6198 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6202 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6206 MDB_GET_KEY(leaf, key);
6210 /** Move the cursor to the last item in the database. */
6212 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6218 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6220 if (!(mc->mc_flags & C_EOF)) {
6222 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6223 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
6224 if (rc != MDB_SUCCESS)
6227 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6230 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
6231 mc->mc_flags |= C_INITIALIZED|C_EOF;
6232 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6234 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6235 key->mv_size = mc->mc_db->md_pad;
6236 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
6241 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6242 mdb_xcursor_init1(mc, leaf);
6243 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6247 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6252 MDB_GET_KEY(leaf, key);
6257 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6262 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
6267 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
6271 case MDB_GET_CURRENT:
6272 if (!(mc->mc_flags & C_INITIALIZED)) {
6275 MDB_page *mp = mc->mc_pg[mc->mc_top];
6276 int nkeys = NUMKEYS(mp);
6277 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
6278 mc->mc_ki[mc->mc_top] = nkeys;
6284 key->mv_size = mc->mc_db->md_pad;
6285 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6287 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6288 MDB_GET_KEY(leaf, key);
6290 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6291 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
6293 rc = mdb_node_read(mc, leaf, data);
6300 case MDB_GET_BOTH_RANGE:
6305 if (mc->mc_xcursor == NULL) {
6306 rc = MDB_INCOMPATIBLE;
6316 rc = mdb_cursor_set(mc, key, data, op,
6317 op == MDB_SET_RANGE ? NULL : &exact);
6320 case MDB_GET_MULTIPLE:
6321 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6325 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6326 rc = MDB_INCOMPATIBLE;
6330 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6331 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6334 case MDB_NEXT_MULTIPLE:
6339 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6340 rc = MDB_INCOMPATIBLE;
6343 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6344 if (rc == MDB_SUCCESS) {
6345 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6348 mx = &mc->mc_xcursor->mx_cursor;
6349 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
6351 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
6352 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
6358 case MDB_PREV_MULTIPLE:
6363 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6364 rc = MDB_INCOMPATIBLE;
6367 if (!(mc->mc_flags & C_INITIALIZED))
6368 rc = mdb_cursor_last(mc, key, data);
6371 if (rc == MDB_SUCCESS) {
6372 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
6373 if (mx->mc_flags & C_INITIALIZED) {
6374 rc = mdb_cursor_sibling(mx, 0);
6375 if (rc == MDB_SUCCESS)
6384 case MDB_NEXT_NODUP:
6385 rc = mdb_cursor_next(mc, key, data, op);
6389 case MDB_PREV_NODUP:
6390 rc = mdb_cursor_prev(mc, key, data, op);
6393 rc = mdb_cursor_first(mc, key, data);
6396 mfunc = mdb_cursor_first;
6398 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6402 if (mc->mc_xcursor == NULL) {
6403 rc = MDB_INCOMPATIBLE;
6407 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6408 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6409 MDB_GET_KEY(leaf, key);
6410 rc = mdb_node_read(mc, leaf, data);
6414 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6418 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
6421 rc = mdb_cursor_last(mc, key, data);
6424 mfunc = mdb_cursor_last;
6427 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
6432 if (mc->mc_flags & C_DEL)
6433 mc->mc_flags ^= C_DEL;
6438 /** Touch all the pages in the cursor stack. Set mc_top.
6439 * Makes sure all the pages are writable, before attempting a write operation.
6440 * @param[in] mc The cursor to operate on.
6443 mdb_cursor_touch(MDB_cursor *mc)
6445 int rc = MDB_SUCCESS;
6447 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & (DB_DIRTY|DB_DUPDATA))) {
6448 /* Touch DB record of named DB */
6451 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6453 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
6454 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
6457 *mc->mc_dbflag |= DB_DIRTY;
6462 rc = mdb_page_touch(mc);
6463 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
6464 mc->mc_top = mc->mc_snum-1;
6469 /** Do not spill pages to disk if txn is getting full, may fail instead */
6470 #define MDB_NOSPILL 0x8000
6473 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6477 MDB_node *leaf = NULL;
6478 MDB_page *fp, *mp, *sub_root = NULL;
6480 MDB_val xdata, *rdata, dkey, olddata;
6482 int do_sub = 0, insert_key, insert_data;
6483 unsigned int mcount = 0, dcount = 0, nospill;
6486 unsigned int nflags;
6489 if (mc == NULL || key == NULL)
6492 env = mc->mc_txn->mt_env;
6494 /* Check this first so counter will always be zero on any
6497 if (flags & MDB_MULTIPLE) {
6498 dcount = data[1].mv_size;
6499 data[1].mv_size = 0;
6500 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
6501 return MDB_INCOMPATIBLE;
6504 nospill = flags & MDB_NOSPILL;
6505 flags &= ~MDB_NOSPILL;
6507 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6508 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6510 if (key->mv_size-1 >= ENV_MAXKEY(env))
6511 return MDB_BAD_VALSIZE;
6513 #if SIZE_MAX > MAXDATASIZE
6514 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
6515 return MDB_BAD_VALSIZE;
6517 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
6518 return MDB_BAD_VALSIZE;
6521 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
6522 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
6526 if (flags == MDB_CURRENT) {
6527 if (!(mc->mc_flags & C_INITIALIZED))
6530 } else if (mc->mc_db->md_root == P_INVALID) {
6531 /* new database, cursor has nothing to point to */
6534 mc->mc_flags &= ~C_INITIALIZED;
6539 if (flags & MDB_APPEND) {
6541 rc = mdb_cursor_last(mc, &k2, &d2);
6543 rc = mc->mc_dbx->md_cmp(key, &k2);
6546 mc->mc_ki[mc->mc_top]++;
6548 /* new key is <= last key */
6553 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6555 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6556 DPRINTF(("duplicate key [%s]", DKEY(key)));
6558 return MDB_KEYEXIST;
6560 if (rc && rc != MDB_NOTFOUND)
6564 if (mc->mc_flags & C_DEL)
6565 mc->mc_flags ^= C_DEL;
6567 /* Cursor is positioned, check for room in the dirty list */
6569 if (flags & MDB_MULTIPLE) {
6571 xdata.mv_size = data->mv_size * dcount;
6575 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6579 if (rc == MDB_NO_ROOT) {
6581 /* new database, write a root leaf page */
6582 DPUTS("allocating new root leaf page");
6583 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6586 mdb_cursor_push(mc, np);
6587 mc->mc_db->md_root = np->mp_pgno;
6588 mc->mc_db->md_depth++;
6589 *mc->mc_dbflag |= DB_DIRTY;
6590 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6592 np->mp_flags |= P_LEAF2;
6593 mc->mc_flags |= C_INITIALIZED;
6595 /* make sure all cursor pages are writable */
6596 rc2 = mdb_cursor_touch(mc);
6601 insert_key = insert_data = rc;
6603 /* The key does not exist */
6604 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6605 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6606 LEAFSIZE(key, data) > env->me_nodemax)
6608 /* Too big for a node, insert in sub-DB. Set up an empty
6609 * "old sub-page" for prep_subDB to expand to a full page.
6611 fp_flags = P_LEAF|P_DIRTY;
6613 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6614 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6615 olddata.mv_size = PAGEHDRSZ;
6619 /* there's only a key anyway, so this is a no-op */
6620 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6622 unsigned int ksize = mc->mc_db->md_pad;
6623 if (key->mv_size != ksize)
6624 return MDB_BAD_VALSIZE;
6625 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6626 memcpy(ptr, key->mv_data, ksize);
6628 /* if overwriting slot 0 of leaf, need to
6629 * update branch key if there is a parent page
6631 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6632 unsigned short dtop = 1;
6634 /* slot 0 is always an empty key, find real slot */
6635 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6639 if (mc->mc_ki[mc->mc_top])
6640 rc2 = mdb_update_key(mc, key);
6651 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6652 olddata.mv_size = NODEDSZ(leaf);
6653 olddata.mv_data = NODEDATA(leaf);
6656 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6657 /* Prepare (sub-)page/sub-DB to accept the new item,
6658 * if needed. fp: old sub-page or a header faking
6659 * it. mp: new (sub-)page. offset: growth in page
6660 * size. xdata: node data with new page or DB.
6662 unsigned i, offset = 0;
6663 mp = fp = xdata.mv_data = env->me_pbuf;
6664 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6666 /* Was a single item before, must convert now */
6667 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6669 /* Just overwrite the current item */
6670 if (flags == MDB_CURRENT)
6672 dcmp = mc->mc_dbx->md_dcmp;
6673 #if UINT_MAX < SIZE_MAX
6674 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6675 dcmp = mdb_cmp_clong;
6677 /* does data match? */
6678 if (!dcmp(data, &olddata)) {
6679 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
6680 return MDB_KEYEXIST;
6685 /* Back up original data item */
6686 dkey.mv_size = olddata.mv_size;
6687 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6689 /* Make sub-page header for the dup items, with dummy body */
6690 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6691 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6692 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6693 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6694 fp->mp_flags |= P_LEAF2;
6695 fp->mp_pad = data->mv_size;
6696 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6698 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6699 (dkey.mv_size & 1) + (data->mv_size & 1);
6701 fp->mp_upper = xdata.mv_size - PAGEBASE;
6702 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6703 } else if (leaf->mn_flags & F_SUBDATA) {
6704 /* Data is on sub-DB, just store it */
6705 flags |= F_DUPDATA|F_SUBDATA;
6708 /* Data is on sub-page */
6709 fp = olddata.mv_data;
6712 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6713 offset = EVEN(NODESIZE + sizeof(indx_t) +
6717 offset = fp->mp_pad;
6718 if (SIZELEFT(fp) < offset) {
6719 offset *= 4; /* space for 4 more */
6722 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6724 fp->mp_flags |= P_DIRTY;
6725 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6726 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6730 xdata.mv_size = olddata.mv_size + offset;
6733 fp_flags = fp->mp_flags;
6734 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6735 /* Too big for a sub-page, convert to sub-DB */
6736 fp_flags &= ~P_SUBP;
6738 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6739 fp_flags |= P_LEAF2;
6740 dummy.md_pad = fp->mp_pad;
6741 dummy.md_flags = MDB_DUPFIXED;
6742 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6743 dummy.md_flags |= MDB_INTEGERKEY;
6749 dummy.md_branch_pages = 0;
6750 dummy.md_leaf_pages = 1;
6751 dummy.md_overflow_pages = 0;
6752 dummy.md_entries = NUMKEYS(fp);
6753 xdata.mv_size = sizeof(MDB_db);
6754 xdata.mv_data = &dummy;
6755 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6757 offset = env->me_psize - olddata.mv_size;
6758 flags |= F_DUPDATA|F_SUBDATA;
6759 dummy.md_root = mp->mp_pgno;
6763 mp->mp_flags = fp_flags | P_DIRTY;
6764 mp->mp_pad = fp->mp_pad;
6765 mp->mp_lower = fp->mp_lower;
6766 mp->mp_upper = fp->mp_upper + offset;
6767 if (fp_flags & P_LEAF2) {
6768 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6770 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6771 olddata.mv_size - fp->mp_upper - PAGEBASE);
6772 for (i=0; i<NUMKEYS(fp); i++)
6773 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6781 mdb_node_del(mc, 0);
6785 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
6786 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
6787 return MDB_INCOMPATIBLE;
6788 /* overflow page overwrites need special handling */
6789 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6792 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6794 memcpy(&pg, olddata.mv_data, sizeof(pg));
6795 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
6797 ovpages = omp->mp_pages;
6799 /* Is the ov page large enough? */
6800 if (ovpages >= dpages) {
6801 if (!(omp->mp_flags & P_DIRTY) &&
6802 (level || (env->me_flags & MDB_WRITEMAP)))
6804 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6807 level = 0; /* dirty in this txn or clean */
6810 if (omp->mp_flags & P_DIRTY) {
6811 /* yes, overwrite it. Note in this case we don't
6812 * bother to try shrinking the page if the new data
6813 * is smaller than the overflow threshold.
6816 /* It is writable only in a parent txn */
6817 size_t sz = (size_t) env->me_psize * ovpages, off;
6818 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6824 /* Note - this page is already counted in parent's dirty_room */
6825 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6826 mdb_cassert(mc, rc2 == 0);
6827 /* Currently we make the page look as with put() in the
6828 * parent txn, in case the user peeks at MDB_RESERVEd
6829 * or unused parts. Some users treat ovpages specially.
6831 if (!(flags & MDB_RESERVE)) {
6832 /* Skip the part where LMDB will put *data.
6833 * Copy end of page, adjusting alignment so
6834 * compiler may copy words instead of bytes.
6836 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6837 memcpy((size_t *)((char *)np + off),
6838 (size_t *)((char *)omp + off), sz - off);
6841 memcpy(np, omp, sz); /* Copy beginning of page */
6844 SETDSZ(leaf, data->mv_size);
6845 if (F_ISSET(flags, MDB_RESERVE))
6846 data->mv_data = METADATA(omp);
6848 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6852 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6854 } else if (data->mv_size == olddata.mv_size) {
6855 /* same size, just replace it. Note that we could
6856 * also reuse this node if the new data is smaller,
6857 * but instead we opt to shrink the node in that case.
6859 if (F_ISSET(flags, MDB_RESERVE))
6860 data->mv_data = olddata.mv_data;
6861 else if (!(mc->mc_flags & C_SUB))
6862 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6864 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6869 mdb_node_del(mc, 0);
6875 nflags = flags & NODE_ADD_FLAGS;
6876 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6877 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6878 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6879 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6881 nflags |= MDB_SPLIT_REPLACE;
6882 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6884 /* There is room already in this leaf page. */
6885 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6887 /* Adjust other cursors pointing to mp */
6888 MDB_cursor *m2, *m3;
6889 MDB_dbi dbi = mc->mc_dbi;
6890 unsigned i = mc->mc_top;
6891 MDB_page *mp = mc->mc_pg[i];
6893 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6894 if (mc->mc_flags & C_SUB)
6895 m3 = &m2->mc_xcursor->mx_cursor;
6898 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
6899 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
6902 if (XCURSOR_INITED(m3))
6903 XCURSOR_REFRESH(m3, mp, m3->mc_ki[i]);
6908 if (rc == MDB_SUCCESS) {
6909 /* Now store the actual data in the child DB. Note that we're
6910 * storing the user data in the keys field, so there are strict
6911 * size limits on dupdata. The actual data fields of the child
6912 * DB are all zero size.
6915 int xflags, new_dupdata;
6920 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6921 if (flags & MDB_CURRENT) {
6922 xflags = MDB_CURRENT|MDB_NOSPILL;
6924 mdb_xcursor_init1(mc, leaf);
6925 xflags = (flags & MDB_NODUPDATA) ?
6926 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6929 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
6930 new_dupdata = (int)dkey.mv_size;
6931 /* converted, write the original data first */
6933 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6936 /* we've done our job */
6939 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
6940 /* Adjust other cursors pointing to mp */
6942 MDB_xcursor *mx = mc->mc_xcursor;
6943 unsigned i = mc->mc_top;
6944 MDB_page *mp = mc->mc_pg[i];
6945 int nkeys = NUMKEYS(mp);
6947 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6948 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6949 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6950 if (m2->mc_pg[i] == mp) {
6951 if (m2->mc_ki[i] == mc->mc_ki[i]) {
6952 mdb_xcursor_init2(m2, mx, new_dupdata);
6953 } else if (!insert_key && m2->mc_ki[i] < nkeys) {
6954 XCURSOR_REFRESH(m2, mp, m2->mc_ki[i]);
6959 ecount = mc->mc_xcursor->mx_db.md_entries;
6960 if (flags & MDB_APPENDDUP)
6961 xflags |= MDB_APPEND;
6962 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6963 if (flags & F_SUBDATA) {
6964 void *db = NODEDATA(leaf);
6965 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6967 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6969 /* Increment count unless we just replaced an existing item. */
6971 mc->mc_db->md_entries++;
6973 /* Invalidate txn if we created an empty sub-DB */
6976 /* If we succeeded and the key didn't exist before,
6977 * make sure the cursor is marked valid.
6979 mc->mc_flags |= C_INITIALIZED;
6981 if (flags & MDB_MULTIPLE) {
6984 /* let caller know how many succeeded, if any */
6985 data[1].mv_size = mcount;
6986 if (mcount < dcount) {
6987 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6988 insert_key = insert_data = 0;
6995 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6998 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7003 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
7009 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7010 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7012 if (!(mc->mc_flags & C_INITIALIZED))
7015 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
7016 return MDB_NOTFOUND;
7018 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
7021 rc = mdb_cursor_touch(mc);
7025 mp = mc->mc_pg[mc->mc_top];
7028 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7030 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7031 if (flags & MDB_NODUPDATA) {
7032 /* mdb_cursor_del0() will subtract the final entry */
7033 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
7034 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7036 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
7037 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7039 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
7042 /* If sub-DB still has entries, we're done */
7043 if (mc->mc_xcursor->mx_db.md_entries) {
7044 if (leaf->mn_flags & F_SUBDATA) {
7045 /* update subDB info */
7046 void *db = NODEDATA(leaf);
7047 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7050 /* shrink fake page */
7051 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
7052 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7053 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7054 /* fix other sub-DB cursors pointed at fake pages on this page */
7055 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7056 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7057 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7058 if (m2->mc_pg[mc->mc_top] == mp) {
7059 MDB_node *n2 = leaf;
7060 if (m2->mc_ki[mc->mc_top] != mc->mc_ki[mc->mc_top]) {
7061 n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
7062 if (n2->mn_flags & F_SUBDATA) continue;
7064 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7068 mc->mc_db->md_entries--;
7071 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7073 /* otherwise fall thru and delete the sub-DB */
7076 if (leaf->mn_flags & F_SUBDATA) {
7077 /* add all the child DB's pages to the free list */
7078 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7083 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
7084 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
7085 rc = MDB_INCOMPATIBLE;
7089 /* add overflow pages to free list */
7090 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7094 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7095 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
7096 (rc = mdb_ovpage_free(mc, omp)))
7101 return mdb_cursor_del0(mc);
7104 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7108 /** Allocate and initialize new pages for a database.
7109 * Set #MDB_TXN_ERROR on failure.
7110 * @param[in] mc a cursor on the database being added to.
7111 * @param[in] flags flags defining what type of page is being allocated.
7112 * @param[in] num the number of pages to allocate. This is usually 1,
7113 * unless allocating overflow pages for a large record.
7114 * @param[out] mp Address of a page, or NULL on failure.
7115 * @return 0 on success, non-zero on failure.
7118 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
7123 if ((rc = mdb_page_alloc(mc, num, &np)))
7125 DPRINTF(("allocated new mpage %"Z"u, page size %u",
7126 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
7127 np->mp_flags = flags | P_DIRTY;
7128 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
7129 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
7132 mc->mc_db->md_branch_pages++;
7133 else if (IS_LEAF(np))
7134 mc->mc_db->md_leaf_pages++;
7135 else if (IS_OVERFLOW(np)) {
7136 mc->mc_db->md_overflow_pages += num;
7144 /** Calculate the size of a leaf node.
7145 * The size depends on the environment's page size; if a data item
7146 * is too large it will be put onto an overflow page and the node
7147 * size will only include the key and not the data. Sizes are always
7148 * rounded up to an even number of bytes, to guarantee 2-byte alignment
7149 * of the #MDB_node headers.
7150 * @param[in] env The environment handle.
7151 * @param[in] key The key for the node.
7152 * @param[in] data The data for the node.
7153 * @return The number of bytes needed to store the node.
7156 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
7160 sz = LEAFSIZE(key, data);
7161 if (sz > env->me_nodemax) {
7162 /* put on overflow page */
7163 sz -= data->mv_size - sizeof(pgno_t);
7166 return EVEN(sz + sizeof(indx_t));
7169 /** Calculate the size of a branch node.
7170 * The size should depend on the environment's page size but since
7171 * we currently don't support spilling large keys onto overflow
7172 * pages, it's simply the size of the #MDB_node header plus the
7173 * size of the key. Sizes are always rounded up to an even number
7174 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7175 * @param[in] env The environment handle.
7176 * @param[in] key The key for the node.
7177 * @return The number of bytes needed to store the node.
7180 mdb_branch_size(MDB_env *env, MDB_val *key)
7185 if (sz > env->me_nodemax) {
7186 /* put on overflow page */
7187 /* not implemented */
7188 /* sz -= key->size - sizeof(pgno_t); */
7191 return sz + sizeof(indx_t);
7194 /** Add a node to the page pointed to by the cursor.
7195 * Set #MDB_TXN_ERROR on failure.
7196 * @param[in] mc The cursor for this operation.
7197 * @param[in] indx The index on the page where the new node should be added.
7198 * @param[in] key The key for the new node.
7199 * @param[in] data The data for the new node, if any.
7200 * @param[in] pgno The page number, if adding a branch node.
7201 * @param[in] flags Flags for the node.
7202 * @return 0 on success, non-zero on failure. Possible errors are:
7204 * <li>ENOMEM - failed to allocate overflow pages for the node.
7205 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
7206 * should never happen since all callers already calculate the
7207 * page's free space before calling this function.
7211 mdb_node_add(MDB_cursor *mc, indx_t indx,
7212 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
7215 size_t node_size = NODESIZE;
7219 MDB_page *mp = mc->mc_pg[mc->mc_top];
7220 MDB_page *ofp = NULL; /* overflow page */
7224 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
7226 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
7227 IS_LEAF(mp) ? "leaf" : "branch",
7228 IS_SUBP(mp) ? "sub-" : "",
7229 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
7230 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
7233 /* Move higher keys up one slot. */
7234 int ksize = mc->mc_db->md_pad, dif;
7235 char *ptr = LEAF2KEY(mp, indx, ksize);
7236 dif = NUMKEYS(mp) - indx;
7238 memmove(ptr+ksize, ptr, dif*ksize);
7239 /* insert new key */
7240 memcpy(ptr, key->mv_data, ksize);
7242 /* Just using these for counting */
7243 mp->mp_lower += sizeof(indx_t);
7244 mp->mp_upper -= ksize - sizeof(indx_t);
7248 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
7250 node_size += key->mv_size;
7252 mdb_cassert(mc, key && data);
7253 if (F_ISSET(flags, F_BIGDATA)) {
7254 /* Data already on overflow page. */
7255 node_size += sizeof(pgno_t);
7256 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
7257 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
7259 /* Put data on overflow page. */
7260 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
7261 data->mv_size, node_size+data->mv_size));
7262 node_size = EVEN(node_size + sizeof(pgno_t));
7263 if ((ssize_t)node_size > room)
7265 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
7267 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
7271 node_size += data->mv_size;
7274 node_size = EVEN(node_size);
7275 if ((ssize_t)node_size > room)
7279 /* Move higher pointers up one slot. */
7280 for (i = NUMKEYS(mp); i > indx; i--)
7281 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
7283 /* Adjust free space offsets. */
7284 ofs = mp->mp_upper - node_size;
7285 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
7286 mp->mp_ptrs[indx] = ofs;
7288 mp->mp_lower += sizeof(indx_t);
7290 /* Write the node data. */
7291 node = NODEPTR(mp, indx);
7292 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
7293 node->mn_flags = flags;
7295 SETDSZ(node,data->mv_size);
7300 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7303 ndata = NODEDATA(node);
7305 if (F_ISSET(flags, F_BIGDATA))
7306 memcpy(ndata, data->mv_data, sizeof(pgno_t));
7307 else if (F_ISSET(flags, MDB_RESERVE))
7308 data->mv_data = ndata;
7310 memcpy(ndata, data->mv_data, data->mv_size);
7312 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
7313 ndata = METADATA(ofp);
7314 if (F_ISSET(flags, MDB_RESERVE))
7315 data->mv_data = ndata;
7317 memcpy(ndata, data->mv_data, data->mv_size);
7324 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
7325 mdb_dbg_pgno(mp), NUMKEYS(mp)));
7326 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
7327 DPRINTF(("node size = %"Z"u", node_size));
7328 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7329 return MDB_PAGE_FULL;
7332 /** Delete the specified node from a page.
7333 * @param[in] mc Cursor pointing to the node to delete.
7334 * @param[in] ksize The size of a node. Only used if the page is
7335 * part of a #MDB_DUPFIXED database.
7338 mdb_node_del(MDB_cursor *mc, int ksize)
7340 MDB_page *mp = mc->mc_pg[mc->mc_top];
7341 indx_t indx = mc->mc_ki[mc->mc_top];
7343 indx_t i, j, numkeys, ptr;
7347 DPRINTF(("delete node %u on %s page %"Z"u", indx,
7348 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
7349 numkeys = NUMKEYS(mp);
7350 mdb_cassert(mc, indx < numkeys);
7353 int x = numkeys - 1 - indx;
7354 base = LEAF2KEY(mp, indx, ksize);
7356 memmove(base, base + ksize, x * ksize);
7357 mp->mp_lower -= sizeof(indx_t);
7358 mp->mp_upper += ksize - sizeof(indx_t);
7362 node = NODEPTR(mp, indx);
7363 sz = NODESIZE + node->mn_ksize;
7365 if (F_ISSET(node->mn_flags, F_BIGDATA))
7366 sz += sizeof(pgno_t);
7368 sz += NODEDSZ(node);
7372 ptr = mp->mp_ptrs[indx];
7373 for (i = j = 0; i < numkeys; i++) {
7375 mp->mp_ptrs[j] = mp->mp_ptrs[i];
7376 if (mp->mp_ptrs[i] < ptr)
7377 mp->mp_ptrs[j] += sz;
7382 base = (char *)mp + mp->mp_upper + PAGEBASE;
7383 memmove(base + sz, base, ptr - mp->mp_upper);
7385 mp->mp_lower -= sizeof(indx_t);
7389 /** Compact the main page after deleting a node on a subpage.
7390 * @param[in] mp The main page to operate on.
7391 * @param[in] indx The index of the subpage on the main page.
7394 mdb_node_shrink(MDB_page *mp, indx_t indx)
7399 indx_t delta, nsize, len, ptr;
7402 node = NODEPTR(mp, indx);
7403 sp = (MDB_page *)NODEDATA(node);
7404 delta = SIZELEFT(sp);
7405 nsize = NODEDSZ(node) - delta;
7407 /* Prepare to shift upward, set len = length(subpage part to shift) */
7411 return; /* do not make the node uneven-sized */
7413 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
7414 for (i = NUMKEYS(sp); --i >= 0; )
7415 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
7418 sp->mp_upper = sp->mp_lower;
7419 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
7420 SETDSZ(node, nsize);
7422 /* Shift <lower nodes...initial part of subpage> upward */
7423 base = (char *)mp + mp->mp_upper + PAGEBASE;
7424 memmove(base + delta, base, (char *)sp + len - base);
7426 ptr = mp->mp_ptrs[indx];
7427 for (i = NUMKEYS(mp); --i >= 0; ) {
7428 if (mp->mp_ptrs[i] <= ptr)
7429 mp->mp_ptrs[i] += delta;
7431 mp->mp_upper += delta;
7434 /** Initial setup of a sorted-dups cursor.
7435 * Sorted duplicates are implemented as a sub-database for the given key.
7436 * The duplicate data items are actually keys of the sub-database.
7437 * Operations on the duplicate data items are performed using a sub-cursor
7438 * initialized when the sub-database is first accessed. This function does
7439 * the preliminary setup of the sub-cursor, filling in the fields that
7440 * depend only on the parent DB.
7441 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7444 mdb_xcursor_init0(MDB_cursor *mc)
7446 MDB_xcursor *mx = mc->mc_xcursor;
7448 mx->mx_cursor.mc_xcursor = NULL;
7449 mx->mx_cursor.mc_txn = mc->mc_txn;
7450 mx->mx_cursor.mc_db = &mx->mx_db;
7451 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
7452 mx->mx_cursor.mc_dbi = mc->mc_dbi;
7453 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
7454 mx->mx_cursor.mc_snum = 0;
7455 mx->mx_cursor.mc_top = 0;
7456 mx->mx_cursor.mc_flags = C_SUB;
7457 mx->mx_dbx.md_name.mv_size = 0;
7458 mx->mx_dbx.md_name.mv_data = NULL;
7459 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
7460 mx->mx_dbx.md_dcmp = NULL;
7461 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
7464 /** Final setup of a sorted-dups cursor.
7465 * Sets up the fields that depend on the data from the main cursor.
7466 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7467 * @param[in] node The data containing the #MDB_db record for the
7468 * sorted-dup database.
7471 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
7473 MDB_xcursor *mx = mc->mc_xcursor;
7475 if (node->mn_flags & F_SUBDATA) {
7476 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
7477 mx->mx_cursor.mc_pg[0] = 0;
7478 mx->mx_cursor.mc_snum = 0;
7479 mx->mx_cursor.mc_top = 0;
7480 mx->mx_cursor.mc_flags = C_SUB;
7482 MDB_page *fp = NODEDATA(node);
7483 mx->mx_db.md_pad = 0;
7484 mx->mx_db.md_flags = 0;
7485 mx->mx_db.md_depth = 1;
7486 mx->mx_db.md_branch_pages = 0;
7487 mx->mx_db.md_leaf_pages = 1;
7488 mx->mx_db.md_overflow_pages = 0;
7489 mx->mx_db.md_entries = NUMKEYS(fp);
7490 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
7491 mx->mx_cursor.mc_snum = 1;
7492 mx->mx_cursor.mc_top = 0;
7493 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
7494 mx->mx_cursor.mc_pg[0] = fp;
7495 mx->mx_cursor.mc_ki[0] = 0;
7496 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7497 mx->mx_db.md_flags = MDB_DUPFIXED;
7498 mx->mx_db.md_pad = fp->mp_pad;
7499 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7500 mx->mx_db.md_flags |= MDB_INTEGERKEY;
7503 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7504 mx->mx_db.md_root));
7505 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
7506 #if UINT_MAX < SIZE_MAX
7507 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
7508 mx->mx_dbx.md_cmp = mdb_cmp_clong;
7513 /** Fixup a sorted-dups cursor due to underlying update.
7514 * Sets up some fields that depend on the data from the main cursor.
7515 * Almost the same as init1, but skips initialization steps if the
7516 * xcursor had already been used.
7517 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
7518 * @param[in] src_mx The xcursor of an up-to-date cursor.
7519 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
7522 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
7524 MDB_xcursor *mx = mc->mc_xcursor;
7527 mx->mx_cursor.mc_snum = 1;
7528 mx->mx_cursor.mc_top = 0;
7529 mx->mx_cursor.mc_flags |= C_INITIALIZED;
7530 mx->mx_cursor.mc_ki[0] = 0;
7531 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
7532 #if UINT_MAX < SIZE_MAX
7533 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
7535 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
7538 mx->mx_db = src_mx->mx_db;
7539 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
7540 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7541 mx->mx_db.md_root));
7544 /** Initialize a cursor for a given transaction and database. */
7546 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
7549 mc->mc_backup = NULL;
7552 mc->mc_db = &txn->mt_dbs[dbi];
7553 mc->mc_dbx = &txn->mt_dbxs[dbi];
7554 mc->mc_dbflag = &txn->mt_dbflags[dbi];
7560 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
7561 mdb_tassert(txn, mx != NULL);
7562 mc->mc_xcursor = mx;
7563 mdb_xcursor_init0(mc);
7565 mc->mc_xcursor = NULL;
7567 if (*mc->mc_dbflag & DB_STALE) {
7568 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
7573 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
7576 size_t size = sizeof(MDB_cursor);
7578 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
7581 if (txn->mt_flags & MDB_TXN_BLOCKED)
7584 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7587 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
7588 size += sizeof(MDB_xcursor);
7590 if ((mc = malloc(size)) != NULL) {
7591 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
7592 if (txn->mt_cursors) {
7593 mc->mc_next = txn->mt_cursors[dbi];
7594 txn->mt_cursors[dbi] = mc;
7595 mc->mc_flags |= C_UNTRACK;
7607 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
7609 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
7612 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
7615 if (txn->mt_flags & MDB_TXN_BLOCKED)
7618 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
7622 /* Return the count of duplicate data items for the current key */
7624 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7628 if (mc == NULL || countp == NULL)
7631 if (mc->mc_xcursor == NULL)
7632 return MDB_INCOMPATIBLE;
7634 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
7637 if (!(mc->mc_flags & C_INITIALIZED))
7640 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
7641 return MDB_NOTFOUND;
7643 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7644 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7647 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7650 *countp = mc->mc_xcursor->mx_db.md_entries;
7656 mdb_cursor_close(MDB_cursor *mc)
7658 if (mc && !mc->mc_backup) {
7659 /* remove from txn, if tracked */
7660 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7661 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7662 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7664 *prev = mc->mc_next;
7671 mdb_cursor_txn(MDB_cursor *mc)
7673 if (!mc) return NULL;
7678 mdb_cursor_dbi(MDB_cursor *mc)
7683 /** Replace the key for a branch node with a new key.
7684 * Set #MDB_TXN_ERROR on failure.
7685 * @param[in] mc Cursor pointing to the node to operate on.
7686 * @param[in] key The new key to use.
7687 * @return 0 on success, non-zero on failure.
7690 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7696 int delta, ksize, oksize;
7697 indx_t ptr, i, numkeys, indx;
7700 indx = mc->mc_ki[mc->mc_top];
7701 mp = mc->mc_pg[mc->mc_top];
7702 node = NODEPTR(mp, indx);
7703 ptr = mp->mp_ptrs[indx];
7707 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7708 k2.mv_data = NODEKEY(node);
7709 k2.mv_size = node->mn_ksize;
7710 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7712 mdb_dkey(&k2, kbuf2),
7718 /* Sizes must be 2-byte aligned. */
7719 ksize = EVEN(key->mv_size);
7720 oksize = EVEN(node->mn_ksize);
7721 delta = ksize - oksize;
7723 /* Shift node contents if EVEN(key length) changed. */
7725 if (delta > 0 && SIZELEFT(mp) < delta) {
7727 /* not enough space left, do a delete and split */
7728 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7729 pgno = NODEPGNO(node);
7730 mdb_node_del(mc, 0);
7731 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7734 numkeys = NUMKEYS(mp);
7735 for (i = 0; i < numkeys; i++) {
7736 if (mp->mp_ptrs[i] <= ptr)
7737 mp->mp_ptrs[i] -= delta;
7740 base = (char *)mp + mp->mp_upper + PAGEBASE;
7741 len = ptr - mp->mp_upper + NODESIZE;
7742 memmove(base - delta, base, len);
7743 mp->mp_upper -= delta;
7745 node = NODEPTR(mp, indx);
7748 /* But even if no shift was needed, update ksize */
7749 if (node->mn_ksize != key->mv_size)
7750 node->mn_ksize = key->mv_size;
7753 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7759 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7761 /** Perform \b act while tracking temporary cursor \b mn */
7762 #define WITH_CURSOR_TRACKING(mn, act) do { \
7763 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
7764 if ((mn).mc_flags & C_SUB) { \
7765 dummy.mc_flags = C_INITIALIZED; \
7766 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
7771 tracked->mc_next = *tp; \
7774 *tp = tracked->mc_next; \
7777 /** Move a node from csrc to cdst.
7780 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
7787 unsigned short flags;
7791 /* Mark src and dst as dirty. */
7792 if ((rc = mdb_page_touch(csrc)) ||
7793 (rc = mdb_page_touch(cdst)))
7796 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7797 key.mv_size = csrc->mc_db->md_pad;
7798 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7800 data.mv_data = NULL;
7804 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7805 mdb_cassert(csrc, !((size_t)srcnode & 1));
7806 srcpg = NODEPGNO(srcnode);
7807 flags = srcnode->mn_flags;
7808 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7809 unsigned int snum = csrc->mc_snum;
7811 /* must find the lowest key below src */
7812 rc = mdb_page_search_lowest(csrc);
7815 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7816 key.mv_size = csrc->mc_db->md_pad;
7817 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7819 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7820 key.mv_size = NODEKSZ(s2);
7821 key.mv_data = NODEKEY(s2);
7823 csrc->mc_snum = snum--;
7824 csrc->mc_top = snum;
7826 key.mv_size = NODEKSZ(srcnode);
7827 key.mv_data = NODEKEY(srcnode);
7829 data.mv_size = NODEDSZ(srcnode);
7830 data.mv_data = NODEDATA(srcnode);
7832 mn.mc_xcursor = NULL;
7833 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7834 unsigned int snum = cdst->mc_snum;
7837 /* must find the lowest key below dst */
7838 mdb_cursor_copy(cdst, &mn);
7839 rc = mdb_page_search_lowest(&mn);
7842 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7843 bkey.mv_size = mn.mc_db->md_pad;
7844 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7846 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7847 bkey.mv_size = NODEKSZ(s2);
7848 bkey.mv_data = NODEKEY(s2);
7850 mn.mc_snum = snum--;
7853 rc = mdb_update_key(&mn, &bkey);
7858 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7859 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7860 csrc->mc_ki[csrc->mc_top],
7862 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7863 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7865 /* Add the node to the destination page.
7867 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7868 if (rc != MDB_SUCCESS)
7871 /* Delete the node from the source page.
7873 mdb_node_del(csrc, key.mv_size);
7876 /* Adjust other cursors pointing to mp */
7877 MDB_cursor *m2, *m3;
7878 MDB_dbi dbi = csrc->mc_dbi;
7879 MDB_page *mpd, *mps;
7881 mps = csrc->mc_pg[csrc->mc_top];
7882 /* If we're adding on the left, bump others up */
7884 mpd = cdst->mc_pg[csrc->mc_top];
7885 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7886 if (csrc->mc_flags & C_SUB)
7887 m3 = &m2->mc_xcursor->mx_cursor;
7890 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
7893 m3->mc_pg[csrc->mc_top] == mpd &&
7894 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
7895 m3->mc_ki[csrc->mc_top]++;
7898 m3->mc_pg[csrc->mc_top] == mps &&
7899 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
7900 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7901 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7902 m3->mc_ki[csrc->mc_top-1]++;
7904 if (XCURSOR_INITED(m3) && IS_LEAF(mps))
7905 XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
7908 /* Adding on the right, bump others down */
7910 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7911 if (csrc->mc_flags & C_SUB)
7912 m3 = &m2->mc_xcursor->mx_cursor;
7915 if (m3 == csrc) continue;
7916 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
7918 if (m3->mc_pg[csrc->mc_top] == mps) {
7919 if (!m3->mc_ki[csrc->mc_top]) {
7920 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7921 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7922 m3->mc_ki[csrc->mc_top-1]--;
7924 m3->mc_ki[csrc->mc_top]--;
7926 if (XCURSOR_INITED(m3) && IS_LEAF(mps))
7927 XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
7933 /* Update the parent separators.
7935 if (csrc->mc_ki[csrc->mc_top] == 0) {
7936 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7937 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7938 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7940 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7941 key.mv_size = NODEKSZ(srcnode);
7942 key.mv_data = NODEKEY(srcnode);
7944 DPRINTF(("update separator for source page %"Z"u to [%s]",
7945 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7946 mdb_cursor_copy(csrc, &mn);
7949 /* We want mdb_rebalance to find mn when doing fixups */
7950 WITH_CURSOR_TRACKING(mn,
7951 rc = mdb_update_key(&mn, &key));
7955 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7957 indx_t ix = csrc->mc_ki[csrc->mc_top];
7958 nullkey.mv_size = 0;
7959 csrc->mc_ki[csrc->mc_top] = 0;
7960 rc = mdb_update_key(csrc, &nullkey);
7961 csrc->mc_ki[csrc->mc_top] = ix;
7962 mdb_cassert(csrc, rc == MDB_SUCCESS);
7966 if (cdst->mc_ki[cdst->mc_top] == 0) {
7967 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7968 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7969 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7971 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7972 key.mv_size = NODEKSZ(srcnode);
7973 key.mv_data = NODEKEY(srcnode);
7975 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7976 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7977 mdb_cursor_copy(cdst, &mn);
7980 /* We want mdb_rebalance to find mn when doing fixups */
7981 WITH_CURSOR_TRACKING(mn,
7982 rc = mdb_update_key(&mn, &key));
7986 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7988 indx_t ix = cdst->mc_ki[cdst->mc_top];
7989 nullkey.mv_size = 0;
7990 cdst->mc_ki[cdst->mc_top] = 0;
7991 rc = mdb_update_key(cdst, &nullkey);
7992 cdst->mc_ki[cdst->mc_top] = ix;
7993 mdb_cassert(cdst, rc == MDB_SUCCESS);
8000 /** Merge one page into another.
8001 * The nodes from the page pointed to by \b csrc will
8002 * be copied to the page pointed to by \b cdst and then
8003 * the \b csrc page will be freed.
8004 * @param[in] csrc Cursor pointing to the source page.
8005 * @param[in] cdst Cursor pointing to the destination page.
8006 * @return 0 on success, non-zero on failure.
8009 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
8011 MDB_page *psrc, *pdst;
8018 psrc = csrc->mc_pg[csrc->mc_top];
8019 pdst = cdst->mc_pg[cdst->mc_top];
8021 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
8023 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
8024 mdb_cassert(csrc, cdst->mc_snum > 1);
8026 /* Mark dst as dirty. */
8027 if ((rc = mdb_page_touch(cdst)))
8030 /* get dst page again now that we've touched it. */
8031 pdst = cdst->mc_pg[cdst->mc_top];
8033 /* Move all nodes from src to dst.
8035 j = nkeys = NUMKEYS(pdst);
8036 if (IS_LEAF2(psrc)) {
8037 key.mv_size = csrc->mc_db->md_pad;
8038 key.mv_data = METADATA(psrc);
8039 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8040 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
8041 if (rc != MDB_SUCCESS)
8043 key.mv_data = (char *)key.mv_data + key.mv_size;
8046 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8047 srcnode = NODEPTR(psrc, i);
8048 if (i == 0 && IS_BRANCH(psrc)) {
8051 mdb_cursor_copy(csrc, &mn);
8052 mn.mc_xcursor = NULL;
8053 /* must find the lowest key below src */
8054 rc = mdb_page_search_lowest(&mn);
8057 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8058 key.mv_size = mn.mc_db->md_pad;
8059 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
8061 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8062 key.mv_size = NODEKSZ(s2);
8063 key.mv_data = NODEKEY(s2);
8066 key.mv_size = srcnode->mn_ksize;
8067 key.mv_data = NODEKEY(srcnode);
8070 data.mv_size = NODEDSZ(srcnode);
8071 data.mv_data = NODEDATA(srcnode);
8072 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
8073 if (rc != MDB_SUCCESS)
8078 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
8079 pdst->mp_pgno, NUMKEYS(pdst),
8080 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
8082 /* Unlink the src page from parent and add to free list.
8085 mdb_node_del(csrc, 0);
8086 if (csrc->mc_ki[csrc->mc_top] == 0) {
8088 rc = mdb_update_key(csrc, &key);
8096 psrc = csrc->mc_pg[csrc->mc_top];
8097 /* If not operating on FreeDB, allow this page to be reused
8098 * in this txn. Otherwise just add to free list.
8100 rc = mdb_page_loose(csrc, psrc);
8104 csrc->mc_db->md_leaf_pages--;
8106 csrc->mc_db->md_branch_pages--;
8108 /* Adjust other cursors pointing to mp */
8109 MDB_cursor *m2, *m3;
8110 MDB_dbi dbi = csrc->mc_dbi;
8111 unsigned int top = csrc->mc_top;
8113 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8114 if (csrc->mc_flags & C_SUB)
8115 m3 = &m2->mc_xcursor->mx_cursor;
8118 if (m3 == csrc) continue;
8119 if (m3->mc_snum < csrc->mc_snum) continue;
8120 if (m3->mc_pg[top] == psrc) {
8121 m3->mc_pg[top] = pdst;
8122 m3->mc_ki[top] += nkeys;
8123 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
8124 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
8125 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
8128 if (XCURSOR_INITED(m3) && IS_LEAF(psrc))
8129 XCURSOR_REFRESH(m3, m3->mc_pg[top], m3->mc_ki[top]);
8133 unsigned int snum = cdst->mc_snum;
8134 uint16_t depth = cdst->mc_db->md_depth;
8135 mdb_cursor_pop(cdst);
8136 rc = mdb_rebalance(cdst);
8137 /* Did the tree height change? */
8138 if (depth != cdst->mc_db->md_depth)
8139 snum += cdst->mc_db->md_depth - depth;
8140 cdst->mc_snum = snum;
8141 cdst->mc_top = snum-1;
8146 /** Copy the contents of a cursor.
8147 * @param[in] csrc The cursor to copy from.
8148 * @param[out] cdst The cursor to copy to.
8151 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
8155 cdst->mc_txn = csrc->mc_txn;
8156 cdst->mc_dbi = csrc->mc_dbi;
8157 cdst->mc_db = csrc->mc_db;
8158 cdst->mc_dbx = csrc->mc_dbx;
8159 cdst->mc_snum = csrc->mc_snum;
8160 cdst->mc_top = csrc->mc_top;
8161 cdst->mc_flags = csrc->mc_flags;
8163 for (i=0; i<csrc->mc_snum; i++) {
8164 cdst->mc_pg[i] = csrc->mc_pg[i];
8165 cdst->mc_ki[i] = csrc->mc_ki[i];
8169 /** Rebalance the tree after a delete operation.
8170 * @param[in] mc Cursor pointing to the page where rebalancing
8172 * @return 0 on success, non-zero on failure.
8175 mdb_rebalance(MDB_cursor *mc)
8179 unsigned int ptop, minkeys, thresh;
8183 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
8188 thresh = FILL_THRESHOLD;
8190 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
8191 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
8192 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
8193 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
8195 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
8196 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
8197 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
8198 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
8202 if (mc->mc_snum < 2) {
8203 MDB_page *mp = mc->mc_pg[0];
8205 DPUTS("Can't rebalance a subpage, ignoring");
8208 if (NUMKEYS(mp) == 0) {
8209 DPUTS("tree is completely empty");
8210 mc->mc_db->md_root = P_INVALID;
8211 mc->mc_db->md_depth = 0;
8212 mc->mc_db->md_leaf_pages = 0;
8213 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8216 /* Adjust cursors pointing to mp */
8219 mc->mc_flags &= ~C_INITIALIZED;
8221 MDB_cursor *m2, *m3;
8222 MDB_dbi dbi = mc->mc_dbi;
8224 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8225 if (mc->mc_flags & C_SUB)
8226 m3 = &m2->mc_xcursor->mx_cursor;
8229 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
8231 if (m3->mc_pg[0] == mp) {
8234 m3->mc_flags &= ~C_INITIALIZED;
8238 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
8240 DPUTS("collapsing root page!");
8241 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8244 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
8245 rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
8248 mc->mc_db->md_depth--;
8249 mc->mc_db->md_branch_pages--;
8250 mc->mc_ki[0] = mc->mc_ki[1];
8251 for (i = 1; i<mc->mc_db->md_depth; i++) {
8252 mc->mc_pg[i] = mc->mc_pg[i+1];
8253 mc->mc_ki[i] = mc->mc_ki[i+1];
8256 /* Adjust other cursors pointing to mp */
8257 MDB_cursor *m2, *m3;
8258 MDB_dbi dbi = mc->mc_dbi;
8260 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8261 if (mc->mc_flags & C_SUB)
8262 m3 = &m2->mc_xcursor->mx_cursor;
8265 if (m3 == mc) continue;
8266 if (!(m3->mc_flags & C_INITIALIZED))
8268 if (m3->mc_pg[0] == mp) {
8269 for (i=0; i<mc->mc_db->md_depth; i++) {
8270 m3->mc_pg[i] = m3->mc_pg[i+1];
8271 m3->mc_ki[i] = m3->mc_ki[i+1];
8279 DPUTS("root page doesn't need rebalancing");
8283 /* The parent (branch page) must have at least 2 pointers,
8284 * otherwise the tree is invalid.
8286 ptop = mc->mc_top-1;
8287 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
8289 /* Leaf page fill factor is below the threshold.
8290 * Try to move keys from left or right neighbor, or
8291 * merge with a neighbor page.
8296 mdb_cursor_copy(mc, &mn);
8297 mn.mc_xcursor = NULL;
8299 oldki = mc->mc_ki[mc->mc_top];
8300 if (mc->mc_ki[ptop] == 0) {
8301 /* We're the leftmost leaf in our parent.
8303 DPUTS("reading right neighbor");
8305 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8306 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8309 mn.mc_ki[mn.mc_top] = 0;
8310 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
8313 /* There is at least one neighbor to the left.
8315 DPUTS("reading left neighbor");
8317 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8318 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8321 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
8322 mc->mc_ki[mc->mc_top] = 0;
8326 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
8327 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
8328 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
8330 /* If the neighbor page is above threshold and has enough keys,
8331 * move one key from it. Otherwise we should try to merge them.
8332 * (A branch page must never have less than 2 keys.)
8334 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
8335 rc = mdb_node_move(&mn, mc, fromleft);
8337 /* if we inserted on left, bump position up */
8342 rc = mdb_page_merge(&mn, mc);
8344 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
8345 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
8346 /* We want mdb_rebalance to find mn when doing fixups */
8347 WITH_CURSOR_TRACKING(mn,
8348 rc = mdb_page_merge(mc, &mn));
8349 mdb_cursor_copy(&mn, mc);
8351 mc->mc_flags &= ~C_EOF;
8353 mc->mc_ki[mc->mc_top] = oldki;
8357 /** Complete a delete operation started by #mdb_cursor_del(). */
8359 mdb_cursor_del0(MDB_cursor *mc)
8365 MDB_cursor *m2, *m3;
8366 MDB_dbi dbi = mc->mc_dbi;
8368 ki = mc->mc_ki[mc->mc_top];
8369 mp = mc->mc_pg[mc->mc_top];
8370 mdb_node_del(mc, mc->mc_db->md_pad);
8371 mc->mc_db->md_entries--;
8373 /* Adjust other cursors pointing to mp */
8374 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8375 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8376 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8378 if (m3 == mc || m3->mc_snum < mc->mc_snum)
8380 if (m3->mc_pg[mc->mc_top] == mp) {
8381 if (m3->mc_ki[mc->mc_top] == ki) {
8382 m3->mc_flags |= C_DEL;
8383 if (mc->mc_db->md_flags & MDB_DUPSORT) {
8384 /* Sub-cursor referred into dataset which is gone */
8385 m3->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
8388 } else if (m3->mc_ki[mc->mc_top] > ki) {
8389 m3->mc_ki[mc->mc_top]--;
8391 if (XCURSOR_INITED(m3))
8392 XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
8396 rc = mdb_rebalance(mc);
8398 if (rc == MDB_SUCCESS) {
8399 /* DB is totally empty now, just bail out.
8400 * Other cursors adjustments were already done
8401 * by mdb_rebalance and aren't needed here.
8406 mp = mc->mc_pg[mc->mc_top];
8407 nkeys = NUMKEYS(mp);
8409 /* Adjust other cursors pointing to mp */
8410 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
8411 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8412 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8414 if (m3->mc_snum < mc->mc_snum)
8416 if (m3->mc_pg[mc->mc_top] == mp) {
8417 /* if m3 points past last node in page, find next sibling */
8418 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
8419 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8420 rc = mdb_cursor_sibling(m3, 1);
8421 if (rc == MDB_NOTFOUND) {
8422 m3->mc_flags |= C_EOF;
8427 if (mc->mc_db->md_flags & MDB_DUPSORT) {
8428 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
8429 /* If this node is a fake page, it needs to be reinited
8430 * because its data has moved. But just reset mc_pg[0]
8431 * if the xcursor is already live.
8433 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) {
8434 if (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)
8435 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8437 mdb_xcursor_init1(m3, node);
8443 mc->mc_flags |= C_DEL;
8447 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8452 mdb_del(MDB_txn *txn, MDB_dbi dbi,
8453 MDB_val *key, MDB_val *data)
8455 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8458 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8459 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8461 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
8462 /* must ignore any data */
8466 return mdb_del0(txn, dbi, key, data, 0);
8470 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
8471 MDB_val *key, MDB_val *data, unsigned flags)
8476 MDB_val rdata, *xdata;
8480 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
8482 mdb_cursor_init(&mc, txn, dbi, &mx);
8491 flags |= MDB_NODUPDATA;
8493 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
8495 /* let mdb_page_split know about this cursor if needed:
8496 * delete will trigger a rebalance; if it needs to move
8497 * a node from one page to another, it will have to
8498 * update the parent's separator key(s). If the new sepkey
8499 * is larger than the current one, the parent page may
8500 * run out of space, triggering a split. We need this
8501 * cursor to be consistent until the end of the rebalance.
8503 mc.mc_flags |= C_UNTRACK;
8504 mc.mc_next = txn->mt_cursors[dbi];
8505 txn->mt_cursors[dbi] = &mc;
8506 rc = mdb_cursor_del(&mc, flags);
8507 txn->mt_cursors[dbi] = mc.mc_next;
8512 /** Split a page and insert a new node.
8513 * Set #MDB_TXN_ERROR on failure.
8514 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
8515 * The cursor will be updated to point to the actual page and index where
8516 * the node got inserted after the split.
8517 * @param[in] newkey The key for the newly inserted node.
8518 * @param[in] newdata The data for the newly inserted node.
8519 * @param[in] newpgno The page number, if the new node is a branch node.
8520 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
8521 * @return 0 on success, non-zero on failure.
8524 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
8525 unsigned int nflags)
8528 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
8531 int i, j, split_indx, nkeys, pmax;
8532 MDB_env *env = mc->mc_txn->mt_env;
8534 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
8535 MDB_page *copy = NULL;
8536 MDB_page *mp, *rp, *pp;
8541 mp = mc->mc_pg[mc->mc_top];
8542 newindx = mc->mc_ki[mc->mc_top];
8543 nkeys = NUMKEYS(mp);
8545 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
8546 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
8547 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
8549 /* Create a right sibling. */
8550 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
8552 rp->mp_pad = mp->mp_pad;
8553 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
8555 /* Usually when splitting the root page, the cursor
8556 * height is 1. But when called from mdb_update_key,
8557 * the cursor height may be greater because it walks
8558 * up the stack while finding the branch slot to update.
8560 if (mc->mc_top < 1) {
8561 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
8563 /* shift current top to make room for new parent */
8564 for (i=mc->mc_snum; i>0; i--) {
8565 mc->mc_pg[i] = mc->mc_pg[i-1];
8566 mc->mc_ki[i] = mc->mc_ki[i-1];
8570 mc->mc_db->md_root = pp->mp_pgno;
8571 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
8572 new_root = mc->mc_db->md_depth++;
8574 /* Add left (implicit) pointer. */
8575 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
8576 /* undo the pre-push */
8577 mc->mc_pg[0] = mc->mc_pg[1];
8578 mc->mc_ki[0] = mc->mc_ki[1];
8579 mc->mc_db->md_root = mp->mp_pgno;
8580 mc->mc_db->md_depth--;
8587 ptop = mc->mc_top-1;
8588 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
8591 mdb_cursor_copy(mc, &mn);
8592 mn.mc_xcursor = NULL;
8593 mn.mc_pg[mn.mc_top] = rp;
8594 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
8596 if (nflags & MDB_APPEND) {
8597 mn.mc_ki[mn.mc_top] = 0;
8599 split_indx = newindx;
8603 split_indx = (nkeys+1) / 2;
8608 unsigned int lsize, rsize, ksize;
8609 /* Move half of the keys to the right sibling */
8610 x = mc->mc_ki[mc->mc_top] - split_indx;
8611 ksize = mc->mc_db->md_pad;
8612 split = LEAF2KEY(mp, split_indx, ksize);
8613 rsize = (nkeys - split_indx) * ksize;
8614 lsize = (nkeys - split_indx) * sizeof(indx_t);
8615 mp->mp_lower -= lsize;
8616 rp->mp_lower += lsize;
8617 mp->mp_upper += rsize - lsize;
8618 rp->mp_upper -= rsize - lsize;
8619 sepkey.mv_size = ksize;
8620 if (newindx == split_indx) {
8621 sepkey.mv_data = newkey->mv_data;
8623 sepkey.mv_data = split;
8626 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
8627 memcpy(rp->mp_ptrs, split, rsize);
8628 sepkey.mv_data = rp->mp_ptrs;
8629 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
8630 memcpy(ins, newkey->mv_data, ksize);
8631 mp->mp_lower += sizeof(indx_t);
8632 mp->mp_upper -= ksize - sizeof(indx_t);
8635 memcpy(rp->mp_ptrs, split, x * ksize);
8636 ins = LEAF2KEY(rp, x, ksize);
8637 memcpy(ins, newkey->mv_data, ksize);
8638 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
8639 rp->mp_lower += sizeof(indx_t);
8640 rp->mp_upper -= ksize - sizeof(indx_t);
8641 mc->mc_ki[mc->mc_top] = x;
8644 int psize, nsize, k;
8645 /* Maximum free space in an empty page */
8646 pmax = env->me_psize - PAGEHDRSZ;
8648 nsize = mdb_leaf_size(env, newkey, newdata);
8650 nsize = mdb_branch_size(env, newkey);
8651 nsize = EVEN(nsize);
8653 /* grab a page to hold a temporary copy */
8654 copy = mdb_page_malloc(mc->mc_txn, 1);
8659 copy->mp_pgno = mp->mp_pgno;
8660 copy->mp_flags = mp->mp_flags;
8661 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
8662 copy->mp_upper = env->me_psize - PAGEBASE;
8664 /* prepare to insert */
8665 for (i=0, j=0; i<nkeys; i++) {
8667 copy->mp_ptrs[j++] = 0;
8669 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
8672 /* When items are relatively large the split point needs
8673 * to be checked, because being off-by-one will make the
8674 * difference between success or failure in mdb_node_add.
8676 * It's also relevant if a page happens to be laid out
8677 * such that one half of its nodes are all "small" and
8678 * the other half of its nodes are "large." If the new
8679 * item is also "large" and falls on the half with
8680 * "large" nodes, it also may not fit.
8682 * As a final tweak, if the new item goes on the last
8683 * spot on the page (and thus, onto the new page), bias
8684 * the split so the new page is emptier than the old page.
8685 * This yields better packing during sequential inserts.
8687 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
8688 /* Find split point */
8690 if (newindx <= split_indx || newindx >= nkeys) {
8692 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
8697 for (; i!=k; i+=j) {
8702 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8703 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
8705 if (F_ISSET(node->mn_flags, F_BIGDATA))
8706 psize += sizeof(pgno_t);
8708 psize += NODEDSZ(node);
8710 psize = EVEN(psize);
8712 if (psize > pmax || i == k-j) {
8713 split_indx = i + (j<0);
8718 if (split_indx == newindx) {
8719 sepkey.mv_size = newkey->mv_size;
8720 sepkey.mv_data = newkey->mv_data;
8722 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
8723 sepkey.mv_size = node->mn_ksize;
8724 sepkey.mv_data = NODEKEY(node);
8729 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
8731 /* Copy separator key to the parent.
8733 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
8734 int snum = mc->mc_snum;
8738 /* We want other splits to find mn when doing fixups */
8739 WITH_CURSOR_TRACKING(mn,
8740 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
8745 if (mc->mc_snum > snum) {
8748 /* Right page might now have changed parent.
8749 * Check if left page also changed parent.
8751 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8752 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8753 for (i=0; i<ptop; i++) {
8754 mc->mc_pg[i] = mn.mc_pg[i];
8755 mc->mc_ki[i] = mn.mc_ki[i];
8757 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8758 if (mn.mc_ki[ptop]) {
8759 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8761 /* find right page's left sibling */
8762 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8763 mdb_cursor_sibling(mc, 0);
8768 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8771 if (rc != MDB_SUCCESS) {
8774 if (nflags & MDB_APPEND) {
8775 mc->mc_pg[mc->mc_top] = rp;
8776 mc->mc_ki[mc->mc_top] = 0;
8777 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8780 for (i=0; i<mc->mc_top; i++)
8781 mc->mc_ki[i] = mn.mc_ki[i];
8782 } else if (!IS_LEAF2(mp)) {
8784 mc->mc_pg[mc->mc_top] = rp;
8789 rkey.mv_data = newkey->mv_data;
8790 rkey.mv_size = newkey->mv_size;
8796 /* Update index for the new key. */
8797 mc->mc_ki[mc->mc_top] = j;
8799 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8800 rkey.mv_data = NODEKEY(node);
8801 rkey.mv_size = node->mn_ksize;
8803 xdata.mv_data = NODEDATA(node);
8804 xdata.mv_size = NODEDSZ(node);
8807 pgno = NODEPGNO(node);
8808 flags = node->mn_flags;
8811 if (!IS_LEAF(mp) && j == 0) {
8812 /* First branch index doesn't need key data. */
8816 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8822 mc->mc_pg[mc->mc_top] = copy;
8827 } while (i != split_indx);
8829 nkeys = NUMKEYS(copy);
8830 for (i=0; i<nkeys; i++)
8831 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8832 mp->mp_lower = copy->mp_lower;
8833 mp->mp_upper = copy->mp_upper;
8834 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8835 env->me_psize - copy->mp_upper - PAGEBASE);
8837 /* reset back to original page */
8838 if (newindx < split_indx) {
8839 mc->mc_pg[mc->mc_top] = mp;
8841 mc->mc_pg[mc->mc_top] = rp;
8843 /* Make sure mc_ki is still valid.
8845 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8846 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8847 for (i=0; i<=ptop; i++) {
8848 mc->mc_pg[i] = mn.mc_pg[i];
8849 mc->mc_ki[i] = mn.mc_ki[i];
8853 if (nflags & MDB_RESERVE) {
8854 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8855 if (!(node->mn_flags & F_BIGDATA))
8856 newdata->mv_data = NODEDATA(node);
8859 if (newindx >= split_indx) {
8860 mc->mc_pg[mc->mc_top] = rp;
8862 /* Make sure mc_ki is still valid.
8864 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8865 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8866 for (i=0; i<=ptop; i++) {
8867 mc->mc_pg[i] = mn.mc_pg[i];
8868 mc->mc_ki[i] = mn.mc_ki[i];
8875 /* Adjust other cursors pointing to mp */
8876 MDB_cursor *m2, *m3;
8877 MDB_dbi dbi = mc->mc_dbi;
8878 nkeys = NUMKEYS(mp);
8880 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8881 if (mc->mc_flags & C_SUB)
8882 m3 = &m2->mc_xcursor->mx_cursor;
8887 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8891 /* sub cursors may be on different DB */
8892 if (m3->mc_pg[0] != mp)
8895 for (k=new_root; k>=0; k--) {
8896 m3->mc_ki[k+1] = m3->mc_ki[k];
8897 m3->mc_pg[k+1] = m3->mc_pg[k];
8899 if (m3->mc_ki[0] >= nkeys) {
8904 m3->mc_pg[0] = mc->mc_pg[0];
8908 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8909 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8910 m3->mc_ki[mc->mc_top]++;
8911 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8912 m3->mc_pg[mc->mc_top] = rp;
8913 m3->mc_ki[mc->mc_top] -= nkeys;
8914 for (i=0; i<mc->mc_top; i++) {
8915 m3->mc_ki[i] = mn.mc_ki[i];
8916 m3->mc_pg[i] = mn.mc_pg[i];
8919 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8920 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8923 if (XCURSOR_INITED(m3) && IS_LEAF(mp))
8924 XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
8927 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8930 if (copy) /* tmp page */
8931 mdb_page_free(env, copy);
8933 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8938 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8939 MDB_val *key, MDB_val *data, unsigned int flags)
8945 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8948 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
8951 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8952 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8954 mdb_cursor_init(&mc, txn, dbi, &mx);
8955 mc.mc_next = txn->mt_cursors[dbi];
8956 txn->mt_cursors[dbi] = &mc;
8957 rc = mdb_cursor_put(&mc, key, data, flags);
8958 txn->mt_cursors[dbi] = mc.mc_next;
8963 #define MDB_WBUF (1024*1024)
8965 #define MDB_EOF 0x10 /**< #mdb_env_copyfd1() is done reading */
8967 /** State needed for a double-buffering compacting copy. */
8968 typedef struct mdb_copy {
8971 pthread_mutex_t mc_mutex;
8972 pthread_cond_t mc_cond; /**< Condition variable for #mc_new */
8977 pgno_t mc_next_pgno;
8979 int mc_toggle; /**< Buffer number in provider */
8980 int mc_new; /**< (0-2 buffers to write) | (#MDB_EOF at end) */
8981 /** Error code. Never cleared if set. Both threads can set nonzero
8982 * to fail the copy. Not mutex-protected, LMDB expects atomic int.
8984 volatile int mc_error;
8987 /** Dedicated writer thread for compacting copy. */
8988 static THREAD_RET ESECT CALL_CONV
8989 mdb_env_copythr(void *arg)
8993 int toggle = 0, wsize, rc;
8996 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8999 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9003 sigaddset(&set, SIGPIPE);
9004 if ((rc = pthread_sigmask(SIG_BLOCK, &set, NULL)) != 0)
9009 pthread_mutex_lock(&my->mc_mutex);
9012 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9013 if (my->mc_new == 0 + MDB_EOF) /* 0 buffers, just EOF */
9015 wsize = my->mc_wlen[toggle];
9016 ptr = my->mc_wbuf[toggle];
9019 while (wsize > 0 && !my->mc_error) {
9020 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
9023 #if defined(SIGPIPE) && !defined(_WIN32)
9025 /* Collect the pending SIGPIPE, otherwise at least OS X
9026 * gives it to the process on thread-exit (ITS#8504).
9029 sigwait(&set, &tmp);
9033 } else if (len > 0) {
9046 /* If there's an overflow page tail, write it too */
9047 if (my->mc_olen[toggle]) {
9048 wsize = my->mc_olen[toggle];
9049 ptr = my->mc_over[toggle];
9050 my->mc_olen[toggle] = 0;
9053 my->mc_wlen[toggle] = 0;
9055 /* Return the empty buffer to provider */
9057 pthread_cond_signal(&my->mc_cond);
9059 pthread_mutex_unlock(&my->mc_mutex);
9060 return (THREAD_RET)0;
9064 /** Give buffer and/or #MDB_EOF to writer thread, await unused buffer.
9066 * @param[in] my control structure.
9067 * @param[in] adjust (1 to hand off 1 buffer) | (MDB_EOF when ending).
9070 mdb_env_cthr_toggle(mdb_copy *my, int adjust)
9072 pthread_mutex_lock(&my->mc_mutex);
9073 my->mc_new += adjust;
9074 pthread_cond_signal(&my->mc_cond);
9075 while (my->mc_new & 2) /* both buffers in use */
9076 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9077 pthread_mutex_unlock(&my->mc_mutex);
9079 my->mc_toggle ^= (adjust & 1);
9080 /* Both threads reset mc_wlen, to be safe from threading errors */
9081 my->mc_wlen[my->mc_toggle] = 0;
9082 return my->mc_error;
9085 /** Depth-first tree traversal for compacting copy.
9086 * @param[in] my control structure.
9087 * @param[in,out] pg database root.
9088 * @param[in] flags includes #F_DUPDATA if it is a sorted-duplicate sub-DB.
9091 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
9093 MDB_cursor mc = {0};
9095 MDB_page *mo, *mp, *leaf;
9100 /* Empty DB, nothing to do */
9101 if (*pg == P_INVALID)
9105 mc.mc_txn = my->mc_txn;
9107 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
9110 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
9114 /* Make cursor pages writable */
9115 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
9119 for (i=0; i<mc.mc_top; i++) {
9120 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
9121 mc.mc_pg[i] = (MDB_page *)ptr;
9122 ptr += my->mc_env->me_psize;
9125 /* This is writable space for a leaf page. Usually not needed. */
9126 leaf = (MDB_page *)ptr;
9128 toggle = my->mc_toggle;
9129 while (mc.mc_snum > 0) {
9131 mp = mc.mc_pg[mc.mc_top];
9135 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
9136 for (i=0; i<n; i++) {
9137 ni = NODEPTR(mp, i);
9138 if (ni->mn_flags & F_BIGDATA) {
9142 /* Need writable leaf */
9144 mc.mc_pg[mc.mc_top] = leaf;
9145 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9147 ni = NODEPTR(mp, i);
9150 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9151 memcpy(NODEDATA(ni), &my->mc_next_pgno, sizeof(pgno_t));
9152 rc = mdb_page_get(&mc, pg, &omp, NULL);
9155 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9156 rc = mdb_env_cthr_toggle(my, 1);
9159 toggle = my->mc_toggle;
9161 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9162 memcpy(mo, omp, my->mc_env->me_psize);
9163 mo->mp_pgno = my->mc_next_pgno;
9164 my->mc_next_pgno += omp->mp_pages;
9165 my->mc_wlen[toggle] += my->mc_env->me_psize;
9166 if (omp->mp_pages > 1) {
9167 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
9168 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
9169 rc = mdb_env_cthr_toggle(my, 1);
9172 toggle = my->mc_toggle;
9174 } else if (ni->mn_flags & F_SUBDATA) {
9177 /* Need writable leaf */
9179 mc.mc_pg[mc.mc_top] = leaf;
9180 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9182 ni = NODEPTR(mp, i);
9185 memcpy(&db, NODEDATA(ni), sizeof(db));
9186 my->mc_toggle = toggle;
9187 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
9190 toggle = my->mc_toggle;
9191 memcpy(NODEDATA(ni), &db, sizeof(db));
9196 mc.mc_ki[mc.mc_top]++;
9197 if (mc.mc_ki[mc.mc_top] < n) {
9200 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
9202 rc = mdb_page_get(&mc, pg, &mp, NULL);
9207 mc.mc_ki[mc.mc_top] = 0;
9208 if (IS_BRANCH(mp)) {
9209 /* Whenever we advance to a sibling branch page,
9210 * we must proceed all the way down to its first leaf.
9212 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
9215 mc.mc_pg[mc.mc_top] = mp;
9219 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9220 rc = mdb_env_cthr_toggle(my, 1);
9223 toggle = my->mc_toggle;
9225 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9226 mdb_page_copy(mo, mp, my->mc_env->me_psize);
9227 mo->mp_pgno = my->mc_next_pgno++;
9228 my->mc_wlen[toggle] += my->mc_env->me_psize;
9230 /* Update parent if there is one */
9231 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
9232 SETPGNO(ni, mo->mp_pgno);
9233 mdb_cursor_pop(&mc);
9235 /* Otherwise we're done */
9245 /** Copy environment with compaction. */
9247 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
9252 MDB_txn *txn = NULL;
9254 pgno_t root, new_root;
9255 int rc = MDB_SUCCESS;
9258 if (!(my.mc_mutex = CreateMutex(NULL, FALSE, NULL)) ||
9259 !(my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL))) {
9263 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
9264 if (my.mc_wbuf[0] == NULL) {
9265 /* _aligned_malloc() sets errno, but we use Windows error codes */
9266 rc = ERROR_NOT_ENOUGH_MEMORY;
9270 if ((rc = pthread_mutex_init(&my.mc_mutex, NULL)) != 0)
9272 if ((rc = pthread_cond_init(&my.mc_cond, NULL)) != 0)
9274 #ifdef HAVE_MEMALIGN
9275 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
9276 if (my.mc_wbuf[0] == NULL) {
9283 if ((rc = posix_memalign(&p, env->me_os_psize, MDB_WBUF*2)) != 0)
9289 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
9290 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
9291 my.mc_next_pgno = NUM_METAS;
9294 rc = THREAD_CREATE(thr, mdb_env_copythr, &my);
9298 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9302 mp = (MDB_page *)my.mc_wbuf[0];
9303 memset(mp, 0, NUM_METAS * env->me_psize);
9305 mp->mp_flags = P_META;
9306 mm = (MDB_meta *)METADATA(mp);
9307 mdb_env_init_meta0(env, mm);
9308 mm->mm_address = env->me_metas[0]->mm_address;
9310 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
9312 mp->mp_flags = P_META;
9313 *(MDB_meta *)METADATA(mp) = *mm;
9314 mm = (MDB_meta *)METADATA(mp);
9316 /* Set metapage 1 with current main DB */
9317 root = new_root = txn->mt_dbs[MAIN_DBI].md_root;
9318 if (root != P_INVALID) {
9319 /* Count free pages + freeDB pages. Subtract from last_pg
9320 * to find the new last_pg, which also becomes the new root.
9322 MDB_ID freecount = 0;
9325 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
9326 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
9327 freecount += *(MDB_ID *)data.mv_data;
9328 if (rc != MDB_NOTFOUND)
9330 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
9331 txn->mt_dbs[FREE_DBI].md_leaf_pages +
9332 txn->mt_dbs[FREE_DBI].md_overflow_pages;
9334 new_root = txn->mt_next_pgno - 1 - freecount;
9335 mm->mm_last_pg = new_root;
9336 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
9337 mm->mm_dbs[MAIN_DBI].md_root = new_root;
9339 /* When the DB is empty, handle it specially to
9340 * fix any breakage like page leaks from ITS#8174.
9342 mm->mm_dbs[MAIN_DBI].md_flags = txn->mt_dbs[MAIN_DBI].md_flags;
9344 if (root != P_INVALID || mm->mm_dbs[MAIN_DBI].md_flags) {
9345 mm->mm_txnid = 1; /* use metapage 1 */
9348 my.mc_wlen[0] = env->me_psize * NUM_METAS;
9350 rc = mdb_env_cwalk(&my, &root, 0);
9351 if (rc == MDB_SUCCESS && root != new_root) {
9352 rc = MDB_INCOMPATIBLE; /* page leak or corrupt DB */
9358 mdb_env_cthr_toggle(&my, 1 | MDB_EOF);
9359 rc = THREAD_FINISH(thr);
9364 if (my.mc_wbuf[0]) _aligned_free(my.mc_wbuf[0]);
9365 if (my.mc_cond) CloseHandle(my.mc_cond);
9366 if (my.mc_mutex) CloseHandle(my.mc_mutex);
9368 free(my.mc_wbuf[0]);
9369 pthread_cond_destroy(&my.mc_cond);
9371 pthread_mutex_destroy(&my.mc_mutex);
9373 return rc ? rc : my.mc_error;
9376 /** Copy environment as-is. */
9378 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
9380 MDB_txn *txn = NULL;
9381 mdb_mutexref_t wmutex = NULL;
9387 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9391 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9394 /* Do the lock/unlock of the reader mutex before starting the
9395 * write txn. Otherwise other read txns could block writers.
9397 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9402 /* We must start the actual read txn after blocking writers */
9403 mdb_txn_end(txn, MDB_END_RESET_TMP);
9405 /* Temporarily block writers until we snapshot the meta pages */
9406 wmutex = env->me_wmutex;
9407 if (LOCK_MUTEX(rc, env, wmutex))
9410 rc = mdb_txn_renew0(txn);
9412 UNLOCK_MUTEX(wmutex);
9417 wsize = env->me_psize * NUM_METAS;
9421 DO_WRITE(rc, fd, ptr, w2, len);
9425 } else if (len > 0) {
9431 /* Non-blocking or async handles are not supported */
9437 UNLOCK_MUTEX(wmutex);
9442 w3 = txn->mt_next_pgno * env->me_psize;
9445 if ((rc = mdb_fsize(env->me_fd, &fsize)))
9452 if (wsize > MAX_WRITE)
9456 DO_WRITE(rc, fd, ptr, w2, len);
9460 } else if (len > 0) {
9477 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
9479 if (flags & MDB_CP_COMPACT)
9480 return mdb_env_copyfd1(env, fd);
9482 return mdb_env_copyfd0(env, fd);
9486 mdb_env_copyfd(MDB_env *env, HANDLE fd)
9488 return mdb_env_copyfd2(env, fd, 0);
9492 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
9496 HANDLE newfd = INVALID_HANDLE_VALUE;
9498 rc = mdb_fname_init(path, env->me_flags | MDB_NOLOCK, &fname);
9499 if (rc == MDB_SUCCESS) {
9500 rc = mdb_fopen(env, &fname, MDB_O_COPY, 0666, &newfd);
9501 mdb_fname_destroy(fname);
9503 if (rc == MDB_SUCCESS) {
9504 rc = mdb_env_copyfd2(env, newfd, flags);
9505 if (close(newfd) < 0 && rc == MDB_SUCCESS)
9512 mdb_env_copy(MDB_env *env, const char *path)
9514 return mdb_env_copy2(env, path, 0);
9518 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
9520 if (flag & ~CHANGEABLE)
9523 env->me_flags |= flag;
9525 env->me_flags &= ~flag;
9530 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
9535 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
9540 mdb_env_set_userctx(MDB_env *env, void *ctx)
9544 env->me_userctx = ctx;
9549 mdb_env_get_userctx(MDB_env *env)
9551 return env ? env->me_userctx : NULL;
9555 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
9560 env->me_assert_func = func;
9566 mdb_env_get_path(MDB_env *env, const char **arg)
9571 *arg = env->me_path;
9576 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
9585 /** Common code for #mdb_stat() and #mdb_env_stat().
9586 * @param[in] env the environment to operate in.
9587 * @param[in] db the #MDB_db record containing the stats to return.
9588 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
9589 * @return 0, this function always succeeds.
9592 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
9594 arg->ms_psize = env->me_psize;
9595 arg->ms_depth = db->md_depth;
9596 arg->ms_branch_pages = db->md_branch_pages;
9597 arg->ms_leaf_pages = db->md_leaf_pages;
9598 arg->ms_overflow_pages = db->md_overflow_pages;
9599 arg->ms_entries = db->md_entries;
9605 mdb_env_stat(MDB_env *env, MDB_stat *arg)
9609 if (env == NULL || arg == NULL)
9612 meta = mdb_env_pick_meta(env);
9614 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
9618 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
9622 if (env == NULL || arg == NULL)
9625 meta = mdb_env_pick_meta(env);
9626 arg->me_mapaddr = meta->mm_address;
9627 arg->me_last_pgno = meta->mm_last_pg;
9628 arg->me_last_txnid = meta->mm_txnid;
9630 arg->me_mapsize = env->me_mapsize;
9631 arg->me_maxreaders = env->me_maxreaders;
9632 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
9636 /** Set the default comparison functions for a database.
9637 * Called immediately after a database is opened to set the defaults.
9638 * The user can then override them with #mdb_set_compare() or
9639 * #mdb_set_dupsort().
9640 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
9641 * @param[in] dbi A database handle returned by #mdb_dbi_open()
9644 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
9646 uint16_t f = txn->mt_dbs[dbi].md_flags;
9648 txn->mt_dbxs[dbi].md_cmp =
9649 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
9650 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
9652 txn->mt_dbxs[dbi].md_dcmp =
9653 !(f & MDB_DUPSORT) ? 0 :
9654 ((f & MDB_INTEGERDUP)
9655 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
9656 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
9659 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
9665 int rc, dbflag, exact;
9666 unsigned int unused = 0, seq;
9670 if (flags & ~VALID_FLAGS)
9672 if (txn->mt_flags & MDB_TXN_BLOCKED)
9678 if (flags & PERSISTENT_FLAGS) {
9679 uint16_t f2 = flags & PERSISTENT_FLAGS;
9680 /* make sure flag changes get committed */
9681 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
9682 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
9683 txn->mt_flags |= MDB_TXN_DIRTY;
9686 mdb_default_cmp(txn, MAIN_DBI);
9690 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
9691 mdb_default_cmp(txn, MAIN_DBI);
9694 /* Is the DB already open? */
9696 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
9697 if (!txn->mt_dbxs[i].md_name.mv_size) {
9698 /* Remember this free slot */
9699 if (!unused) unused = i;
9702 if (len == txn->mt_dbxs[i].md_name.mv_size &&
9703 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
9709 /* If no free slot and max hit, fail */
9710 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
9711 return MDB_DBS_FULL;
9713 /* Cannot mix named databases with some mainDB flags */
9714 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
9715 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
9717 /* Find the DB info */
9718 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
9721 key.mv_data = (void *)name;
9722 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
9723 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
9724 if (rc == MDB_SUCCESS) {
9725 /* make sure this is actually a DB */
9726 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
9727 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
9728 return MDB_INCOMPATIBLE;
9729 } else if (! (rc == MDB_NOTFOUND && (flags & MDB_CREATE))) {
9733 /* Done here so we cannot fail after creating a new DB */
9734 if ((namedup = strdup(name)) == NULL)
9738 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
9739 data.mv_size = sizeof(MDB_db);
9740 data.mv_data = &dummy;
9741 memset(&dummy, 0, sizeof(dummy));
9742 dummy.md_root = P_INVALID;
9743 dummy.md_flags = flags & PERSISTENT_FLAGS;
9744 WITH_CURSOR_TRACKING(mc,
9745 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA));
9752 /* Got info, register DBI in this txn */
9753 unsigned int slot = unused ? unused : txn->mt_numdbs;
9754 txn->mt_dbxs[slot].md_name.mv_data = namedup;
9755 txn->mt_dbxs[slot].md_name.mv_size = len;
9756 txn->mt_dbxs[slot].md_rel = NULL;
9757 txn->mt_dbflags[slot] = dbflag;
9758 /* txn-> and env-> are the same in read txns, use
9759 * tmp variable to avoid undefined assignment
9761 seq = ++txn->mt_env->me_dbiseqs[slot];
9762 txn->mt_dbiseqs[slot] = seq;
9764 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
9766 mdb_default_cmp(txn, slot);
9776 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9778 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
9781 if (txn->mt_flags & MDB_TXN_BLOCKED)
9784 if (txn->mt_dbflags[dbi] & DB_STALE) {
9787 /* Stale, must read the DB's root. cursor_init does it for us. */
9788 mdb_cursor_init(&mc, txn, dbi, &mx);
9790 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9793 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9796 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
9798 ptr = env->me_dbxs[dbi].md_name.mv_data;
9799 /* If there was no name, this was already closed */
9801 env->me_dbxs[dbi].md_name.mv_data = NULL;
9802 env->me_dbxs[dbi].md_name.mv_size = 0;
9803 env->me_dbflags[dbi] = 0;
9804 env->me_dbiseqs[dbi]++;
9809 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9811 /* We could return the flags for the FREE_DBI too but what's the point? */
9812 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9814 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9818 /** Add all the DB's pages to the free list.
9819 * @param[in] mc Cursor on the DB to free.
9820 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9821 * @return 0 on success, non-zero on failure.
9824 mdb_drop0(MDB_cursor *mc, int subs)
9828 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9829 if (rc == MDB_SUCCESS) {
9830 MDB_txn *txn = mc->mc_txn;
9835 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
9836 * This also avoids any P_LEAF2 pages, which have no nodes.
9837 * Also if the DB doesn't have sub-DBs and has no overflow
9838 * pages, omit scanning leaves.
9840 if ((mc->mc_flags & C_SUB) ||
9841 (!subs && !mc->mc_db->md_overflow_pages))
9844 mdb_cursor_copy(mc, &mx);
9845 while (mc->mc_snum > 0) {
9846 MDB_page *mp = mc->mc_pg[mc->mc_top];
9847 unsigned n = NUMKEYS(mp);
9849 for (i=0; i<n; i++) {
9850 ni = NODEPTR(mp, i);
9851 if (ni->mn_flags & F_BIGDATA) {
9854 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9855 rc = mdb_page_get(mc, pg, &omp, NULL);
9858 mdb_cassert(mc, IS_OVERFLOW(omp));
9859 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9863 mc->mc_db->md_overflow_pages -= omp->mp_pages;
9864 if (!mc->mc_db->md_overflow_pages && !subs)
9866 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9867 mdb_xcursor_init1(mc, ni);
9868 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9873 if (!subs && !mc->mc_db->md_overflow_pages)
9876 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9878 for (i=0; i<n; i++) {
9880 ni = NODEPTR(mp, i);
9883 mdb_midl_xappend(txn->mt_free_pgs, pg);
9888 mc->mc_ki[mc->mc_top] = i;
9889 rc = mdb_cursor_sibling(mc, 1);
9891 if (rc != MDB_NOTFOUND)
9893 /* no more siblings, go back to beginning
9894 * of previous level.
9899 for (i=1; i<mc->mc_snum; i++) {
9901 mc->mc_pg[i] = mx.mc_pg[i];
9906 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9909 txn->mt_flags |= MDB_TXN_ERROR;
9910 } else if (rc == MDB_NOTFOUND) {
9913 mc->mc_flags &= ~C_INITIALIZED;
9917 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9919 MDB_cursor *mc, *m2;
9922 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9925 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9928 if (TXN_DBI_CHANGED(txn, dbi))
9931 rc = mdb_cursor_open(txn, dbi, &mc);
9935 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9936 /* Invalidate the dropped DB's cursors */
9937 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9938 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9942 /* Can't delete the main DB */
9943 if (del && dbi >= CORE_DBS) {
9944 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
9946 txn->mt_dbflags[dbi] = DB_STALE;
9947 mdb_dbi_close(txn->mt_env, dbi);
9949 txn->mt_flags |= MDB_TXN_ERROR;
9952 /* reset the DB record, mark it dirty */
9953 txn->mt_dbflags[dbi] |= DB_DIRTY;
9954 txn->mt_dbs[dbi].md_depth = 0;
9955 txn->mt_dbs[dbi].md_branch_pages = 0;
9956 txn->mt_dbs[dbi].md_leaf_pages = 0;
9957 txn->mt_dbs[dbi].md_overflow_pages = 0;
9958 txn->mt_dbs[dbi].md_entries = 0;
9959 txn->mt_dbs[dbi].md_root = P_INVALID;
9961 txn->mt_flags |= MDB_TXN_DIRTY;
9964 mdb_cursor_close(mc);
9968 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9970 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9973 txn->mt_dbxs[dbi].md_cmp = cmp;
9977 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9979 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9982 txn->mt_dbxs[dbi].md_dcmp = cmp;
9986 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9988 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9991 txn->mt_dbxs[dbi].md_rel = rel;
9995 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9997 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10000 txn->mt_dbxs[dbi].md_relctx = ctx;
10001 return MDB_SUCCESS;
10005 mdb_env_get_maxkeysize(MDB_env *env)
10007 return ENV_MAXKEY(env);
10011 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
10013 unsigned int i, rdrs;
10016 int rc = 0, first = 1;
10020 if (!env->me_txns) {
10021 return func("(no reader locks)\n", ctx);
10023 rdrs = env->me_txns->mti_numreaders;
10024 mr = env->me_txns->mti_readers;
10025 for (i=0; i<rdrs; i++) {
10026 if (mr[i].mr_pid) {
10027 txnid_t txnid = mr[i].mr_txnid;
10028 sprintf(buf, txnid == (txnid_t)-1 ?
10029 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
10030 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
10033 rc = func(" pid thread txnid\n", ctx);
10037 rc = func(buf, ctx);
10043 rc = func("(no active readers)\n", ctx);
10048 /** Insert pid into list if not already present.
10049 * return -1 if already present.
10052 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
10054 /* binary search of pid in list */
10056 unsigned cursor = 1;
10058 unsigned n = ids[0];
10061 unsigned pivot = n >> 1;
10062 cursor = base + pivot + 1;
10063 val = pid - ids[cursor];
10068 } else if ( val > 0 ) {
10073 /* found, so it's a duplicate */
10082 for (n = ids[0]; n > cursor; n--)
10089 mdb_reader_check(MDB_env *env, int *dead)
10095 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
10098 /** As #mdb_reader_check(). \b rlocked is set if caller locked #me_rmutex. */
10100 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
10102 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
10103 unsigned int i, j, rdrs;
10105 MDB_PID_T *pids, pid;
10106 int rc = MDB_SUCCESS, count = 0;
10108 rdrs = env->me_txns->mti_numreaders;
10109 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
10113 mr = env->me_txns->mti_readers;
10114 for (i=0; i<rdrs; i++) {
10115 pid = mr[i].mr_pid;
10116 if (pid && pid != env->me_pid) {
10117 if (mdb_pid_insert(pids, pid) == 0) {
10118 if (!mdb_reader_pid(env, Pidcheck, pid)) {
10119 /* Stale reader found */
10122 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
10123 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
10125 rdrs = 0; /* the above checked all readers */
10127 /* Recheck, a new process may have reused pid */
10128 if (mdb_reader_pid(env, Pidcheck, pid))
10132 for (; j<rdrs; j++)
10133 if (mr[j].mr_pid == pid) {
10134 DPRINTF(("clear stale reader pid %u txn %"Z"d",
10135 (unsigned) pid, mr[j].mr_txnid));
10140 UNLOCK_MUTEX(rmutex);
10151 #ifdef MDB_ROBUST_SUPPORTED
10152 /** Handle #LOCK_MUTEX0() failure.
10153 * Try to repair the lock file if the mutex owner died.
10154 * @param[in] env the environment handle
10155 * @param[in] mutex LOCK_MUTEX0() mutex
10156 * @param[in] rc LOCK_MUTEX0() error (nonzero)
10157 * @return 0 on success with the mutex locked, or an error code on failure.
10160 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10165 if (rc == MDB_OWNERDEAD) {
10166 /* We own the mutex. Clean up after dead previous owner. */
10168 rlocked = (mutex == env->me_rmutex);
10170 /* Keep mti_txnid updated, otherwise next writer can
10171 * overwrite data which latest meta page refers to.
10173 meta = mdb_env_pick_meta(env);
10174 env->me_txns->mti_txnid = meta->mm_txnid;
10175 /* env is hosed if the dead thread was ours */
10177 env->me_flags |= MDB_FATAL_ERROR;
10178 env->me_txn = NULL;
10182 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
10183 (rc ? "this process' env is hosed" : "recovering")));
10184 rc2 = mdb_reader_check0(env, rlocked, NULL);
10186 rc2 = mdb_mutex_consistent(mutex);
10187 if (rc || (rc = rc2)) {
10188 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
10189 UNLOCK_MUTEX(mutex);
10195 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
10200 #endif /* MDB_ROBUST_SUPPORTED */
10202 #if defined(_WIN32)
10203 /** Convert \b src to new wchar_t[] string with room for \b xtra extra chars */
10205 utf8_to_utf16(const char *src, MDB_name *dst, int xtra)
10208 wchar_t *result = NULL;
10209 for (;;) { /* malloc result, then fill it in */
10210 need = MultiByteToWideChar(CP_UTF8, 0, src, -1, result, need);
10217 result = malloc(sizeof(wchar_t) * (need + xtra));
10222 dst->mn_alloced = 1;
10223 dst->mn_len = need - 1;
10224 dst->mn_val = result;
10225 return MDB_SUCCESS;
10228 #endif /* defined(_WIN32) */