2 * @brief Lightning memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2017 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
38 #if defined(__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
116 /* On Solaris, we need the POSIX sigwait function */
118 # define _POSIX_PTHREAD_SEMANTICS 1
122 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
123 #include <netinet/in.h>
124 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
127 #if defined(__APPLE__) || defined (BSD) || defined(__FreeBSD_kernel__)
128 # define MDB_USE_POSIX_SEM 1
129 # define MDB_FDATASYNC fsync
130 #elif defined(ANDROID)
131 # define MDB_FDATASYNC fsync
137 #ifdef MDB_USE_POSIX_SEM
138 # define MDB_USE_HASH 1
139 #include <semaphore.h>
141 #define MDB_USE_POSIX_MUTEX 1
145 #if defined(_WIN32) + defined(MDB_USE_POSIX_SEM) \
146 + defined(MDB_USE_POSIX_MUTEX) != 1
147 # error "Ambiguous shared-lock implementation"
151 #include <valgrind/memcheck.h>
152 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
153 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
154 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
155 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
156 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
158 #define VGMEMP_CREATE(h,r,z)
159 #define VGMEMP_ALLOC(h,a,s)
160 #define VGMEMP_FREE(h,a)
161 #define VGMEMP_DESTROY(h)
162 #define VGMEMP_DEFINED(a,s)
166 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
167 /* Solaris just defines one or the other */
168 # define LITTLE_ENDIAN 1234
169 # define BIG_ENDIAN 4321
170 # ifdef _LITTLE_ENDIAN
171 # define BYTE_ORDER LITTLE_ENDIAN
173 # define BYTE_ORDER BIG_ENDIAN
176 # define BYTE_ORDER __BYTE_ORDER
180 #ifndef LITTLE_ENDIAN
181 #define LITTLE_ENDIAN __LITTLE_ENDIAN
184 #define BIG_ENDIAN __BIG_ENDIAN
187 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
188 #define MISALIGNED_OK 1
194 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
195 # error "Unknown or unsupported endianness (BYTE_ORDER)"
196 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
197 # error "Two's complement, reasonably sized integer types, please"
201 /** Put infrequently used env functions in separate section */
203 # define ESECT __attribute__ ((section("__TEXT,text_env")))
205 # define ESECT __attribute__ ((section("text_env")))
212 #define CALL_CONV WINAPI
217 /** @defgroup internal LMDB Internals
220 /** @defgroup compat Compatibility Macros
221 * A bunch of macros to minimize the amount of platform-specific ifdefs
222 * needed throughout the rest of the code. When the features this library
223 * needs are similar enough to POSIX to be hidden in a one-or-two line
224 * replacement, this macro approach is used.
228 /** Features under development */
233 /** Wrapper around __func__, which is a C99 feature */
234 #if __STDC_VERSION__ >= 199901L
235 # define mdb_func_ __func__
236 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
237 # define mdb_func_ __FUNCTION__
239 /* If a debug message says <mdb_unknown>(), update the #if statements above */
240 # define mdb_func_ "<mdb_unknown>"
243 /* Internal error codes, not exposed outside liblmdb */
244 #define MDB_NO_ROOT (MDB_LAST_ERRCODE + 10)
246 #define MDB_OWNERDEAD ((int) WAIT_ABANDONED)
247 #elif defined(MDB_USE_POSIX_MUTEX) && defined(EOWNERDEAD)
248 #define MDB_OWNERDEAD EOWNERDEAD /**< #LOCK_MUTEX0() result if dead owner */
252 #define GLIBC_VER ((__GLIBC__ << 16 )| __GLIBC_MINOR__)
254 /** Some platforms define the EOWNERDEAD error code
255 * even though they don't support Robust Mutexes.
256 * Compile with -DMDB_USE_ROBUST=0, or use some other
257 * mechanism like -DMDB_USE_POSIX_SEM instead of
258 * -DMDB_USE_POSIX_MUTEX.
259 * (Posix semaphores are not robust.)
261 #ifndef MDB_USE_ROBUST
262 /* Android currently lacks Robust Mutex support. So does glibc < 2.4. */
263 # if defined(MDB_USE_POSIX_MUTEX) && (defined(ANDROID) || \
264 (defined(__GLIBC__) && GLIBC_VER < 0x020004))
265 # define MDB_USE_ROBUST 0
267 # define MDB_USE_ROBUST 1
269 #endif /* !MDB_USE_ROBUST */
271 #if defined(MDB_USE_POSIX_MUTEX) && (MDB_USE_ROBUST)
272 /* glibc < 2.12 only provided _np API */
273 # if (defined(__GLIBC__) && GLIBC_VER < 0x02000c) || \
274 (defined(PTHREAD_MUTEX_ROBUST_NP) && !defined(PTHREAD_MUTEX_ROBUST))
275 # define PTHREAD_MUTEX_ROBUST PTHREAD_MUTEX_ROBUST_NP
276 # define pthread_mutexattr_setrobust(attr, flag) pthread_mutexattr_setrobust_np(attr, flag)
277 # define pthread_mutex_consistent(mutex) pthread_mutex_consistent_np(mutex)
279 #endif /* MDB_USE_POSIX_MUTEX && MDB_USE_ROBUST */
281 #if defined(MDB_OWNERDEAD) && (MDB_USE_ROBUST)
282 #define MDB_ROBUST_SUPPORTED 1
286 #define MDB_USE_HASH 1
287 #define MDB_PIDLOCK 0
288 #define THREAD_RET DWORD
289 #define pthread_t HANDLE
290 #define pthread_mutex_t HANDLE
291 #define pthread_cond_t HANDLE
292 typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
293 #define pthread_key_t DWORD
294 #define pthread_self() GetCurrentThreadId()
295 #define pthread_key_create(x,y) \
296 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
297 #define pthread_key_delete(x) TlsFree(x)
298 #define pthread_getspecific(x) TlsGetValue(x)
299 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
300 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
301 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
302 #define pthread_cond_signal(x) SetEvent(*x)
303 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
304 #define THREAD_CREATE(thr,start,arg) \
305 (((thr) = CreateThread(NULL, 0, start, arg, 0, NULL)) ? 0 : ErrCode())
306 #define THREAD_FINISH(thr) \
307 (WaitForSingleObject(thr, INFINITE) ? ErrCode() : 0)
308 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
309 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
310 #define mdb_mutex_consistent(mutex) 0
311 #define getpid() GetCurrentProcessId()
312 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
313 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
314 #define ErrCode() GetLastError()
315 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
316 #define close(fd) (CloseHandle(fd) ? 0 : -1)
317 #define munmap(ptr,len) UnmapViewOfFile(ptr)
318 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
319 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
321 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
325 #define THREAD_RET void *
326 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
327 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
328 #define Z "z" /**< printf format modifier for size_t */
330 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
331 #define MDB_PIDLOCK 1
333 #ifdef MDB_USE_POSIX_SEM
335 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
336 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
337 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
340 mdb_sem_wait(sem_t *sem)
343 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
347 #else /* MDB_USE_POSIX_MUTEX: */
348 /** Shared mutex/semaphore as the original is stored.
350 * Not for copies. Instead it can be assigned to an #mdb_mutexref_t.
351 * When mdb_mutexref_t is a pointer and mdb_mutex_t is not, then it
352 * is array[size 1] so it can be assigned to the pointer.
354 typedef pthread_mutex_t mdb_mutex_t[1];
355 /** Reference to an #mdb_mutex_t */
356 typedef pthread_mutex_t *mdb_mutexref_t;
357 /** Lock the reader or writer mutex.
358 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
360 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
361 /** Unlock the reader or writer mutex.
363 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
364 /** Mark mutex-protected data as repaired, after death of previous owner.
366 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
367 #endif /* MDB_USE_POSIX_SEM */
369 /** Get the error code for the last failed system function.
371 #define ErrCode() errno
373 /** An abstraction for a file handle.
374 * On POSIX systems file handles are small integers. On Windows
375 * they're opaque pointers.
379 /** A value for an invalid file handle.
380 * Mainly used to initialize file variables and signify that they are
383 #define INVALID_HANDLE_VALUE (-1)
385 /** Get the size of a memory page for the system.
386 * This is the basic size that the platform's memory manager uses, and is
387 * fundamental to the use of memory-mapped files.
389 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
392 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
395 #define MNAME_LEN (sizeof(pthread_mutex_t))
400 #ifdef MDB_ROBUST_SUPPORTED
401 /** Lock mutex, handle any error, set rc = result.
402 * Return 0 on success, nonzero (not rc) on error.
404 #define LOCK_MUTEX(rc, env, mutex) \
405 (((rc) = LOCK_MUTEX0(mutex)) && \
406 ((rc) = mdb_mutex_failed(env, mutex, rc)))
407 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
409 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
410 #define mdb_mutex_failed(env, mutex, rc) (rc)
414 /** A flag for opening a file and requesting synchronous data writes.
415 * This is only used when writing a meta page. It's not strictly needed;
416 * we could just do a normal write and then immediately perform a flush.
417 * But if this flag is available it saves us an extra system call.
419 * @note If O_DSYNC is undefined but exists in /usr/include,
420 * preferably set some compiler flag to get the definition.
424 # define MDB_DSYNC O_DSYNC
426 # define MDB_DSYNC O_SYNC
431 /** Function for flushing the data of a file. Define this to fsync
432 * if fdatasync() is not supported.
434 #ifndef MDB_FDATASYNC
435 # define MDB_FDATASYNC fdatasync
439 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
450 /** A page number in the database.
451 * Note that 64 bit page numbers are overkill, since pages themselves
452 * already represent 12-13 bits of addressable memory, and the OS will
453 * always limit applications to a maximum of 63 bits of address space.
455 * @note In the #MDB_node structure, we only store 48 bits of this value,
456 * which thus limits us to only 60 bits of addressable data.
458 typedef MDB_ID pgno_t;
460 /** A transaction ID.
461 * See struct MDB_txn.mt_txnid for details.
463 typedef MDB_ID txnid_t;
465 /** @defgroup debug Debug Macros
469 /** Enable debug output. Needs variable argument macros (a C99 feature).
470 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
471 * read from and written to the database (used for free space management).
477 static int mdb_debug;
478 static txnid_t mdb_debug_start;
480 /** Print a debug message with printf formatting.
481 * Requires double parenthesis around 2 or more args.
483 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
484 # define DPRINTF0(fmt, ...) \
485 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
487 # define DPRINTF(args) ((void) 0)
489 /** Print a debug string.
490 * The string is printed literally, with no format processing.
492 #define DPUTS(arg) DPRINTF(("%s", arg))
493 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
495 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
498 /** @brief The maximum size of a database page.
500 * It is 32k or 64k, since value-PAGEBASE must fit in
501 * #MDB_page.%mp_upper.
503 * LMDB will use database pages < OS pages if needed.
504 * That causes more I/O in write transactions: The OS must
505 * know (read) the whole page before writing a partial page.
507 * Note that we don't currently support Huge pages. On Linux,
508 * regular data files cannot use Huge pages, and in general
509 * Huge pages aren't actually pageable. We rely on the OS
510 * demand-pager to read our data and page it out when memory
511 * pressure from other processes is high. So until OSs have
512 * actual paging support for Huge pages, they're not viable.
514 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
516 /** The minimum number of keys required in a database page.
517 * Setting this to a larger value will place a smaller bound on the
518 * maximum size of a data item. Data items larger than this size will
519 * be pushed into overflow pages instead of being stored directly in
520 * the B-tree node. This value used to default to 4. With a page size
521 * of 4096 bytes that meant that any item larger than 1024 bytes would
522 * go into an overflow page. That also meant that on average 2-3KB of
523 * each overflow page was wasted space. The value cannot be lower than
524 * 2 because then there would no longer be a tree structure. With this
525 * value, items larger than 2KB will go into overflow pages, and on
526 * average only 1KB will be wasted.
528 #define MDB_MINKEYS 2
530 /** A stamp that identifies a file as an LMDB file.
531 * There's nothing special about this value other than that it is easily
532 * recognizable, and it will reflect any byte order mismatches.
534 #define MDB_MAGIC 0xBEEFC0DE
536 /** The version number for a database's datafile format. */
537 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
538 /** The version number for a database's lockfile format. */
539 #define MDB_LOCK_VERSION 1
541 /** @brief The max size of a key we can write, or 0 for computed max.
543 * This macro should normally be left alone or set to 0.
544 * Note that a database with big keys or dupsort data cannot be
545 * reliably modified by a liblmdb which uses a smaller max.
546 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
548 * Other values are allowed, for backwards compat. However:
549 * A value bigger than the computed max can break if you do not
550 * know what you are doing, and liblmdb <= 0.9.10 can break when
551 * modifying a DB with keys/dupsort data bigger than its max.
553 * Data items in an #MDB_DUPSORT database are also limited to
554 * this size, since they're actually keys of a sub-DB. Keys and
555 * #MDB_DUPSORT data items must fit on a node in a regular page.
557 #ifndef MDB_MAXKEYSIZE
558 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
561 /** The maximum size of a key we can write to the environment. */
563 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
565 #define ENV_MAXKEY(env) ((env)->me_maxkey)
568 /** @brief The maximum size of a data item.
570 * We only store a 32 bit value for node sizes.
572 #define MAXDATASIZE 0xffffffffUL
575 /** Key size which fits in a #DKBUF.
578 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
581 * This is used for printing a hex dump of a key's contents.
583 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
584 /** Display a key in hex.
586 * Invoke a function to display a key in hex.
588 #define DKEY(x) mdb_dkey(x, kbuf)
594 /** An invalid page number.
595 * Mainly used to denote an empty tree.
597 #define P_INVALID (~(pgno_t)0)
599 /** Test if the flags \b f are set in a flag word \b w. */
600 #define F_ISSET(w, f) (((w) & (f)) == (f))
602 /** Round \b n up to an even number. */
603 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
605 /** Used for offsets within a single page.
606 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
609 typedef uint16_t indx_t;
611 /** Default size of memory map.
612 * This is certainly too small for any actual applications. Apps should always set
613 * the size explicitly using #mdb_env_set_mapsize().
615 #define DEFAULT_MAPSIZE 1048576
617 /** @defgroup readers Reader Lock Table
618 * Readers don't acquire any locks for their data access. Instead, they
619 * simply record their transaction ID in the reader table. The reader
620 * mutex is needed just to find an empty slot in the reader table. The
621 * slot's address is saved in thread-specific data so that subsequent read
622 * transactions started by the same thread need no further locking to proceed.
624 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
626 * No reader table is used if the database is on a read-only filesystem, or
627 * if #MDB_NOLOCK is set.
629 * Since the database uses multi-version concurrency control, readers don't
630 * actually need any locking. This table is used to keep track of which
631 * readers are using data from which old transactions, so that we'll know
632 * when a particular old transaction is no longer in use. Old transactions
633 * that have discarded any data pages can then have those pages reclaimed
634 * for use by a later write transaction.
636 * The lock table is constructed such that reader slots are aligned with the
637 * processor's cache line size. Any slot is only ever used by one thread.
638 * This alignment guarantees that there will be no contention or cache
639 * thrashing as threads update their own slot info, and also eliminates
640 * any need for locking when accessing a slot.
642 * A writer thread will scan every slot in the table to determine the oldest
643 * outstanding reader transaction. Any freed pages older than this will be
644 * reclaimed by the writer. The writer doesn't use any locks when scanning
645 * this table. This means that there's no guarantee that the writer will
646 * see the most up-to-date reader info, but that's not required for correct
647 * operation - all we need is to know the upper bound on the oldest reader,
648 * we don't care at all about the newest reader. So the only consequence of
649 * reading stale information here is that old pages might hang around a
650 * while longer before being reclaimed. That's actually good anyway, because
651 * the longer we delay reclaiming old pages, the more likely it is that a
652 * string of contiguous pages can be found after coalescing old pages from
653 * many old transactions together.
656 /** Number of slots in the reader table.
657 * This value was chosen somewhat arbitrarily. 126 readers plus a
658 * couple mutexes fit exactly into 8KB on my development machine.
659 * Applications should set the table size using #mdb_env_set_maxreaders().
661 #define DEFAULT_READERS 126
663 /** The size of a CPU cache line in bytes. We want our lock structures
664 * aligned to this size to avoid false cache line sharing in the
666 * This value works for most CPUs. For Itanium this should be 128.
672 /** The information we store in a single slot of the reader table.
673 * In addition to a transaction ID, we also record the process and
674 * thread ID that owns a slot, so that we can detect stale information,
675 * e.g. threads or processes that went away without cleaning up.
676 * @note We currently don't check for stale records. We simply re-init
677 * the table when we know that we're the only process opening the
680 typedef struct MDB_rxbody {
681 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
682 * Multiple readers that start at the same time will probably have the
683 * same ID here. Again, it's not important to exclude them from
684 * anything; all we need to know is which version of the DB they
685 * started from so we can avoid overwriting any data used in that
686 * particular version.
688 volatile txnid_t mrb_txnid;
689 /** The process ID of the process owning this reader txn. */
690 volatile MDB_PID_T mrb_pid;
691 /** The thread ID of the thread owning this txn. */
692 volatile MDB_THR_T mrb_tid;
695 /** The actual reader record, with cacheline padding. */
696 typedef struct MDB_reader {
699 /** shorthand for mrb_txnid */
700 #define mr_txnid mru.mrx.mrb_txnid
701 #define mr_pid mru.mrx.mrb_pid
702 #define mr_tid mru.mrx.mrb_tid
703 /** cache line alignment */
704 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
708 /** The header for the reader table.
709 * The table resides in a memory-mapped file. (This is a different file
710 * than is used for the main database.)
712 * For POSIX the actual mutexes reside in the shared memory of this
713 * mapped file. On Windows, mutexes are named objects allocated by the
714 * kernel; we store the mutex names in this mapped file so that other
715 * processes can grab them. This same approach is also used on
716 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
717 * process-shared POSIX mutexes. For these cases where a named object
718 * is used, the object name is derived from a 64 bit FNV hash of the
719 * environment pathname. As such, naming collisions are extremely
720 * unlikely. If a collision occurs, the results are unpredictable.
722 typedef struct MDB_txbody {
723 /** Stamp identifying this as an LMDB file. It must be set
726 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
728 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
729 char mtb_rmname[MNAME_LEN];
731 /** Mutex protecting access to this table.
732 * This is the reader table lock used with LOCK_MUTEX().
734 mdb_mutex_t mtb_rmutex;
736 /** The ID of the last transaction committed to the database.
737 * This is recorded here only for convenience; the value can always
738 * be determined by reading the main database meta pages.
740 volatile txnid_t mtb_txnid;
741 /** The number of slots that have been used in the reader table.
742 * This always records the maximum count, it is not decremented
743 * when readers release their slots.
745 volatile unsigned mtb_numreaders;
748 /** The actual reader table definition. */
749 typedef struct MDB_txninfo {
752 #define mti_magic mt1.mtb.mtb_magic
753 #define mti_format mt1.mtb.mtb_format
754 #define mti_rmutex mt1.mtb.mtb_rmutex
755 #define mti_rmname mt1.mtb.mtb_rmname
756 #define mti_txnid mt1.mtb.mtb_txnid
757 #define mti_numreaders mt1.mtb.mtb_numreaders
758 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
761 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
762 char mt2_wmname[MNAME_LEN];
763 #define mti_wmname mt2.mt2_wmname
765 mdb_mutex_t mt2_wmutex;
766 #define mti_wmutex mt2.mt2_wmutex
768 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
770 MDB_reader mti_readers[1];
773 /** Lockfile format signature: version, features and field layout */
774 #define MDB_LOCK_FORMAT \
776 ((MDB_LOCK_VERSION) \
777 /* Flags which describe functionality */ \
778 + (((MDB_PIDLOCK) != 0) << 16)))
781 /** Common header for all page types. The page type depends on #mp_flags.
783 * #P_BRANCH and #P_LEAF pages have unsorted '#MDB_node's at the end, with
784 * sorted #mp_ptrs[] entries referring to them. Exception: #P_LEAF2 pages
785 * omit mp_ptrs and pack sorted #MDB_DUPFIXED values after the page header.
787 * #P_OVERFLOW records occupy one or more contiguous pages where only the
788 * first has a page header. They hold the real data of #F_BIGDATA nodes.
790 * #P_SUBP sub-pages are small leaf "pages" with duplicate data.
791 * A node with flag #F_DUPDATA but not #F_SUBDATA contains a sub-page.
792 * (Duplicate data can also go in sub-databases, which use normal pages.)
794 * #P_META pages contain #MDB_meta, the start point of an LMDB snapshot.
796 * Each non-metapage up to #MDB_meta.%mm_last_pg is reachable exactly once
797 * in the snapshot: Either used by a database or listed in a freeDB record.
799 typedef struct MDB_page {
800 #define mp_pgno mp_p.p_pgno
801 #define mp_next mp_p.p_next
803 pgno_t p_pgno; /**< page number */
804 struct MDB_page *p_next; /**< for in-memory list of freed pages */
806 uint16_t mp_pad; /**< key size if this is a LEAF2 page */
807 /** @defgroup mdb_page Page Flags
809 * Flags for the page headers.
812 #define P_BRANCH 0x01 /**< branch page */
813 #define P_LEAF 0x02 /**< leaf page */
814 #define P_OVERFLOW 0x04 /**< overflow page */
815 #define P_META 0x08 /**< meta page */
816 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
817 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
818 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
819 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
820 #define P_KEEP 0x8000 /**< leave this page alone during spill */
822 uint16_t mp_flags; /**< @ref mdb_page */
823 #define mp_lower mp_pb.pb.pb_lower
824 #define mp_upper mp_pb.pb.pb_upper
825 #define mp_pages mp_pb.pb_pages
828 indx_t pb_lower; /**< lower bound of free space */
829 indx_t pb_upper; /**< upper bound of free space */
831 uint32_t pb_pages; /**< number of overflow pages */
833 indx_t mp_ptrs[1]; /**< dynamic size */
836 /** Size of the page header, excluding dynamic data at the end */
837 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
839 /** Address of first usable data byte in a page, after the header */
840 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
842 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
843 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
845 /** Number of nodes on a page */
846 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
848 /** The amount of space remaining in the page */
849 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
851 /** The percentage of space used in the page, in tenths of a percent. */
852 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
853 ((env)->me_psize - PAGEHDRSZ))
854 /** The minimum page fill factor, in tenths of a percent.
855 * Pages emptier than this are candidates for merging.
857 #define FILL_THRESHOLD 250
859 /** Test if a page is a leaf page */
860 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
861 /** Test if a page is a LEAF2 page */
862 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
863 /** Test if a page is a branch page */
864 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
865 /** Test if a page is an overflow page */
866 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
867 /** Test if a page is a sub page */
868 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
870 /** The number of overflow pages needed to store the given size. */
871 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
873 /** Link in #MDB_txn.%mt_loose_pgs list.
874 * Kept outside the page header, which is needed when reusing the page.
876 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
878 /** Header for a single key/data pair within a page.
879 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
880 * We guarantee 2-byte alignment for 'MDB_node's.
882 * #mn_lo and #mn_hi are used for data size on leaf nodes, and for child
883 * pgno on branch nodes. On 64 bit platforms, #mn_flags is also used
884 * for pgno. (Branch nodes have no flags). Lo and hi are in host byte
885 * order in case some accesses can be optimized to 32-bit word access.
887 * Leaf node flags describe node contents. #F_BIGDATA says the node's
888 * data part is the page number of an overflow page with actual data.
889 * #F_DUPDATA and #F_SUBDATA can be combined giving duplicate data in
890 * a sub-page/sub-database, and named databases (just #F_SUBDATA).
892 typedef struct MDB_node {
893 /** part of data size or pgno
895 #if BYTE_ORDER == LITTLE_ENDIAN
896 unsigned short mn_lo, mn_hi;
898 unsigned short mn_hi, mn_lo;
901 /** @defgroup mdb_node Node Flags
903 * Flags for node headers.
906 #define F_BIGDATA 0x01 /**< data put on overflow page */
907 #define F_SUBDATA 0x02 /**< data is a sub-database */
908 #define F_DUPDATA 0x04 /**< data has duplicates */
910 /** valid flags for #mdb_node_add() */
911 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
914 unsigned short mn_flags; /**< @ref mdb_node */
915 unsigned short mn_ksize; /**< key size */
916 char mn_data[1]; /**< key and data are appended here */
919 /** Size of the node header, excluding dynamic data at the end */
920 #define NODESIZE offsetof(MDB_node, mn_data)
922 /** Bit position of top word in page number, for shifting mn_flags */
923 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
925 /** Size of a node in a branch page with a given key.
926 * This is just the node header plus the key, there is no data.
928 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
930 /** Size of a node in a leaf page with a given key and data.
931 * This is node header plus key plus data size.
933 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
935 /** Address of node \b i in page \b p */
936 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
938 /** Address of the key for the node */
939 #define NODEKEY(node) (void *)((node)->mn_data)
941 /** Address of the data for a node */
942 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
944 /** Get the page number pointed to by a branch node */
945 #define NODEPGNO(node) \
946 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
947 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
948 /** Set the page number in a branch node */
949 #define SETPGNO(node,pgno) do { \
950 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
951 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
953 /** Get the size of the data in a leaf node */
954 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
955 /** Set the size of the data for a leaf node */
956 #define SETDSZ(node,size) do { \
957 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
958 /** The size of a key in a node */
959 #define NODEKSZ(node) ((node)->mn_ksize)
961 /** Copy a page number from src to dst */
963 #define COPY_PGNO(dst,src) dst = src
965 #if SIZE_MAX > 4294967295UL
966 #define COPY_PGNO(dst,src) do { \
967 unsigned short *s, *d; \
968 s = (unsigned short *)&(src); \
969 d = (unsigned short *)&(dst); \
976 #define COPY_PGNO(dst,src) do { \
977 unsigned short *s, *d; \
978 s = (unsigned short *)&(src); \
979 d = (unsigned short *)&(dst); \
985 /** The address of a key in a LEAF2 page.
986 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
987 * There are no node headers, keys are stored contiguously.
989 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
991 /** Set the \b node's key into \b keyptr, if requested. */
992 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
993 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
995 /** Set the \b node's key into \b key. */
996 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
998 /** Information about a single database in the environment. */
999 typedef struct MDB_db {
1000 uint32_t md_pad; /**< also ksize for LEAF2 pages */
1001 uint16_t md_flags; /**< @ref mdb_dbi_open */
1002 uint16_t md_depth; /**< depth of this tree */
1003 pgno_t md_branch_pages; /**< number of internal pages */
1004 pgno_t md_leaf_pages; /**< number of leaf pages */
1005 pgno_t md_overflow_pages; /**< number of overflow pages */
1006 size_t md_entries; /**< number of data items */
1007 pgno_t md_root; /**< the root page of this tree */
1010 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
1011 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
1012 /** #mdb_dbi_open() flags */
1013 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
1014 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
1016 /** Handle for the DB used to track free pages. */
1018 /** Handle for the default DB. */
1020 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
1023 /** Number of meta pages - also hardcoded elsewhere */
1026 /** Meta page content.
1027 * A meta page is the start point for accessing a database snapshot.
1028 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
1030 typedef struct MDB_meta {
1031 /** Stamp identifying this as an LMDB file. It must be set
1034 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
1035 uint32_t mm_version;
1036 void *mm_address; /**< address for fixed mapping */
1037 size_t mm_mapsize; /**< size of mmap region */
1038 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
1039 /** The size of pages used in this DB */
1040 #define mm_psize mm_dbs[FREE_DBI].md_pad
1041 /** Any persistent environment flags. @ref mdb_env */
1042 #define mm_flags mm_dbs[FREE_DBI].md_flags
1043 /** Last used page in the datafile.
1044 * Actually the file may be shorter if the freeDB lists the final pages.
1047 volatile txnid_t mm_txnid; /**< txnid that committed this page */
1050 /** Buffer for a stack-allocated meta page.
1051 * The members define size and alignment, and silence type
1052 * aliasing warnings. They are not used directly; that could
1053 * mean incorrectly using several union members in parallel.
1055 typedef union MDB_metabuf {
1058 char mm_pad[PAGEHDRSZ];
1063 /** Auxiliary DB info.
1064 * The information here is mostly static/read-only. There is
1065 * only a single copy of this record in the environment.
1067 typedef struct MDB_dbx {
1068 MDB_val md_name; /**< name of the database */
1069 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1070 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1071 MDB_rel_func *md_rel; /**< user relocate function */
1072 void *md_relctx; /**< user-provided context for md_rel */
1075 /** A database transaction.
1076 * Every operation requires a transaction handle.
1079 MDB_txn *mt_parent; /**< parent of a nested txn */
1080 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1082 pgno_t mt_next_pgno; /**< next unallocated page */
1083 /** The ID of this transaction. IDs are integers incrementing from 1.
1084 * Only committed write transactions increment the ID. If a transaction
1085 * aborts, the ID may be re-used by the next writer.
1088 MDB_env *mt_env; /**< the DB environment */
1089 /** The list of pages that became unused during this transaction.
1091 MDB_IDL mt_free_pgs;
1092 /** The list of loose pages that became unused and may be reused
1093 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1095 MDB_page *mt_loose_pgs;
1096 /** Number of loose pages (#mt_loose_pgs) */
1098 /** The sorted list of dirty pages we temporarily wrote to disk
1099 * because the dirty list was full. page numbers in here are
1100 * shifted left by 1, deleted slots have the LSB set.
1102 MDB_IDL mt_spill_pgs;
1104 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1105 MDB_ID2L dirty_list;
1106 /** For read txns: This thread/txn's reader table slot, or NULL. */
1109 /** Array of records for each DB known in the environment. */
1111 /** Array of MDB_db records for each known DB */
1113 /** Array of sequence numbers for each DB handle */
1114 unsigned int *mt_dbiseqs;
1115 /** @defgroup mt_dbflag Transaction DB Flags
1119 #define DB_DIRTY 0x01 /**< DB was written in this txn */
1120 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1121 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1122 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1123 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1124 #define DB_DUPDATA 0x20 /**< DB is #MDB_DUPSORT data */
1126 /** In write txns, array of cursors for each DB */
1127 MDB_cursor **mt_cursors;
1128 /** Array of flags for each DB */
1129 unsigned char *mt_dbflags;
1130 /** Number of DB records in use, or 0 when the txn is finished.
1131 * This number only ever increments until the txn finishes; we
1132 * don't decrement it when individual DB handles are closed.
1136 /** @defgroup mdb_txn Transaction Flags
1140 /** #mdb_txn_begin() flags */
1141 #define MDB_TXN_BEGIN_FLAGS MDB_RDONLY
1142 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1143 /* internal txn flags */
1144 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1145 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1146 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1147 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1148 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1149 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1150 /** most operations on the txn are currently illegal */
1151 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1153 unsigned int mt_flags; /**< @ref mdb_txn */
1154 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1155 * Includes ancestor txns' dirty pages not hidden by other txns'
1156 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1157 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1159 unsigned int mt_dirty_room;
1162 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1163 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1164 * raise this on a 64 bit machine.
1166 #define CURSOR_STACK 32
1170 /** Cursors are used for all DB operations.
1171 * A cursor holds a path of (page pointer, key index) from the DB
1172 * root to a position in the DB, plus other state. #MDB_DUPSORT
1173 * cursors include an xcursor to the current data item. Write txns
1174 * track their cursors and keep them up to date when data moves.
1175 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1176 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1179 /** Next cursor on this DB in this txn */
1180 MDB_cursor *mc_next;
1181 /** Backup of the original cursor if this cursor is a shadow */
1182 MDB_cursor *mc_backup;
1183 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1184 struct MDB_xcursor *mc_xcursor;
1185 /** The transaction that owns this cursor */
1187 /** The database handle this cursor operates on */
1189 /** The database record for this cursor */
1191 /** The database auxiliary record for this cursor */
1193 /** The @ref mt_dbflag for this database */
1194 unsigned char *mc_dbflag;
1195 unsigned short mc_snum; /**< number of pushed pages */
1196 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1197 /** @defgroup mdb_cursor Cursor Flags
1199 * Cursor state flags.
1202 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1203 #define C_EOF 0x02 /**< No more data */
1204 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1205 #define C_DEL 0x08 /**< last op was a cursor_del */
1206 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1208 unsigned int mc_flags; /**< @ref mdb_cursor */
1209 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1210 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1213 /** Context for sorted-dup records.
1214 * We could have gone to a fully recursive design, with arbitrarily
1215 * deep nesting of sub-databases. But for now we only handle these
1216 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1218 typedef struct MDB_xcursor {
1219 /** A sub-cursor for traversing the Dup DB */
1220 MDB_cursor mx_cursor;
1221 /** The database record for this Dup DB */
1223 /** The auxiliary DB record for this Dup DB */
1225 /** The @ref mt_dbflag for this Dup DB */
1226 unsigned char mx_dbflag;
1229 /** Check if there is an inited xcursor, so #XCURSOR_REFRESH() is proper */
1230 #define XCURSOR_INITED(mc) \
1231 ((mc)->mc_xcursor && ((mc)->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
1233 /** Update sub-page pointer, if any, in \b mc->mc_xcursor. Needed
1234 * when the node which contains the sub-page may have moved. Called
1235 * with \b mp = mc->mc_pg[mc->mc_top], \b ki = mc->mc_ki[mc->mc_top].
1237 #define XCURSOR_REFRESH(mc, mp, ki) do { \
1238 MDB_page *xr_pg = (mp); \
1239 MDB_node *xr_node = NODEPTR(xr_pg, ki); \
1240 if ((xr_node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) \
1241 (mc)->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(xr_node); \
1244 /** State of FreeDB old pages, stored in the MDB_env */
1245 typedef struct MDB_pgstate {
1246 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1247 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1250 /** The database environment. */
1252 HANDLE me_fd; /**< The main data file */
1253 HANDLE me_lfd; /**< The lock file */
1254 HANDLE me_mfd; /**< For writing and syncing the meta pages */
1255 /** Failed to update the meta page. Probably an I/O error. */
1256 #define MDB_FATAL_ERROR 0x80000000U
1257 /** Some fields are initialized. */
1258 #define MDB_ENV_ACTIVE 0x20000000U
1259 /** me_txkey is set */
1260 #define MDB_ENV_TXKEY 0x10000000U
1261 /** fdatasync is unreliable */
1262 #define MDB_FSYNCONLY 0x08000000U
1263 uint32_t me_flags; /**< @ref mdb_env */
1264 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1265 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1266 unsigned int me_maxreaders; /**< size of the reader table */
1267 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1268 volatile int me_close_readers;
1269 MDB_dbi me_numdbs; /**< number of DBs opened */
1270 MDB_dbi me_maxdbs; /**< size of the DB table */
1271 MDB_PID_T me_pid; /**< process ID of this env */
1272 char *me_path; /**< path to the DB files */
1273 char *me_map; /**< the memory map of the data file */
1274 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1275 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1276 void *me_pbuf; /**< scratch area for DUPSORT put() */
1277 MDB_txn *me_txn; /**< current write transaction */
1278 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1279 size_t me_mapsize; /**< size of the data memory map */
1280 off_t me_size; /**< current file size */
1281 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1282 MDB_dbx *me_dbxs; /**< array of static DB info */
1283 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1284 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1285 pthread_key_t me_txkey; /**< thread-key for readers */
1286 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1287 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1288 # define me_pglast me_pgstate.mf_pglast
1289 # define me_pghead me_pgstate.mf_pghead
1290 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1291 /** IDL of pages that became unused in a write txn */
1292 MDB_IDL me_free_pgs;
1293 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1294 MDB_ID2L me_dirty_list;
1295 /** Max number of freelist items that can fit in a single overflow page */
1297 /** Max size of a node on a page */
1298 unsigned int me_nodemax;
1299 #if !(MDB_MAXKEYSIZE)
1300 unsigned int me_maxkey; /**< max size of a key */
1302 int me_live_reader; /**< have liveness lock in reader table */
1304 int me_pidquery; /**< Used in OpenProcess */
1306 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1307 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1308 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1310 mdb_mutex_t me_rmutex;
1311 mdb_mutex_t me_wmutex;
1313 void *me_userctx; /**< User-settable context */
1314 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1317 /** Nested transaction */
1318 typedef struct MDB_ntxn {
1319 MDB_txn mnt_txn; /**< the transaction */
1320 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1323 /** max number of pages to commit in one writev() call */
1324 #define MDB_COMMIT_PAGES 64
1325 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1326 #undef MDB_COMMIT_PAGES
1327 #define MDB_COMMIT_PAGES IOV_MAX
1330 /** max bytes to write in one call */
1331 #define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
1333 /** Check \b txn and \b dbi arguments to a function */
1334 #define TXN_DBI_EXIST(txn, dbi, validity) \
1335 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1337 /** Check for misused \b dbi handles */
1338 #define TXN_DBI_CHANGED(txn, dbi) \
1339 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1341 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1342 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1343 static int mdb_page_touch(MDB_cursor *mc);
1345 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1346 "reset-tmp", "fail-begin", "fail-beginchild"}
1348 /* mdb_txn_end operation number, for logging */
1349 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1350 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1352 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1353 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1354 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1355 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1356 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1358 static int mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
1359 static int mdb_page_search_root(MDB_cursor *mc,
1360 MDB_val *key, int modify);
1361 #define MDB_PS_MODIFY 1
1362 #define MDB_PS_ROOTONLY 2
1363 #define MDB_PS_FIRST 4
1364 #define MDB_PS_LAST 8
1365 static int mdb_page_search(MDB_cursor *mc,
1366 MDB_val *key, int flags);
1367 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1369 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1370 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1371 pgno_t newpgno, unsigned int nflags);
1373 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1374 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1375 static int mdb_env_write_meta(MDB_txn *txn);
1376 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1377 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1379 static void mdb_env_close0(MDB_env *env, int excl);
1381 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1382 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1383 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1384 static void mdb_node_del(MDB_cursor *mc, int ksize);
1385 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1386 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1387 static int mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
1388 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1389 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1391 static int mdb_rebalance(MDB_cursor *mc);
1392 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1394 static void mdb_cursor_pop(MDB_cursor *mc);
1395 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1397 static int mdb_cursor_del0(MDB_cursor *mc);
1398 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1399 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1400 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1401 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1402 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1404 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1405 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1407 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1408 static void mdb_xcursor_init0(MDB_cursor *mc);
1409 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1410 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1412 static int mdb_drop0(MDB_cursor *mc, int subs);
1413 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1414 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1417 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1420 /** Compare two items pointing at size_t's of unknown alignment. */
1421 #ifdef MISALIGNED_OK
1422 # define mdb_cmp_clong mdb_cmp_long
1424 # define mdb_cmp_clong mdb_cmp_cint
1428 static SECURITY_DESCRIPTOR mdb_null_sd;
1429 static SECURITY_ATTRIBUTES mdb_all_sa;
1430 static int mdb_sec_inited;
1433 static int utf8_to_utf16(const char *src, struct MDB_name *dst, int xtra);
1436 /** Return the library version info. */
1438 mdb_version(int *major, int *minor, int *patch)
1440 if (major) *major = MDB_VERSION_MAJOR;
1441 if (minor) *minor = MDB_VERSION_MINOR;
1442 if (patch) *patch = MDB_VERSION_PATCH;
1443 return MDB_VERSION_STRING;
1446 /** Table of descriptions for LMDB @ref errors */
1447 static char *const mdb_errstr[] = {
1448 "MDB_KEYEXIST: Key/data pair already exists",
1449 "MDB_NOTFOUND: No matching key/data pair found",
1450 "MDB_PAGE_NOTFOUND: Requested page not found",
1451 "MDB_CORRUPTED: Located page was wrong type",
1452 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1453 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1454 "MDB_INVALID: File is not an LMDB file",
1455 "MDB_MAP_FULL: Environment mapsize limit reached",
1456 "MDB_DBS_FULL: Environment maxdbs limit reached",
1457 "MDB_READERS_FULL: Environment maxreaders limit reached",
1458 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1459 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1460 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1461 "MDB_PAGE_FULL: Internal error - page has no more space",
1462 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1463 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1464 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1465 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1466 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1467 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1471 mdb_strerror(int err)
1474 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1475 * This works as long as no function between the call to mdb_strerror
1476 * and the actual use of the message uses more than 4K of stack.
1478 #define MSGSIZE 1024
1479 #define PADSIZE 4096
1480 char buf[MSGSIZE+PADSIZE], *ptr = buf;
1484 return ("Successful return: 0");
1486 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1487 i = err - MDB_KEYEXIST;
1488 return mdb_errstr[i];
1492 /* These are the C-runtime error codes we use. The comment indicates
1493 * their numeric value, and the Win32 error they would correspond to
1494 * if the error actually came from a Win32 API. A major mess, we should
1495 * have used LMDB-specific error codes for everything.
1498 case ENOENT: /* 2, FILE_NOT_FOUND */
1499 case EIO: /* 5, ACCESS_DENIED */
1500 case ENOMEM: /* 12, INVALID_ACCESS */
1501 case EACCES: /* 13, INVALID_DATA */
1502 case EBUSY: /* 16, CURRENT_DIRECTORY */
1503 case EINVAL: /* 22, BAD_COMMAND */
1504 case ENOSPC: /* 28, OUT_OF_PAPER */
1505 return strerror(err);
1510 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1511 FORMAT_MESSAGE_IGNORE_INSERTS,
1512 NULL, err, 0, ptr, MSGSIZE, (va_list *)buf+MSGSIZE);
1515 return strerror(err);
1519 /** assert(3) variant in cursor context */
1520 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1521 /** assert(3) variant in transaction context */
1522 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1523 /** assert(3) variant in environment context */
1524 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1527 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1528 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1531 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1532 const char *func, const char *file, int line)
1535 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1536 file, line, expr_txt, func);
1537 if (env->me_assert_func)
1538 env->me_assert_func(env, buf);
1539 fprintf(stderr, "%s\n", buf);
1543 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1547 /** Return the page number of \b mp which may be sub-page, for debug output */
1549 mdb_dbg_pgno(MDB_page *mp)
1552 COPY_PGNO(ret, mp->mp_pgno);
1556 /** Display a key in hexadecimal and return the address of the result.
1557 * @param[in] key the key to display
1558 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1559 * @return The key in hexadecimal form.
1562 mdb_dkey(MDB_val *key, char *buf)
1565 unsigned char *c = key->mv_data;
1571 if (key->mv_size > DKBUF_MAXKEYSIZE)
1572 return "MDB_MAXKEYSIZE";
1573 /* may want to make this a dynamic check: if the key is mostly
1574 * printable characters, print it as-is instead of converting to hex.
1578 for (i=0; i<key->mv_size; i++)
1579 ptr += sprintf(ptr, "%02x", *c++);
1581 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1587 mdb_leafnode_type(MDB_node *n)
1589 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1590 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1591 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1594 /** Display all the keys in the page. */
1596 mdb_page_list(MDB_page *mp)
1598 pgno_t pgno = mdb_dbg_pgno(mp);
1599 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1601 unsigned int i, nkeys, nsize, total = 0;
1605 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1606 case P_BRANCH: type = "Branch page"; break;
1607 case P_LEAF: type = "Leaf page"; break;
1608 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1609 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1610 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1612 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1613 pgno, mp->mp_pages, state);
1616 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1617 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1620 fprintf(stderr, "Bad page %"Z"u flags 0x%X\n", pgno, mp->mp_flags);
1624 nkeys = NUMKEYS(mp);
1625 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1627 for (i=0; i<nkeys; i++) {
1628 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1629 key.mv_size = nsize = mp->mp_pad;
1630 key.mv_data = LEAF2KEY(mp, i, nsize);
1632 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1635 node = NODEPTR(mp, i);
1636 key.mv_size = node->mn_ksize;
1637 key.mv_data = node->mn_data;
1638 nsize = NODESIZE + key.mv_size;
1639 if (IS_BRANCH(mp)) {
1640 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1644 if (F_ISSET(node->mn_flags, F_BIGDATA))
1645 nsize += sizeof(pgno_t);
1647 nsize += NODEDSZ(node);
1649 nsize += sizeof(indx_t);
1650 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1651 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1653 total = EVEN(total);
1655 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1656 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1660 mdb_cursor_chk(MDB_cursor *mc)
1666 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1667 for (i=0; i<mc->mc_top; i++) {
1669 node = NODEPTR(mp, mc->mc_ki[i]);
1670 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1673 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1675 if (XCURSOR_INITED(mc)) {
1676 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1677 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1678 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1686 /** Count all the pages in each DB and in the freelist
1687 * and make sure it matches the actual number of pages
1689 * All named DBs must be open for a correct count.
1691 static void mdb_audit(MDB_txn *txn)
1695 MDB_ID freecount, count;
1700 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1701 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1702 freecount += *(MDB_ID *)data.mv_data;
1703 mdb_tassert(txn, rc == MDB_NOTFOUND);
1706 for (i = 0; i<txn->mt_numdbs; i++) {
1708 if (!(txn->mt_dbflags[i] & DB_VALID))
1710 mdb_cursor_init(&mc, txn, i, &mx);
1711 if (txn->mt_dbs[i].md_root == P_INVALID)
1713 count += txn->mt_dbs[i].md_branch_pages +
1714 txn->mt_dbs[i].md_leaf_pages +
1715 txn->mt_dbs[i].md_overflow_pages;
1716 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1717 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1718 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1721 mp = mc.mc_pg[mc.mc_top];
1722 for (j=0; j<NUMKEYS(mp); j++) {
1723 MDB_node *leaf = NODEPTR(mp, j);
1724 if (leaf->mn_flags & F_SUBDATA) {
1726 memcpy(&db, NODEDATA(leaf), sizeof(db));
1727 count += db.md_branch_pages + db.md_leaf_pages +
1728 db.md_overflow_pages;
1732 mdb_tassert(txn, rc == MDB_NOTFOUND);
1735 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1736 fprintf(stderr, "audit: %"Z"u freecount: %"Z"u count: %"Z"u total: %"Z"u next_pgno: %"Z"u\n",
1737 txn->mt_txnid, freecount, count+NUM_METAS,
1738 freecount+count+NUM_METAS, txn->mt_next_pgno);
1744 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1746 return txn->mt_dbxs[dbi].md_cmp(a, b);
1750 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1752 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1753 #if UINT_MAX < SIZE_MAX
1754 if (dcmp == mdb_cmp_int && a->mv_size == sizeof(size_t))
1755 dcmp = mdb_cmp_clong;
1760 /** Allocate memory for a page.
1761 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1762 * Set #MDB_TXN_ERROR on failure.
1765 mdb_page_malloc(MDB_txn *txn, unsigned num)
1767 MDB_env *env = txn->mt_env;
1768 MDB_page *ret = env->me_dpages;
1769 size_t psize = env->me_psize, sz = psize, off;
1770 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1771 * For a single page alloc, we init everything after the page header.
1772 * For multi-page, we init the final page; if the caller needed that
1773 * many pages they will be filling in at least up to the last page.
1777 VGMEMP_ALLOC(env, ret, sz);
1778 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1779 env->me_dpages = ret->mp_next;
1782 psize -= off = PAGEHDRSZ;
1787 if ((ret = malloc(sz)) != NULL) {
1788 VGMEMP_ALLOC(env, ret, sz);
1789 if (!(env->me_flags & MDB_NOMEMINIT)) {
1790 memset((char *)ret + off, 0, psize);
1794 txn->mt_flags |= MDB_TXN_ERROR;
1798 /** Free a single page.
1799 * Saves single pages to a list, for future reuse.
1800 * (This is not used for multi-page overflow pages.)
1803 mdb_page_free(MDB_env *env, MDB_page *mp)
1805 mp->mp_next = env->me_dpages;
1806 VGMEMP_FREE(env, mp);
1807 env->me_dpages = mp;
1810 /** Free a dirty page */
1812 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1814 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1815 mdb_page_free(env, dp);
1817 /* large pages just get freed directly */
1818 VGMEMP_FREE(env, dp);
1823 /** Return all dirty pages to dpage list */
1825 mdb_dlist_free(MDB_txn *txn)
1827 MDB_env *env = txn->mt_env;
1828 MDB_ID2L dl = txn->mt_u.dirty_list;
1829 unsigned i, n = dl[0].mid;
1831 for (i = 1; i <= n; i++) {
1832 mdb_dpage_free(env, dl[i].mptr);
1837 /** Loosen or free a single page.
1838 * Saves single pages to a list for future reuse
1839 * in this same txn. It has been pulled from the freeDB
1840 * and already resides on the dirty list, but has been
1841 * deleted. Use these pages first before pulling again
1844 * If the page wasn't dirtied in this txn, just add it
1845 * to this txn's free list.
1848 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1851 pgno_t pgno = mp->mp_pgno;
1852 MDB_txn *txn = mc->mc_txn;
1854 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1855 if (txn->mt_parent) {
1856 MDB_ID2 *dl = txn->mt_u.dirty_list;
1857 /* If txn has a parent, make sure the page is in our
1861 unsigned x = mdb_mid2l_search(dl, pgno);
1862 if (x <= dl[0].mid && dl[x].mid == pgno) {
1863 if (mp != dl[x].mptr) { /* bad cursor? */
1864 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1865 txn->mt_flags |= MDB_TXN_ERROR;
1866 return MDB_CORRUPTED;
1873 /* no parent txn, so it's just ours */
1878 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1880 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1881 txn->mt_loose_pgs = mp;
1882 txn->mt_loose_count++;
1883 mp->mp_flags |= P_LOOSE;
1885 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1893 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1894 * @param[in] mc A cursor handle for the current operation.
1895 * @param[in] pflags Flags of the pages to update:
1896 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1897 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1898 * @return 0 on success, non-zero on failure.
1901 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1903 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1904 MDB_txn *txn = mc->mc_txn;
1905 MDB_cursor *m3, *m0 = mc;
1910 int rc = MDB_SUCCESS, level;
1912 /* Mark pages seen by cursors */
1913 if (mc->mc_flags & C_UNTRACK)
1914 mc = NULL; /* will find mc in mt_cursors */
1915 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1916 for (; mc; mc=mc->mc_next) {
1917 if (!(mc->mc_flags & C_INITIALIZED))
1919 for (m3 = mc;; m3 = &mx->mx_cursor) {
1921 for (j=0; j<m3->mc_snum; j++) {
1923 if ((mp->mp_flags & Mask) == pflags)
1924 mp->mp_flags ^= P_KEEP;
1926 mx = m3->mc_xcursor;
1927 /* Proceed to mx if it is at a sub-database */
1928 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1930 if (! (mp && (mp->mp_flags & P_LEAF)))
1932 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1933 if (!(leaf->mn_flags & F_SUBDATA))
1942 /* Mark dirty root pages */
1943 for (i=0; i<txn->mt_numdbs; i++) {
1944 if (txn->mt_dbflags[i] & DB_DIRTY) {
1945 pgno_t pgno = txn->mt_dbs[i].md_root;
1946 if (pgno == P_INVALID)
1948 if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
1950 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1951 dp->mp_flags ^= P_KEEP;
1959 static int mdb_page_flush(MDB_txn *txn, int keep);
1961 /** Spill pages from the dirty list back to disk.
1962 * This is intended to prevent running into #MDB_TXN_FULL situations,
1963 * but note that they may still occur in a few cases:
1964 * 1) our estimate of the txn size could be too small. Currently this
1965 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1966 * 2) child txns may run out of space if their parents dirtied a
1967 * lot of pages and never spilled them. TODO: we probably should do
1968 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1969 * the parent's dirty_room is below a given threshold.
1971 * Otherwise, if not using nested txns, it is expected that apps will
1972 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1973 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1974 * If the txn never references them again, they can be left alone.
1975 * If the txn only reads them, they can be used without any fuss.
1976 * If the txn writes them again, they can be dirtied immediately without
1977 * going thru all of the work of #mdb_page_touch(). Such references are
1978 * handled by #mdb_page_unspill().
1980 * Also note, we never spill DB root pages, nor pages of active cursors,
1981 * because we'll need these back again soon anyway. And in nested txns,
1982 * we can't spill a page in a child txn if it was already spilled in a
1983 * parent txn. That would alter the parent txns' data even though
1984 * the child hasn't committed yet, and we'd have no way to undo it if
1985 * the child aborted.
1987 * @param[in] m0 cursor A cursor handle identifying the transaction and
1988 * database for which we are checking space.
1989 * @param[in] key For a put operation, the key being stored.
1990 * @param[in] data For a put operation, the data being stored.
1991 * @return 0 on success, non-zero on failure.
1994 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1996 MDB_txn *txn = m0->mc_txn;
1998 MDB_ID2L dl = txn->mt_u.dirty_list;
1999 unsigned int i, j, need;
2002 if (m0->mc_flags & C_SUB)
2005 /* Estimate how much space this op will take */
2006 i = m0->mc_db->md_depth;
2007 /* Named DBs also dirty the main DB */
2008 if (m0->mc_dbi >= CORE_DBS)
2009 i += txn->mt_dbs[MAIN_DBI].md_depth;
2010 /* For puts, roughly factor in the key+data size */
2012 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
2013 i += i; /* double it for good measure */
2016 if (txn->mt_dirty_room > i)
2019 if (!txn->mt_spill_pgs) {
2020 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
2021 if (!txn->mt_spill_pgs)
2024 /* purge deleted slots */
2025 MDB_IDL sl = txn->mt_spill_pgs;
2026 unsigned int num = sl[0];
2028 for (i=1; i<=num; i++) {
2035 /* Preserve pages which may soon be dirtied again */
2036 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2039 /* Less aggressive spill - we originally spilled the entire dirty list,
2040 * with a few exceptions for cursor pages and DB root pages. But this
2041 * turns out to be a lot of wasted effort because in a large txn many
2042 * of those pages will need to be used again. So now we spill only 1/8th
2043 * of the dirty pages. Testing revealed this to be a good tradeoff,
2044 * better than 1/2, 1/4, or 1/10.
2046 if (need < MDB_IDL_UM_MAX / 8)
2047 need = MDB_IDL_UM_MAX / 8;
2049 /* Save the page IDs of all the pages we're flushing */
2050 /* flush from the tail forward, this saves a lot of shifting later on. */
2051 for (i=dl[0].mid; i && need; i--) {
2052 MDB_ID pn = dl[i].mid << 1;
2054 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2056 /* Can't spill twice, make sure it's not already in a parent's
2059 if (txn->mt_parent) {
2061 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2062 if (tx2->mt_spill_pgs) {
2063 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2064 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2065 dp->mp_flags |= P_KEEP;
2073 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2077 mdb_midl_sort(txn->mt_spill_pgs);
2079 /* Flush the spilled part of dirty list */
2080 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2083 /* Reset any dirty pages we kept that page_flush didn't see */
2084 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2087 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2091 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2093 mdb_find_oldest(MDB_txn *txn)
2096 txnid_t mr, oldest = txn->mt_txnid - 1;
2097 if (txn->mt_env->me_txns) {
2098 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2099 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2110 /** Add a page to the txn's dirty list */
2112 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2115 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2117 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2118 insert = mdb_mid2l_append;
2120 insert = mdb_mid2l_insert;
2122 mid.mid = mp->mp_pgno;
2124 rc = insert(txn->mt_u.dirty_list, &mid);
2125 mdb_tassert(txn, rc == 0);
2126 txn->mt_dirty_room--;
2129 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2130 * me_pghead and mt_next_pgno. Set #MDB_TXN_ERROR on failure.
2132 * If there are free pages available from older transactions, they
2133 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2134 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2135 * and move me_pglast to say which records were consumed. Only this
2136 * function can create me_pghead and move me_pglast/mt_next_pgno.
2137 * @param[in] mc cursor A cursor handle identifying the transaction and
2138 * database for which we are allocating.
2139 * @param[in] num the number of pages to allocate.
2140 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2141 * will always be satisfied by a single contiguous chunk of memory.
2142 * @return 0 on success, non-zero on failure.
2145 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2147 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2148 /* Get at most <Max_retries> more freeDB records once me_pghead
2149 * has enough pages. If not enough, use new pages from the map.
2150 * If <Paranoid> and mc is updating the freeDB, only get new
2151 * records if me_pghead is empty. Then the freelist cannot play
2152 * catch-up with itself by growing while trying to save it.
2154 enum { Paranoid = 1, Max_retries = 500 };
2156 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2158 int rc, retry = num * 60;
2159 MDB_txn *txn = mc->mc_txn;
2160 MDB_env *env = txn->mt_env;
2161 pgno_t pgno, *mop = env->me_pghead;
2162 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2164 txnid_t oldest = 0, last;
2169 /* If there are any loose pages, just use them */
2170 if (num == 1 && txn->mt_loose_pgs) {
2171 np = txn->mt_loose_pgs;
2172 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2173 txn->mt_loose_count--;
2174 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
2182 /* If our dirty list is already full, we can't do anything */
2183 if (txn->mt_dirty_room == 0) {
2188 for (op = MDB_FIRST;; op = MDB_NEXT) {
2193 /* Seek a big enough contiguous page range. Prefer
2194 * pages at the tail, just truncating the list.
2200 if (mop[i-n2] == pgno+n2)
2207 if (op == MDB_FIRST) { /* 1st iteration */
2208 /* Prepare to fetch more and coalesce */
2209 last = env->me_pglast;
2210 oldest = env->me_pgoldest;
2211 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2214 key.mv_data = &last; /* will look up last+1 */
2215 key.mv_size = sizeof(last);
2217 if (Paranoid && mc->mc_dbi == FREE_DBI)
2220 if (Paranoid && retry < 0 && mop_len)
2224 /* Do not fetch more if the record will be too recent */
2225 if (oldest <= last) {
2227 oldest = mdb_find_oldest(txn);
2228 env->me_pgoldest = oldest;
2234 rc = mdb_cursor_get(&m2, &key, NULL, op);
2236 if (rc == MDB_NOTFOUND)
2240 last = *(txnid_t*)key.mv_data;
2241 if (oldest <= last) {
2243 oldest = mdb_find_oldest(txn);
2244 env->me_pgoldest = oldest;
2250 np = m2.mc_pg[m2.mc_top];
2251 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2252 if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
2255 idl = (MDB_ID *) data.mv_data;
2258 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2263 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2265 mop = env->me_pghead;
2267 env->me_pglast = last;
2269 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2270 last, txn->mt_dbs[FREE_DBI].md_root, i));
2272 DPRINTF(("IDL %"Z"u", idl[j]));
2274 /* Merge in descending sorted order */
2275 mdb_midl_xmerge(mop, idl);
2279 /* Use new pages from the map when nothing suitable in the freeDB */
2281 pgno = txn->mt_next_pgno;
2282 if (pgno + num >= env->me_maxpg) {
2283 DPUTS("DB size maxed out");
2289 if (env->me_flags & MDB_WRITEMAP) {
2290 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2292 if (!(np = mdb_page_malloc(txn, num))) {
2298 mop[0] = mop_len -= num;
2299 /* Move any stragglers down */
2300 for (j = i-num; j < mop_len; )
2301 mop[++j] = mop[++i];
2303 txn->mt_next_pgno = pgno + num;
2306 mdb_page_dirty(txn, np);
2312 txn->mt_flags |= MDB_TXN_ERROR;
2316 /** Copy the used portions of a non-overflow page.
2317 * @param[in] dst page to copy into
2318 * @param[in] src page to copy from
2319 * @param[in] psize size of a page
2322 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2324 enum { Align = sizeof(pgno_t) };
2325 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2327 /* If page isn't full, just copy the used portion. Adjust
2328 * alignment so memcpy may copy words instead of bytes.
2330 if ((unused &= -Align) && !IS_LEAF2(src)) {
2331 upper = (upper + PAGEBASE) & -Align;
2332 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2333 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2336 memcpy(dst, src, psize - unused);
2340 /** Pull a page off the txn's spill list, if present.
2341 * If a page being referenced was spilled to disk in this txn, bring
2342 * it back and make it dirty/writable again.
2343 * @param[in] txn the transaction handle.
2344 * @param[in] mp the page being referenced. It must not be dirty.
2345 * @param[out] ret the writable page, if any. ret is unchanged if
2346 * mp wasn't spilled.
2349 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2351 MDB_env *env = txn->mt_env;
2354 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2356 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2357 if (!tx2->mt_spill_pgs)
2359 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2360 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2363 if (txn->mt_dirty_room == 0)
2364 return MDB_TXN_FULL;
2365 if (IS_OVERFLOW(mp))
2369 if (env->me_flags & MDB_WRITEMAP) {
2372 np = mdb_page_malloc(txn, num);
2376 memcpy(np, mp, num * env->me_psize);
2378 mdb_page_copy(np, mp, env->me_psize);
2381 /* If in current txn, this page is no longer spilled.
2382 * If it happens to be the last page, truncate the spill list.
2383 * Otherwise mark it as deleted by setting the LSB.
2385 if (x == txn->mt_spill_pgs[0])
2386 txn->mt_spill_pgs[0]--;
2388 txn->mt_spill_pgs[x] |= 1;
2389 } /* otherwise, if belonging to a parent txn, the
2390 * page remains spilled until child commits
2393 mdb_page_dirty(txn, np);
2394 np->mp_flags |= P_DIRTY;
2402 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2403 * Set #MDB_TXN_ERROR on failure.
2404 * @param[in] mc cursor pointing to the page to be touched
2405 * @return 0 on success, non-zero on failure.
2408 mdb_page_touch(MDB_cursor *mc)
2410 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2411 MDB_txn *txn = mc->mc_txn;
2412 MDB_cursor *m2, *m3;
2416 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2417 if (txn->mt_flags & MDB_TXN_SPILLS) {
2419 rc = mdb_page_unspill(txn, mp, &np);
2425 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2426 (rc = mdb_page_alloc(mc, 1, &np)))
2429 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2430 mp->mp_pgno, pgno));
2431 mdb_cassert(mc, mp->mp_pgno != pgno);
2432 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2433 /* Update the parent page, if any, to point to the new page */
2435 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2436 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2437 SETPGNO(node, pgno);
2439 mc->mc_db->md_root = pgno;
2441 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2442 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2444 /* If txn has a parent, make sure the page is in our
2448 unsigned x = mdb_mid2l_search(dl, pgno);
2449 if (x <= dl[0].mid && dl[x].mid == pgno) {
2450 if (mp != dl[x].mptr) { /* bad cursor? */
2451 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2452 txn->mt_flags |= MDB_TXN_ERROR;
2453 return MDB_CORRUPTED;
2458 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2460 np = mdb_page_malloc(txn, 1);
2465 rc = mdb_mid2l_insert(dl, &mid);
2466 mdb_cassert(mc, rc == 0);
2471 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2473 np->mp_flags |= P_DIRTY;
2476 /* Adjust cursors pointing to mp */
2477 mc->mc_pg[mc->mc_top] = np;
2478 m2 = txn->mt_cursors[mc->mc_dbi];
2479 if (mc->mc_flags & C_SUB) {
2480 for (; m2; m2=m2->mc_next) {
2481 m3 = &m2->mc_xcursor->mx_cursor;
2482 if (m3->mc_snum < mc->mc_snum) continue;
2483 if (m3->mc_pg[mc->mc_top] == mp)
2484 m3->mc_pg[mc->mc_top] = np;
2487 for (; m2; m2=m2->mc_next) {
2488 if (m2->mc_snum < mc->mc_snum) continue;
2489 if (m2 == mc) continue;
2490 if (m2->mc_pg[mc->mc_top] == mp) {
2491 m2->mc_pg[mc->mc_top] = np;
2492 if (XCURSOR_INITED(m2) && IS_LEAF(np))
2493 XCURSOR_REFRESH(m2, np, m2->mc_ki[mc->mc_top]);
2500 txn->mt_flags |= MDB_TXN_ERROR;
2505 mdb_env_sync(MDB_env *env, int force)
2508 if (env->me_flags & MDB_RDONLY)
2510 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2511 if (env->me_flags & MDB_WRITEMAP) {
2512 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2513 ? MS_ASYNC : MS_SYNC;
2514 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2517 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2521 #ifdef BROKEN_FDATASYNC
2522 if (env->me_flags & MDB_FSYNCONLY) {
2523 if (fsync(env->me_fd))
2527 if (MDB_FDATASYNC(env->me_fd))
2534 /** Back up parent txn's cursors, then grab the originals for tracking */
2536 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2538 MDB_cursor *mc, *bk;
2543 for (i = src->mt_numdbs; --i >= 0; ) {
2544 if ((mc = src->mt_cursors[i]) != NULL) {
2545 size = sizeof(MDB_cursor);
2547 size += sizeof(MDB_xcursor);
2548 for (; mc; mc = bk->mc_next) {
2554 mc->mc_db = &dst->mt_dbs[i];
2555 /* Kill pointers into src to reduce abuse: The
2556 * user may not use mc until dst ends. But we need a valid
2557 * txn pointer here for cursor fixups to keep working.
2560 mc->mc_dbflag = &dst->mt_dbflags[i];
2561 if ((mx = mc->mc_xcursor) != NULL) {
2562 *(MDB_xcursor *)(bk+1) = *mx;
2563 mx->mx_cursor.mc_txn = dst;
2565 mc->mc_next = dst->mt_cursors[i];
2566 dst->mt_cursors[i] = mc;
2573 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2574 * @param[in] txn the transaction handle.
2575 * @param[in] merge true to keep changes to parent cursors, false to revert.
2576 * @return 0 on success, non-zero on failure.
2579 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2581 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2585 for (i = txn->mt_numdbs; --i >= 0; ) {
2586 for (mc = cursors[i]; mc; mc = next) {
2588 if ((bk = mc->mc_backup) != NULL) {
2590 /* Commit changes to parent txn */
2591 mc->mc_next = bk->mc_next;
2592 mc->mc_backup = bk->mc_backup;
2593 mc->mc_txn = bk->mc_txn;
2594 mc->mc_db = bk->mc_db;
2595 mc->mc_dbflag = bk->mc_dbflag;
2596 if ((mx = mc->mc_xcursor) != NULL)
2597 mx->mx_cursor.mc_txn = bk->mc_txn;
2599 /* Abort nested txn */
2601 if ((mx = mc->mc_xcursor) != NULL)
2602 *mx = *(MDB_xcursor *)(bk+1);
2606 /* Only malloced cursors are permanently tracked. */
2613 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2619 Pidset = F_SETLK, Pidcheck = F_GETLK
2623 /** Set or check a pid lock. Set returns 0 on success.
2624 * Check returns 0 if the process is certainly dead, nonzero if it may
2625 * be alive (the lock exists or an error happened so we do not know).
2627 * On Windows Pidset is a no-op, we merely check for the existence
2628 * of the process with the given pid. On POSIX we use a single byte
2629 * lock on the lockfile, set at an offset equal to the pid.
2632 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2634 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2637 if (op == Pidcheck) {
2638 h = OpenProcess(env->me_pidquery, FALSE, pid);
2639 /* No documented "no such process" code, but other program use this: */
2641 return ErrCode() != ERROR_INVALID_PARAMETER;
2642 /* A process exists until all handles to it close. Has it exited? */
2643 ret = WaitForSingleObject(h, 0) != 0;
2650 struct flock lock_info;
2651 memset(&lock_info, 0, sizeof(lock_info));
2652 lock_info.l_type = F_WRLCK;
2653 lock_info.l_whence = SEEK_SET;
2654 lock_info.l_start = pid;
2655 lock_info.l_len = 1;
2656 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2657 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2659 } else if ((rc = ErrCode()) == EINTR) {
2667 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2668 * @param[in] txn the transaction handle to initialize
2669 * @return 0 on success, non-zero on failure.
2672 mdb_txn_renew0(MDB_txn *txn)
2674 MDB_env *env = txn->mt_env;
2675 MDB_txninfo *ti = env->me_txns;
2677 unsigned int i, nr, flags = txn->mt_flags;
2679 int rc, new_notls = 0;
2681 if ((flags &= MDB_TXN_RDONLY) != 0) {
2683 meta = mdb_env_pick_meta(env);
2684 txn->mt_txnid = meta->mm_txnid;
2685 txn->mt_u.reader = NULL;
2687 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2688 pthread_getspecific(env->me_txkey);
2690 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2691 return MDB_BAD_RSLOT;
2693 MDB_PID_T pid = env->me_pid;
2694 MDB_THR_T tid = pthread_self();
2695 mdb_mutexref_t rmutex = env->me_rmutex;
2697 if (!env->me_live_reader) {
2698 rc = mdb_reader_pid(env, Pidset, pid);
2701 env->me_live_reader = 1;
2704 if (LOCK_MUTEX(rc, env, rmutex))
2706 nr = ti->mti_numreaders;
2707 for (i=0; i<nr; i++)
2708 if (ti->mti_readers[i].mr_pid == 0)
2710 if (i == env->me_maxreaders) {
2711 UNLOCK_MUTEX(rmutex);
2712 return MDB_READERS_FULL;
2714 r = &ti->mti_readers[i];
2715 /* Claim the reader slot, carefully since other code
2716 * uses the reader table un-mutexed: First reset the
2717 * slot, next publish it in mti_numreaders. After
2718 * that, it is safe for mdb_env_close() to touch it.
2719 * When it will be closed, we can finally claim it.
2722 r->mr_txnid = (txnid_t)-1;
2725 ti->mti_numreaders = ++nr;
2726 env->me_close_readers = nr;
2728 UNLOCK_MUTEX(rmutex);
2730 new_notls = (env->me_flags & MDB_NOTLS);
2731 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2736 do /* LY: Retry on a race, ITS#7970. */
2737 r->mr_txnid = ti->mti_txnid;
2738 while(r->mr_txnid != ti->mti_txnid);
2739 txn->mt_txnid = r->mr_txnid;
2740 txn->mt_u.reader = r;
2741 meta = env->me_metas[txn->mt_txnid & 1];
2745 /* Not yet touching txn == env->me_txn0, it may be active */
2747 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2749 txn->mt_txnid = ti->mti_txnid;
2750 meta = env->me_metas[txn->mt_txnid & 1];
2752 meta = mdb_env_pick_meta(env);
2753 txn->mt_txnid = meta->mm_txnid;
2757 if (txn->mt_txnid == mdb_debug_start)
2760 txn->mt_child = NULL;
2761 txn->mt_loose_pgs = NULL;
2762 txn->mt_loose_count = 0;
2763 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2764 txn->mt_u.dirty_list = env->me_dirty_list;
2765 txn->mt_u.dirty_list[0].mid = 0;
2766 txn->mt_free_pgs = env->me_free_pgs;
2767 txn->mt_free_pgs[0] = 0;
2768 txn->mt_spill_pgs = NULL;
2770 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2773 /* Copy the DB info and flags */
2774 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
2776 /* Moved to here to avoid a data race in read TXNs */
2777 txn->mt_next_pgno = meta->mm_last_pg+1;
2779 txn->mt_flags = flags;
2782 txn->mt_numdbs = env->me_numdbs;
2783 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
2784 x = env->me_dbflags[i];
2785 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2786 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
2788 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
2789 txn->mt_dbflags[FREE_DBI] = DB_VALID;
2791 if (env->me_flags & MDB_FATAL_ERROR) {
2792 DPUTS("environment had fatal error, must shutdown!");
2794 } else if (env->me_maxpg < txn->mt_next_pgno) {
2795 rc = MDB_MAP_RESIZED;
2799 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
2804 mdb_txn_renew(MDB_txn *txn)
2808 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
2811 rc = mdb_txn_renew0(txn);
2812 if (rc == MDB_SUCCESS) {
2813 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2814 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2815 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2821 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2825 int rc, size, tsize;
2827 flags &= MDB_TXN_BEGIN_FLAGS;
2828 flags |= env->me_flags & MDB_WRITEMAP;
2830 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
2834 /* Nested transactions: Max 1 child, write txns only, no writemap */
2835 flags |= parent->mt_flags;
2836 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
2837 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2839 /* Child txns save MDB_pgstate and use own copy of cursors */
2840 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
2841 size += tsize = sizeof(MDB_ntxn);
2842 } else if (flags & MDB_RDONLY) {
2843 size = env->me_maxdbs * (sizeof(MDB_db)+1);
2844 size += tsize = sizeof(MDB_txn);
2846 /* Reuse preallocated write txn. However, do not touch it until
2847 * mdb_txn_renew0() succeeds, since it currently may be active.
2852 if ((txn = calloc(1, size)) == NULL) {
2853 DPRINTF(("calloc: %s", strerror(errno)));
2856 txn->mt_dbxs = env->me_dbxs; /* static */
2857 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2858 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
2859 txn->mt_flags = flags;
2864 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2865 txn->mt_dbiseqs = parent->mt_dbiseqs;
2866 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2867 if (!txn->mt_u.dirty_list ||
2868 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2870 free(txn->mt_u.dirty_list);
2874 txn->mt_txnid = parent->mt_txnid;
2875 txn->mt_dirty_room = parent->mt_dirty_room;
2876 txn->mt_u.dirty_list[0].mid = 0;
2877 txn->mt_spill_pgs = NULL;
2878 txn->mt_next_pgno = parent->mt_next_pgno;
2879 parent->mt_flags |= MDB_TXN_HAS_CHILD;
2880 parent->mt_child = txn;
2881 txn->mt_parent = parent;
2882 txn->mt_numdbs = parent->mt_numdbs;
2883 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2884 /* Copy parent's mt_dbflags, but clear DB_NEW */
2885 for (i=0; i<txn->mt_numdbs; i++)
2886 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2888 ntxn = (MDB_ntxn *)txn;
2889 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2890 if (env->me_pghead) {
2891 size = MDB_IDL_SIZEOF(env->me_pghead);
2892 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2894 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2899 rc = mdb_cursor_shadow(parent, txn);
2901 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
2902 } else { /* MDB_RDONLY */
2903 txn->mt_dbiseqs = env->me_dbiseqs;
2905 rc = mdb_txn_renew0(txn);
2908 if (txn != env->me_txn0)
2911 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
2913 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2914 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
2915 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2922 mdb_txn_env(MDB_txn *txn)
2924 if(!txn) return NULL;
2929 mdb_txn_id(MDB_txn *txn)
2932 return txn->mt_txnid;
2935 /** Export or close DBI handles opened in this txn. */
2937 mdb_dbis_update(MDB_txn *txn, int keep)
2940 MDB_dbi n = txn->mt_numdbs;
2941 MDB_env *env = txn->mt_env;
2942 unsigned char *tdbflags = txn->mt_dbflags;
2944 for (i = n; --i >= CORE_DBS;) {
2945 if (tdbflags[i] & DB_NEW) {
2947 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2949 char *ptr = env->me_dbxs[i].md_name.mv_data;
2951 env->me_dbxs[i].md_name.mv_data = NULL;
2952 env->me_dbxs[i].md_name.mv_size = 0;
2953 env->me_dbflags[i] = 0;
2954 env->me_dbiseqs[i]++;
2960 if (keep && env->me_numdbs < n)
2964 /** End a transaction, except successful commit of a nested transaction.
2965 * May be called twice for readonly txns: First reset it, then abort.
2966 * @param[in] txn the transaction handle to end
2967 * @param[in] mode why and how to end the transaction
2970 mdb_txn_end(MDB_txn *txn, unsigned mode)
2972 MDB_env *env = txn->mt_env;
2974 static const char *const names[] = MDB_END_NAMES;
2977 /* Export or close DBI handles opened in this txn */
2978 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
2980 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2981 names[mode & MDB_END_OPMASK],
2982 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2983 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2985 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2986 if (txn->mt_u.reader) {
2987 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2988 if (!(env->me_flags & MDB_NOTLS)) {
2989 txn->mt_u.reader = NULL; /* txn does not own reader */
2990 } else if (mode & MDB_END_SLOT) {
2991 txn->mt_u.reader->mr_pid = 0;
2992 txn->mt_u.reader = NULL;
2993 } /* else txn owns the slot until it does MDB_END_SLOT */
2995 txn->mt_numdbs = 0; /* prevent further DBI activity */
2996 txn->mt_flags |= MDB_TXN_FINISHED;
2998 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
2999 pgno_t *pghead = env->me_pghead;
3001 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
3002 mdb_cursors_close(txn, 0);
3003 if (!(env->me_flags & MDB_WRITEMAP)) {
3004 mdb_dlist_free(txn);
3008 txn->mt_flags = MDB_TXN_FINISHED;
3010 if (!txn->mt_parent) {
3011 mdb_midl_shrink(&txn->mt_free_pgs);
3012 env->me_free_pgs = txn->mt_free_pgs;
3014 env->me_pghead = NULL;
3018 mode = 0; /* txn == env->me_txn0, do not free() it */
3020 /* The writer mutex was locked in mdb_txn_begin. */
3022 UNLOCK_MUTEX(env->me_wmutex);
3024 txn->mt_parent->mt_child = NULL;
3025 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
3026 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
3027 mdb_midl_free(txn->mt_free_pgs);
3028 mdb_midl_free(txn->mt_spill_pgs);
3029 free(txn->mt_u.dirty_list);
3032 mdb_midl_free(pghead);
3035 if (mode & MDB_END_FREE)
3040 mdb_txn_reset(MDB_txn *txn)
3045 /* This call is only valid for read-only txns */
3046 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3049 mdb_txn_end(txn, MDB_END_RESET);
3053 mdb_txn_abort(MDB_txn *txn)
3059 mdb_txn_abort(txn->mt_child);
3061 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3064 /** Save the freelist as of this transaction to the freeDB.
3065 * This changes the freelist. Keep trying until it stabilizes.
3068 mdb_freelist_save(MDB_txn *txn)
3070 /* env->me_pghead[] can grow and shrink during this call.
3071 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3072 * Page numbers cannot disappear from txn->mt_free_pgs[].
3075 MDB_env *env = txn->mt_env;
3076 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3077 txnid_t pglast = 0, head_id = 0;
3078 pgno_t freecnt = 0, *free_pgs, *mop;
3079 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3081 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3083 if (env->me_pghead) {
3084 /* Make sure first page of freeDB is touched and on freelist */
3085 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3086 if (rc && rc != MDB_NOTFOUND)
3090 if (!env->me_pghead && txn->mt_loose_pgs) {
3091 /* Put loose page numbers in mt_free_pgs, since
3092 * we may be unable to return them to me_pghead.
3094 MDB_page *mp = txn->mt_loose_pgs;
3095 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3097 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3098 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3099 txn->mt_loose_pgs = NULL;
3100 txn->mt_loose_count = 0;
3103 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3104 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3105 ? SSIZE_MAX : maxfree_1pg;
3108 /* Come back here after each Put() in case freelist changed */
3113 /* If using records from freeDB which we have not yet
3114 * deleted, delete them and any we reserved for me_pghead.
3116 while (pglast < env->me_pglast) {
3117 rc = mdb_cursor_first(&mc, &key, NULL);
3120 pglast = head_id = *(txnid_t *)key.mv_data;
3121 total_room = head_room = 0;
3122 mdb_tassert(txn, pglast <= env->me_pglast);
3123 rc = mdb_cursor_del(&mc, 0);
3128 /* Save the IDL of pages freed by this txn, to a single record */
3129 if (freecnt < txn->mt_free_pgs[0]) {
3131 /* Make sure last page of freeDB is touched and on freelist */
3132 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3133 if (rc && rc != MDB_NOTFOUND)
3136 free_pgs = txn->mt_free_pgs;
3137 /* Write to last page of freeDB */
3138 key.mv_size = sizeof(txn->mt_txnid);
3139 key.mv_data = &txn->mt_txnid;
3141 freecnt = free_pgs[0];
3142 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3143 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3146 /* Retry if mt_free_pgs[] grew during the Put() */
3147 free_pgs = txn->mt_free_pgs;
3148 } while (freecnt < free_pgs[0]);
3149 mdb_midl_sort(free_pgs);
3150 memcpy(data.mv_data, free_pgs, data.mv_size);
3153 unsigned int i = free_pgs[0];
3154 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
3155 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3157 DPRINTF(("IDL %"Z"u", free_pgs[i]));
3163 mop = env->me_pghead;
3164 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3166 /* Reserve records for me_pghead[]. Split it if multi-page,
3167 * to avoid searching freeDB for a page range. Use keys in
3168 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3170 if (total_room >= mop_len) {
3171 if (total_room == mop_len || --more < 0)
3173 } else if (head_room >= maxfree_1pg && head_id > 1) {
3174 /* Keep current record (overflow page), add a new one */
3178 /* (Re)write {key = head_id, IDL length = head_room} */
3179 total_room -= head_room;
3180 head_room = mop_len - total_room;
3181 if (head_room > maxfree_1pg && head_id > 1) {
3182 /* Overflow multi-page for part of me_pghead */
3183 head_room /= head_id; /* amortize page sizes */
3184 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3185 } else if (head_room < 0) {
3186 /* Rare case, not bothering to delete this record */
3189 key.mv_size = sizeof(head_id);
3190 key.mv_data = &head_id;
3191 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3192 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3195 /* IDL is initially empty, zero out at least the length */
3196 pgs = (pgno_t *)data.mv_data;
3197 j = head_room > clean_limit ? head_room : 0;
3201 total_room += head_room;
3204 /* Return loose page numbers to me_pghead, though usually none are
3205 * left at this point. The pages themselves remain in dirty_list.
3207 if (txn->mt_loose_pgs) {
3208 MDB_page *mp = txn->mt_loose_pgs;
3209 unsigned count = txn->mt_loose_count;
3211 /* Room for loose pages + temp IDL with same */
3212 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3214 mop = env->me_pghead;
3215 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3216 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3217 loose[ ++count ] = mp->mp_pgno;
3219 mdb_midl_sort(loose);
3220 mdb_midl_xmerge(mop, loose);
3221 txn->mt_loose_pgs = NULL;
3222 txn->mt_loose_count = 0;
3226 /* Fill in the reserved me_pghead records */
3232 rc = mdb_cursor_first(&mc, &key, &data);
3233 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3234 txnid_t id = *(txnid_t *)key.mv_data;
3235 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3238 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3240 if (len > mop_len) {
3242 data.mv_size = (len + 1) * sizeof(MDB_ID);
3244 data.mv_data = mop -= len;
3247 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3249 if (rc || !(mop_len -= len))
3256 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3257 * @param[in] txn the transaction that's being committed
3258 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3259 * @return 0 on success, non-zero on failure.
3262 mdb_page_flush(MDB_txn *txn, int keep)
3264 MDB_env *env = txn->mt_env;
3265 MDB_ID2L dl = txn->mt_u.dirty_list;
3266 unsigned psize = env->me_psize, j;
3267 int i, pagecount = dl[0].mid, rc;
3268 size_t size = 0, pos = 0;
3270 MDB_page *dp = NULL;
3274 struct iovec iov[MDB_COMMIT_PAGES];
3275 ssize_t wpos = 0, wsize = 0, wres;
3276 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3282 if (env->me_flags & MDB_WRITEMAP) {
3283 /* Clear dirty flags */
3284 while (++i <= pagecount) {
3286 /* Don't flush this page yet */
3287 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3288 dp->mp_flags &= ~P_KEEP;
3292 dp->mp_flags &= ~P_DIRTY;
3297 /* Write the pages */
3299 if (++i <= pagecount) {
3301 /* Don't flush this page yet */
3302 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3303 dp->mp_flags &= ~P_KEEP;
3308 /* clear dirty flag */
3309 dp->mp_flags &= ~P_DIRTY;
3312 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3317 /* Windows actually supports scatter/gather I/O, but only on
3318 * unbuffered file handles. Since we're relying on the OS page
3319 * cache for all our data, that's self-defeating. So we just
3320 * write pages one at a time. We use the ov structure to set
3321 * the write offset, to at least save the overhead of a Seek
3324 DPRINTF(("committing page %"Z"u", pgno));
3325 memset(&ov, 0, sizeof(ov));
3326 ov.Offset = pos & 0xffffffff;
3327 ov.OffsetHigh = pos >> 16 >> 16;
3328 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3330 DPRINTF(("WriteFile: %d", rc));
3334 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3335 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3338 /* Write previous page(s) */
3339 #ifdef MDB_USE_PWRITEV
3340 wres = pwritev(env->me_fd, iov, n, wpos);
3343 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3346 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3350 DPRINTF(("lseek: %s", strerror(rc)));
3353 wres = writev(env->me_fd, iov, n);
3356 if (wres != wsize) {
3361 DPRINTF(("Write error: %s", strerror(rc)));
3363 rc = EIO; /* TODO: Use which error code? */
3364 DPUTS("short write, filesystem full?");
3375 DPRINTF(("committing page %"Z"u", pgno));
3376 next_pos = pos + size;
3377 iov[n].iov_len = size;
3378 iov[n].iov_base = (char *)dp;
3384 /* MIPS has cache coherency issues, this is a no-op everywhere else
3385 * Note: for any size >= on-chip cache size, entire on-chip cache is
3388 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3390 for (i = keep; ++i <= pagecount; ) {
3392 /* This is a page we skipped above */
3395 dl[j].mid = dp->mp_pgno;
3398 mdb_dpage_free(env, dp);
3403 txn->mt_dirty_room += i - j;
3409 mdb_txn_commit(MDB_txn *txn)
3412 unsigned int i, end_mode;
3418 /* mdb_txn_end() mode for a commit which writes nothing */
3419 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3421 if (txn->mt_child) {
3422 rc = mdb_txn_commit(txn->mt_child);
3429 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3433 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3434 DPUTS("txn has failed/finished, can't commit");
3436 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3441 if (txn->mt_parent) {
3442 MDB_txn *parent = txn->mt_parent;
3446 unsigned x, y, len, ps_len;
3448 /* Append our free list to parent's */
3449 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3452 mdb_midl_free(txn->mt_free_pgs);
3453 /* Failures after this must either undo the changes
3454 * to the parent or set MDB_TXN_ERROR in the parent.
3457 parent->mt_next_pgno = txn->mt_next_pgno;
3458 parent->mt_flags = txn->mt_flags;
3460 /* Merge our cursors into parent's and close them */
3461 mdb_cursors_close(txn, 1);
3463 /* Update parent's DB table. */
3464 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3465 parent->mt_numdbs = txn->mt_numdbs;
3466 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3467 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3468 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3469 /* preserve parent's DB_NEW status */
3470 x = parent->mt_dbflags[i] & DB_NEW;
3471 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3474 dst = parent->mt_u.dirty_list;
3475 src = txn->mt_u.dirty_list;
3476 /* Remove anything in our dirty list from parent's spill list */
3477 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3479 pspill[0] = (pgno_t)-1;
3480 /* Mark our dirty pages as deleted in parent spill list */
3481 for (i=0, len=src[0].mid; ++i <= len; ) {
3482 MDB_ID pn = src[i].mid << 1;
3483 while (pn > pspill[x])
3485 if (pn == pspill[x]) {
3490 /* Squash deleted pagenums if we deleted any */
3491 for (x=y; ++x <= ps_len; )
3492 if (!(pspill[x] & 1))
3493 pspill[++y] = pspill[x];
3497 /* Remove anything in our spill list from parent's dirty list */
3498 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3499 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3500 MDB_ID pn = txn->mt_spill_pgs[i];
3502 continue; /* deleted spillpg */
3504 y = mdb_mid2l_search(dst, pn);
3505 if (y <= dst[0].mid && dst[y].mid == pn) {
3507 while (y < dst[0].mid) {
3516 /* Find len = length of merging our dirty list with parent's */
3518 dst[0].mid = 0; /* simplify loops */
3519 if (parent->mt_parent) {
3520 len = x + src[0].mid;
3521 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3522 for (i = x; y && i; y--) {
3523 pgno_t yp = src[y].mid;
3524 while (yp < dst[i].mid)
3526 if (yp == dst[i].mid) {
3531 } else { /* Simplify the above for single-ancestor case */
3532 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3534 /* Merge our dirty list with parent's */
3536 for (i = len; y; dst[i--] = src[y--]) {
3537 pgno_t yp = src[y].mid;
3538 while (yp < dst[x].mid)
3539 dst[i--] = dst[x--];
3540 if (yp == dst[x].mid)
3541 free(dst[x--].mptr);
3543 mdb_tassert(txn, i == x);
3545 free(txn->mt_u.dirty_list);
3546 parent->mt_dirty_room = txn->mt_dirty_room;
3547 if (txn->mt_spill_pgs) {
3548 if (parent->mt_spill_pgs) {
3549 /* TODO: Prevent failure here, so parent does not fail */
3550 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3552 parent->mt_flags |= MDB_TXN_ERROR;
3553 mdb_midl_free(txn->mt_spill_pgs);
3554 mdb_midl_sort(parent->mt_spill_pgs);
3556 parent->mt_spill_pgs = txn->mt_spill_pgs;
3560 /* Append our loose page list to parent's */
3561 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3563 *lp = txn->mt_loose_pgs;
3564 parent->mt_loose_count += txn->mt_loose_count;
3566 parent->mt_child = NULL;
3567 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3572 if (txn != env->me_txn) {
3573 DPUTS("attempt to commit unknown transaction");
3578 mdb_cursors_close(txn, 0);
3580 if (!txn->mt_u.dirty_list[0].mid &&
3581 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3584 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3585 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3587 /* Update DB root pointers */
3588 if (txn->mt_numdbs > CORE_DBS) {
3592 data.mv_size = sizeof(MDB_db);
3594 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3595 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3596 if (txn->mt_dbflags[i] & DB_DIRTY) {
3597 if (TXN_DBI_CHANGED(txn, i)) {
3601 data.mv_data = &txn->mt_dbs[i];
3602 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3610 rc = mdb_freelist_save(txn);
3614 mdb_midl_free(env->me_pghead);
3615 env->me_pghead = NULL;
3616 mdb_midl_shrink(&txn->mt_free_pgs);
3622 if ((rc = mdb_page_flush(txn, 0)) ||
3623 (rc = mdb_env_sync(env, 0)) ||
3624 (rc = mdb_env_write_meta(txn)))
3626 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3629 mdb_txn_end(txn, end_mode);
3637 /** Read the environment parameters of a DB environment before
3638 * mapping it into memory.
3639 * @param[in] env the environment handle
3640 * @param[out] meta address of where to store the meta information
3641 * @return 0 on success, non-zero on failure.
3644 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3650 enum { Size = sizeof(pbuf) };
3652 /* We don't know the page size yet, so use a minimum value.
3653 * Read both meta pages so we can use the latest one.
3656 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3660 memset(&ov, 0, sizeof(ov));
3662 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3663 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3666 rc = pread(env->me_fd, &pbuf, Size, off);
3669 if (rc == 0 && off == 0)
3671 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3672 DPRINTF(("read: %s", mdb_strerror(rc)));
3676 p = (MDB_page *)&pbuf;
3678 if (!F_ISSET(p->mp_flags, P_META)) {
3679 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3684 if (m->mm_magic != MDB_MAGIC) {
3685 DPUTS("meta has invalid magic");
3689 if (m->mm_version != MDB_DATA_VERSION) {
3690 DPRINTF(("database is version %u, expected version %u",
3691 m->mm_version, MDB_DATA_VERSION));
3692 return MDB_VERSION_MISMATCH;
3695 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3701 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3703 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3705 meta->mm_magic = MDB_MAGIC;
3706 meta->mm_version = MDB_DATA_VERSION;
3707 meta->mm_mapsize = env->me_mapsize;
3708 meta->mm_psize = env->me_psize;
3709 meta->mm_last_pg = NUM_METAS-1;
3710 meta->mm_flags = env->me_flags & 0xffff;
3711 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3712 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3713 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3716 /** Write the environment parameters of a freshly created DB environment.
3717 * @param[in] env the environment handle
3718 * @param[in] meta the #MDB_meta to write
3719 * @return 0 on success, non-zero on failure.
3722 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3730 memset(&ov, 0, sizeof(ov));
3731 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3733 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3736 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3737 len = pwrite(fd, ptr, size, pos); \
3738 if (len == -1 && ErrCode() == EINTR) continue; \
3739 rc = (len >= 0); break; } while(1)
3742 DPUTS("writing new meta page");
3744 psize = env->me_psize;
3746 p = calloc(NUM_METAS, psize);
3751 p->mp_flags = P_META;
3752 *(MDB_meta *)METADATA(p) = *meta;
3754 q = (MDB_page *)((char *)p + psize);
3756 q->mp_flags = P_META;
3757 *(MDB_meta *)METADATA(q) = *meta;
3759 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
3762 else if ((unsigned) len == psize * NUM_METAS)
3770 /** Update the environment info to commit a transaction.
3771 * @param[in] txn the transaction that's being committed
3772 * @return 0 on success, non-zero on failure.
3775 mdb_env_write_meta(MDB_txn *txn)
3778 MDB_meta meta, metab, *mp;
3782 int rc, len, toggle;
3791 toggle = txn->mt_txnid & 1;
3792 DPRINTF(("writing meta page %d for root page %"Z"u",
3793 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3796 flags = env->me_flags;
3797 mp = env->me_metas[toggle];
3798 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3799 /* Persist any increases of mapsize config */
3800 if (mapsize < env->me_mapsize)
3801 mapsize = env->me_mapsize;
3803 if (flags & MDB_WRITEMAP) {
3804 mp->mm_mapsize = mapsize;
3805 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3806 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3807 mp->mm_last_pg = txn->mt_next_pgno - 1;
3808 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
3809 !(defined(__i386__) || defined(__x86_64__))
3810 /* LY: issue a memory barrier, if not x86. ITS#7969 */
3811 __sync_synchronize();
3813 mp->mm_txnid = txn->mt_txnid;
3814 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3815 unsigned meta_size = env->me_psize;
3816 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3817 ptr = (char *)mp - PAGEHDRSZ;
3818 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3819 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
3823 if (MDB_MSYNC(ptr, meta_size, rc)) {
3830 metab.mm_txnid = mp->mm_txnid;
3831 metab.mm_last_pg = mp->mm_last_pg;
3833 meta.mm_mapsize = mapsize;
3834 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3835 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3836 meta.mm_last_pg = txn->mt_next_pgno - 1;
3837 meta.mm_txnid = txn->mt_txnid;
3839 off = offsetof(MDB_meta, mm_mapsize);
3840 ptr = (char *)&meta + off;
3841 len = sizeof(MDB_meta) - off;
3842 off += (char *)mp - env->me_map;
3844 /* Write to the SYNC fd unless MDB_NOSYNC/MDB_NOMETASYNC.
3845 * (me_mfd goes to the same file as me_fd, but writing to it
3846 * also syncs to disk. Avoids a separate fdatasync() call.)
3848 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
3851 memset(&ov, 0, sizeof(ov));
3853 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3858 rc = pwrite(mfd, ptr, len, off);
3861 rc = rc < 0 ? ErrCode() : EIO;
3866 DPUTS("write failed, disk error?");
3867 /* On a failure, the pagecache still contains the new data.
3868 * Write some old data back, to prevent it from being used.
3869 * Use the non-SYNC fd; we know it will fail anyway.
3871 meta.mm_last_pg = metab.mm_last_pg;
3872 meta.mm_txnid = metab.mm_txnid;
3874 memset(&ov, 0, sizeof(ov));
3876 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3878 r2 = pwrite(env->me_fd, ptr, len, off);
3879 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3882 env->me_flags |= MDB_FATAL_ERROR;
3885 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3886 CACHEFLUSH(env->me_map + off, len, DCACHE);
3888 /* Memory ordering issues are irrelevant; since the entire writer
3889 * is wrapped by wmutex, all of these changes will become visible
3890 * after the wmutex is unlocked. Since the DB is multi-version,
3891 * readers will get consistent data regardless of how fresh or
3892 * how stale their view of these values is.
3895 env->me_txns->mti_txnid = txn->mt_txnid;
3900 /** Check both meta pages to see which one is newer.
3901 * @param[in] env the environment handle
3902 * @return newest #MDB_meta.
3905 mdb_env_pick_meta(const MDB_env *env)
3907 MDB_meta *const *metas = env->me_metas;
3908 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
3912 mdb_env_create(MDB_env **env)
3916 e = calloc(1, sizeof(MDB_env));
3920 e->me_maxreaders = DEFAULT_READERS;
3921 e->me_maxdbs = e->me_numdbs = CORE_DBS;
3922 e->me_fd = INVALID_HANDLE_VALUE;
3923 e->me_lfd = INVALID_HANDLE_VALUE;
3924 e->me_mfd = INVALID_HANDLE_VALUE;
3925 #ifdef MDB_USE_POSIX_SEM
3926 e->me_rmutex = SEM_FAILED;
3927 e->me_wmutex = SEM_FAILED;
3929 e->me_pid = getpid();
3930 GET_PAGESIZE(e->me_os_psize);
3931 VGMEMP_CREATE(e,0,0);
3937 mdb_env_map(MDB_env *env, void *addr)
3940 unsigned int flags = env->me_flags;
3944 LONG sizelo, sizehi;
3947 if (flags & MDB_RDONLY) {
3948 /* Don't set explicit map size, use whatever exists */
3953 msize = env->me_mapsize;
3954 sizelo = msize & 0xffffffff;
3955 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3957 /* Windows won't create mappings for zero length files.
3958 * and won't map more than the file size.
3959 * Just set the maxsize right now.
3961 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3962 || !SetEndOfFile(env->me_fd)
3963 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3967 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3968 PAGE_READWRITE : PAGE_READONLY,
3969 sizehi, sizelo, NULL);
3972 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3973 FILE_MAP_WRITE : FILE_MAP_READ,
3975 rc = env->me_map ? 0 : ErrCode();
3980 int prot = PROT_READ;
3981 if (flags & MDB_WRITEMAP) {
3983 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3986 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3988 if (env->me_map == MAP_FAILED) {
3993 if (flags & MDB_NORDAHEAD) {
3994 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3996 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3998 #ifdef POSIX_MADV_RANDOM
3999 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
4000 #endif /* POSIX_MADV_RANDOM */
4001 #endif /* MADV_RANDOM */
4005 /* Can happen because the address argument to mmap() is just a
4006 * hint. mmap() can pick another, e.g. if the range is in use.
4007 * The MAP_FIXED flag would prevent that, but then mmap could
4008 * instead unmap existing pages to make room for the new map.
4010 if (addr && env->me_map != addr)
4011 return EBUSY; /* TODO: Make a new MDB_* error code? */
4013 p = (MDB_page *)env->me_map;
4014 env->me_metas[0] = METADATA(p);
4015 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
4021 mdb_env_set_mapsize(MDB_env *env, size_t size)
4023 /* If env is already open, caller is responsible for making
4024 * sure there are no active txns.
4032 meta = mdb_env_pick_meta(env);
4034 size = meta->mm_mapsize;
4036 /* Silently round up to minimum if the size is too small */
4037 size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
4041 munmap(env->me_map, env->me_mapsize);
4042 env->me_mapsize = size;
4043 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4044 rc = mdb_env_map(env, old);
4048 env->me_mapsize = size;
4050 env->me_maxpg = env->me_mapsize / env->me_psize;
4055 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4059 env->me_maxdbs = dbs + CORE_DBS;
4064 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4066 if (env->me_map || readers < 1)
4068 env->me_maxreaders = readers;
4073 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4075 if (!env || !readers)
4077 *readers = env->me_maxreaders;
4082 mdb_fsize(HANDLE fd, size_t *size)
4085 LARGE_INTEGER fsize;
4087 if (!GetFileSizeEx(fd, &fsize))
4090 *size = fsize.QuadPart;
4104 typedef wchar_t mdb_nchar_t;
4105 # define MDB_NAME(str) L##str
4106 # define mdb_name_cpy wcscpy
4108 /** Character type for file names: char on Unix, wchar_t on Windows */
4109 typedef char mdb_nchar_t;
4110 # define MDB_NAME(str) str /**< #mdb_nchar_t[] string literal */
4111 # define mdb_name_cpy strcpy /**< Copy name (#mdb_nchar_t string) */
4114 /** Filename - string of #mdb_nchar_t[] */
4115 typedef struct MDB_name {
4116 int mn_len; /**< Length */
4117 int mn_alloced; /**< True if #mn_val was malloced */
4118 mdb_nchar_t *mn_val; /**< Contents */
4121 /** Filename suffixes [datafile,lockfile][without,with MDB_NOSUBDIR] */
4122 static const mdb_nchar_t *const mdb_suffixes[2][2] = {
4123 { MDB_NAME("/data.mdb"), MDB_NAME("") },
4124 { MDB_NAME("/lock.mdb"), MDB_NAME("-lock") }
4127 #define MDB_SUFFLEN 9 /**< Max string length in #mdb_suffixes[] */
4129 /** Set up filename + scratch area for filename suffix, for opening files.
4130 * It should be freed with #mdb_fname_destroy().
4131 * On Windows, paths are converted from char *UTF-8 to wchar_t *UTF-16.
4133 * @param[in] path Pathname for #mdb_env_open().
4134 * @param[in] envflags Whether a subdir and/or lockfile will be used.
4135 * @param[out] fname Resulting filename, with room for a suffix if necessary.
4138 mdb_fname_init(const char *path, unsigned envflags, MDB_name *fname)
4140 int no_suffix = F_ISSET(envflags, MDB_NOSUBDIR|MDB_NOLOCK);
4141 fname->mn_alloced = 0;
4143 return utf8_to_utf16(path, fname, no_suffix ? 0 : MDB_SUFFLEN);
4145 fname->mn_len = strlen(path);
4147 fname->mn_val = (char *) path;
4148 else if ((fname->mn_val = malloc(fname->mn_len + MDB_SUFFLEN+1)) != NULL) {
4149 fname->mn_alloced = 1;
4150 strcpy(fname->mn_val, path);
4158 /** Destroy \b fname from #mdb_fname_init() */
4159 #define mdb_fname_destroy(fname) \
4160 do { if ((fname).mn_alloced) free((fname).mn_val); } while (0)
4162 #ifdef O_CLOEXEC /* POSIX.1-2008: Set FD_CLOEXEC atomically at open() */
4163 # define MDB_CLOEXEC O_CLOEXEC
4165 # define MDB_CLOEXEC 0
4168 /** File type, access mode etc. for #mdb_fopen() */
4169 enum mdb_fopen_type {
4171 MDB_O_RDONLY, MDB_O_RDWR, MDB_O_META, MDB_O_COPY, MDB_O_LOCKS
4173 /* A comment in mdb_fopen() explains some O_* flag choices. */
4174 MDB_O_RDONLY= O_RDONLY, /**< for RDONLY me_fd */
4175 MDB_O_RDWR = O_RDWR |O_CREAT, /**< for me_fd */
4176 MDB_O_META = O_WRONLY|MDB_DSYNC |MDB_CLOEXEC, /**< for me_mfd */
4177 MDB_O_COPY = O_WRONLY|O_CREAT|O_EXCL|MDB_CLOEXEC, /**< for #mdb_env_copy() */
4178 /** Bitmask for open() flags in enum #mdb_fopen_type. The other bits
4179 * distinguish otherwise-equal MDB_O_* constants from each other.
4181 MDB_O_MASK = MDB_O_RDWR|MDB_CLOEXEC | MDB_O_RDONLY|MDB_O_META|MDB_O_COPY,
4182 MDB_O_LOCKS = MDB_O_RDWR|MDB_CLOEXEC | ((MDB_O_MASK+1) & ~MDB_O_MASK) /**< for me_lfd */
4186 /** Open an LMDB file.
4187 * @param[in] env The LMDB environment.
4188 * @param[in,out] fname Path from from #mdb_fname_init(). A suffix is
4189 * appended if necessary to create the filename, without changing mn_len.
4190 * @param[in] which Determines file type, access mode, etc.
4191 * @param[in] mode The Unix permissions for the file, if we create it.
4192 * @param[out] res Resulting file handle.
4193 * @return 0 on success, non-zero on failure.
4196 mdb_fopen(const MDB_env *env, MDB_name *fname,
4197 enum mdb_fopen_type which, mdb_mode_t mode,
4200 int rc = MDB_SUCCESS;
4203 DWORD acc, share, disp, attrs;
4208 if (fname->mn_alloced) /* modifiable copy */
4209 mdb_name_cpy(fname->mn_val + fname->mn_len,
4210 mdb_suffixes[which==MDB_O_LOCKS][F_ISSET(env->me_flags, MDB_NOSUBDIR)]);
4212 /* The directory must already exist. Usually the file need not.
4213 * MDB_O_META requires the file because we already created it using
4214 * MDB_O_RDWR. MDB_O_COPY must not overwrite an existing file.
4216 * With MDB_O_COPY we do not want the OS to cache the writes, since
4217 * the source data is already in the OS cache.
4219 * The lockfile needs FD_CLOEXEC (close file descriptor on exec*())
4220 * to avoid the flock() issues noted under Caveats in lmdb.h.
4221 * Also set it for other filehandles which the user cannot get at
4222 * and close himself, which he may need after fork(). I.e. all but
4223 * me_fd, which programs do use via mdb_env_get_fd().
4227 acc = GENERIC_READ|GENERIC_WRITE;
4228 share = FILE_SHARE_READ|FILE_SHARE_WRITE;
4230 attrs = FILE_ATTRIBUTE_NORMAL;
4232 case MDB_O_RDONLY: /* read-only datafile */
4234 disp = OPEN_EXISTING;
4236 case MDB_O_META: /* for writing metapages */
4237 acc = GENERIC_WRITE;
4238 disp = OPEN_EXISTING;
4239 attrs = FILE_ATTRIBUTE_NORMAL|FILE_FLAG_WRITE_THROUGH;
4241 case MDB_O_COPY: /* mdb_env_copy() & co */
4242 acc = GENERIC_WRITE;
4245 attrs = FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH;
4247 default: break; /* silence gcc -Wswitch (not all enum values handled) */
4249 fd = CreateFileW(fname->mn_val, acc, share, NULL, disp, attrs, NULL);
4251 fd = open(fname->mn_val, which & MDB_O_MASK, mode);
4254 if (fd == INVALID_HANDLE_VALUE)
4258 if (which != MDB_O_RDONLY && which != MDB_O_RDWR) {
4259 /* Set CLOEXEC if we could not pass it to open() */
4260 if (!MDB_CLOEXEC && (flags = fcntl(fd, F_GETFD)) != -1)
4261 (void) fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
4263 if (which == MDB_O_COPY && env->me_psize >= env->me_os_psize) {
4264 /* This may require buffer alignment. There is no portable
4265 * way to ask how much, so we require OS pagesize alignment.
4267 # ifdef F_NOCACHE /* __APPLE__ */
4268 (void) fcntl(fd, F_NOCACHE, 1);
4269 # elif defined O_DIRECT
4270 /* open(...O_DIRECT...) would break on filesystems without
4271 * O_DIRECT support (ITS#7682). Try to set it here instead.
4273 if ((flags = fcntl(fd, F_GETFL)) != -1)
4274 (void) fcntl(fd, F_SETFL, flags | O_DIRECT);
4278 #endif /* !_WIN32 */
4285 #ifdef BROKEN_FDATASYNC
4286 #include <sys/utsname.h>
4287 #include <sys/vfs.h>
4290 /** Further setup required for opening an LMDB environment
4293 mdb_env_open2(MDB_env *env)
4295 unsigned int flags = env->me_flags;
4296 int i, newenv = 0, rc;
4300 /* See if we should use QueryLimited */
4302 if ((rc & 0xff) > 5)
4303 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4305 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4308 #ifdef BROKEN_FDATASYNC
4309 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4310 * https://lkml.org/lkml/2012/9/3/83
4311 * Kernels after 3.6-rc6 are known good.
4312 * https://lkml.org/lkml/2012/9/10/556
4313 * See if the DB is on ext3/ext4, then check for new enough kernel
4314 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4319 fstatfs(env->me_fd, &st);
4320 while (st.f_type == 0xEF53) {
4324 if (uts.release[0] < '3') {
4325 if (!strncmp(uts.release, "2.6.32.", 7)) {
4326 i = atoi(uts.release+7);
4328 break; /* 2.6.32.60 and newer is OK */
4329 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4330 i = atoi(uts.release+7);
4332 break; /* 2.6.34.15 and newer is OK */
4334 } else if (uts.release[0] == '3') {
4335 i = atoi(uts.release+2);
4337 break; /* 3.6 and newer is OK */
4339 i = atoi(uts.release+4);
4341 break; /* 3.5.4 and newer is OK */
4342 } else if (i == 2) {
4343 i = atoi(uts.release+4);
4345 break; /* 3.2.30 and newer is OK */
4347 } else { /* 4.x and newer is OK */
4350 env->me_flags |= MDB_FSYNCONLY;
4356 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4359 DPUTS("new mdbenv");
4361 env->me_psize = env->me_os_psize;
4362 if (env->me_psize > MAX_PAGESIZE)
4363 env->me_psize = MAX_PAGESIZE;
4364 memset(&meta, 0, sizeof(meta));
4365 mdb_env_init_meta0(env, &meta);
4366 meta.mm_mapsize = DEFAULT_MAPSIZE;
4368 env->me_psize = meta.mm_psize;
4371 /* Was a mapsize configured? */
4372 if (!env->me_mapsize) {
4373 env->me_mapsize = meta.mm_mapsize;
4376 /* Make sure mapsize >= committed data size. Even when using
4377 * mm_mapsize, which could be broken in old files (ITS#7789).
4379 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4380 if (env->me_mapsize < minsize)
4381 env->me_mapsize = minsize;
4383 meta.mm_mapsize = env->me_mapsize;
4385 if (newenv && !(flags & MDB_FIXEDMAP)) {
4386 /* mdb_env_map() may grow the datafile. Write the metapages
4387 * first, so the file will be valid if initialization fails.
4388 * Except with FIXEDMAP, since we do not yet know mm_address.
4389 * We could fill in mm_address later, but then a different
4390 * program might end up doing that - one with a memory layout
4391 * and map address which does not suit the main program.
4393 rc = mdb_env_init_meta(env, &meta);
4399 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4404 if (flags & MDB_FIXEDMAP)
4405 meta.mm_address = env->me_map;
4406 i = mdb_env_init_meta(env, &meta);
4407 if (i != MDB_SUCCESS) {
4412 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4413 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4415 #if !(MDB_MAXKEYSIZE)
4416 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4418 env->me_maxpg = env->me_mapsize / env->me_psize;
4422 MDB_meta *meta = mdb_env_pick_meta(env);
4423 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4425 DPRINTF(("opened database version %u, pagesize %u",
4426 meta->mm_version, env->me_psize));
4427 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4428 DPRINTF(("depth: %u", db->md_depth));
4429 DPRINTF(("entries: %"Z"u", db->md_entries));
4430 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
4431 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
4432 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
4433 DPRINTF(("root: %"Z"u", db->md_root));
4441 /** Release a reader thread's slot in the reader lock table.
4442 * This function is called automatically when a thread exits.
4443 * @param[in] ptr This points to the slot in the reader lock table.
4446 mdb_env_reader_dest(void *ptr)
4448 MDB_reader *reader = ptr;
4451 if (reader->mr_pid == getpid()) /* catch pthread_exit() in child process */
4453 /* We omit the mutex, so do this atomically (i.e. skip mr_txnid) */
4458 /** Junk for arranging thread-specific callbacks on Windows. This is
4459 * necessarily platform and compiler-specific. Windows supports up
4460 * to 1088 keys. Let's assume nobody opens more than 64 environments
4461 * in a single process, for now. They can override this if needed.
4463 #ifndef MAX_TLS_KEYS
4464 #define MAX_TLS_KEYS 64
4466 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4467 static int mdb_tls_nkeys;
4469 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4473 case DLL_PROCESS_ATTACH: break;
4474 case DLL_THREAD_ATTACH: break;
4475 case DLL_THREAD_DETACH:
4476 for (i=0; i<mdb_tls_nkeys; i++) {
4477 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4479 mdb_env_reader_dest(r);
4483 case DLL_PROCESS_DETACH: break;
4488 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4490 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4494 /* Force some symbol references.
4495 * _tls_used forces the linker to create the TLS directory if not already done
4496 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4498 #pragma comment(linker, "/INCLUDE:_tls_used")
4499 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4500 #pragma const_seg(".CRT$XLB")
4501 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4502 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4505 #pragma comment(linker, "/INCLUDE:__tls_used")
4506 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4507 #pragma data_seg(".CRT$XLB")
4508 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4510 #endif /* WIN 32/64 */
4511 #endif /* !__GNUC__ */
4514 /** Downgrade the exclusive lock on the region back to shared */
4516 mdb_env_share_locks(MDB_env *env, int *excl)
4519 MDB_meta *meta = mdb_env_pick_meta(env);
4521 env->me_txns->mti_txnid = meta->mm_txnid;
4526 /* First acquire a shared lock. The Unlock will
4527 * then release the existing exclusive lock.
4529 memset(&ov, 0, sizeof(ov));
4530 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4533 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4539 struct flock lock_info;
4540 /* The shared lock replaces the existing lock */
4541 memset((void *)&lock_info, 0, sizeof(lock_info));
4542 lock_info.l_type = F_RDLCK;
4543 lock_info.l_whence = SEEK_SET;
4544 lock_info.l_start = 0;
4545 lock_info.l_len = 1;
4546 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4547 (rc = ErrCode()) == EINTR) ;
4548 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4555 /** Try to get exclusive lock, otherwise shared.
4556 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4559 mdb_env_excl_lock(MDB_env *env, int *excl)
4563 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4567 memset(&ov, 0, sizeof(ov));
4568 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4575 struct flock lock_info;
4576 memset((void *)&lock_info, 0, sizeof(lock_info));
4577 lock_info.l_type = F_WRLCK;
4578 lock_info.l_whence = SEEK_SET;
4579 lock_info.l_start = 0;
4580 lock_info.l_len = 1;
4581 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4582 (rc = ErrCode()) == EINTR) ;
4586 # ifndef MDB_USE_POSIX_MUTEX
4587 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4590 lock_info.l_type = F_RDLCK;
4591 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4592 (rc = ErrCode()) == EINTR) ;
4602 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4604 * @(#) $Revision: 5.1 $
4605 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4606 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4608 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4612 * Please do not copyright this code. This code is in the public domain.
4614 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4615 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4616 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4617 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4618 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4619 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4620 * PERFORMANCE OF THIS SOFTWARE.
4623 * chongo <Landon Curt Noll> /\oo/\
4624 * http://www.isthe.com/chongo/
4626 * Share and Enjoy! :-)
4629 typedef unsigned long long mdb_hash_t;
4630 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4632 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4633 * @param[in] val value to hash
4634 * @param[in] hval initial value for hash
4635 * @return 64 bit hash
4637 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4638 * hval arg on the first call.
4641 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4643 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4644 unsigned char *end = s + val->mv_size;
4646 * FNV-1a hash each octet of the string
4649 /* xor the bottom with the current octet */
4650 hval ^= (mdb_hash_t)*s++;
4652 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4653 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4654 (hval << 7) + (hval << 8) + (hval << 40);
4656 /* return our new hash value */
4660 /** Hash the string and output the encoded hash.
4661 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4662 * very short name limits. We don't care about the encoding being reversible,
4663 * we just want to preserve as many bits of the input as possible in a
4664 * small printable string.
4665 * @param[in] str string to hash
4666 * @param[out] encbuf an array of 11 chars to hold the hash
4668 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4671 mdb_pack85(unsigned long l, char *out)
4675 for (i=0; i<5; i++) {
4676 *out++ = mdb_a85[l % 85];
4682 mdb_hash_enc(MDB_val *val, char *encbuf)
4684 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4686 mdb_pack85(h, encbuf);
4687 mdb_pack85(h>>32, encbuf+5);
4692 /** Open and/or initialize the lock region for the environment.
4693 * @param[in] env The LMDB environment.
4694 * @param[in] fname Filename + scratch area, from #mdb_fname_init().
4695 * @param[in] mode The Unix permissions for the file, if we create it.
4696 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4697 * @return 0 on success, non-zero on failure.
4700 mdb_env_setup_locks(MDB_env *env, MDB_name *fname, int mode, int *excl)
4703 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4705 # define MDB_ERRCODE_ROFS EROFS
4710 rc = mdb_fopen(env, fname, MDB_O_LOCKS, mode, &env->me_lfd);
4712 /* Omit lockfile if read-only env on read-only filesystem */
4713 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4719 if (!(env->me_flags & MDB_NOTLS)) {
4720 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4723 env->me_flags |= MDB_ENV_TXKEY;
4725 /* Windows TLS callbacks need help finding their TLS info. */
4726 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4730 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4734 /* Try to get exclusive lock. If we succeed, then
4735 * nobody is using the lock region and we should initialize it.
4737 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4740 size = GetFileSize(env->me_lfd, NULL);
4742 size = lseek(env->me_lfd, 0, SEEK_END);
4743 if (size == -1) goto fail_errno;
4745 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4746 if (size < rsize && *excl > 0) {
4748 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4749 || !SetEndOfFile(env->me_lfd))
4752 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4756 size = rsize - sizeof(MDB_txninfo);
4757 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4762 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4764 if (!mh) goto fail_errno;
4765 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4767 if (!env->me_txns) goto fail_errno;
4769 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4771 if (m == MAP_FAILED) goto fail_errno;
4777 BY_HANDLE_FILE_INFORMATION stbuf;
4786 if (!mdb_sec_inited) {
4787 InitializeSecurityDescriptor(&mdb_null_sd,
4788 SECURITY_DESCRIPTOR_REVISION);
4789 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4790 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4791 mdb_all_sa.bInheritHandle = FALSE;
4792 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4795 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4796 idbuf.volume = stbuf.dwVolumeSerialNumber;
4797 idbuf.nhigh = stbuf.nFileIndexHigh;
4798 idbuf.nlow = stbuf.nFileIndexLow;
4799 val.mv_data = &idbuf;
4800 val.mv_size = sizeof(idbuf);
4801 mdb_hash_enc(&val, encbuf);
4802 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4803 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4804 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4805 if (!env->me_rmutex) goto fail_errno;
4806 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4807 if (!env->me_wmutex) goto fail_errno;
4808 #elif defined(MDB_USE_POSIX_SEM)
4817 #if defined(__NetBSD__)
4818 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4820 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4821 idbuf.dev = stbuf.st_dev;
4822 idbuf.ino = stbuf.st_ino;
4823 val.mv_data = &idbuf;
4824 val.mv_size = sizeof(idbuf);
4825 mdb_hash_enc(&val, encbuf);
4826 #ifdef MDB_SHORT_SEMNAMES
4827 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4829 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4830 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4831 /* Clean up after a previous run, if needed: Try to
4832 * remove both semaphores before doing anything else.
4834 sem_unlink(env->me_txns->mti_rmname);
4835 sem_unlink(env->me_txns->mti_wmname);
4836 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4837 O_CREAT|O_EXCL, mode, 1);
4838 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4839 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4840 O_CREAT|O_EXCL, mode, 1);
4841 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4842 #else /* MDB_USE_POSIX_MUTEX: */
4843 pthread_mutexattr_t mattr;
4845 /* Solaris needs this before initing a robust mutex. Otherwise
4846 * it may skip the init and return EBUSY "seems someone already
4847 * inited" or EINVAL "it was inited differently".
4849 memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
4850 memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
4852 if ((rc = pthread_mutexattr_init(&mattr)))
4855 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
4856 #ifdef MDB_ROBUST_SUPPORTED
4857 if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
4859 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
4860 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
4861 pthread_mutexattr_destroy(&mattr);
4864 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4866 env->me_txns->mti_magic = MDB_MAGIC;
4867 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4868 env->me_txns->mti_txnid = 0;
4869 env->me_txns->mti_numreaders = 0;
4872 if (env->me_txns->mti_magic != MDB_MAGIC) {
4873 DPUTS("lock region has invalid magic");
4877 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4878 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4879 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4880 rc = MDB_VERSION_MISMATCH;
4884 if (rc && rc != EACCES && rc != EAGAIN) {
4888 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4889 if (!env->me_rmutex) goto fail_errno;
4890 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4891 if (!env->me_wmutex) goto fail_errno;
4892 #elif defined(MDB_USE_POSIX_SEM)
4893 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4894 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4895 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4896 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4907 /** Only a subset of the @ref mdb_env flags can be changed
4908 * at runtime. Changing other flags requires closing the
4909 * environment and re-opening it with the new flags.
4911 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4912 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
4913 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4915 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4916 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4920 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4925 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4928 flags |= env->me_flags;
4930 rc = mdb_fname_init(path, flags, &fname);
4934 if (flags & MDB_RDONLY) {
4935 /* silently ignore WRITEMAP when we're only getting read access */
4936 flags &= ~MDB_WRITEMAP;
4938 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4939 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4942 env->me_flags = flags |= MDB_ENV_ACTIVE;
4946 env->me_path = strdup(path);
4947 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4948 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4949 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4950 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4954 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
4956 /* For RDONLY, get lockfile after we know datafile exists */
4957 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4958 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
4963 rc = mdb_fopen(env, &fname,
4964 (flags & MDB_RDONLY) ? MDB_O_RDONLY : MDB_O_RDWR,
4969 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4970 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
4975 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4976 if (!(flags & (MDB_RDONLY|MDB_WRITEMAP))) {
4977 /* Synchronous fd for meta writes. Needed even with
4978 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4980 rc = mdb_fopen(env, &fname, MDB_O_META, mode, &env->me_mfd);
4984 DPRINTF(("opened dbenv %p", (void *) env));
4986 rc = mdb_env_share_locks(env, &excl);
4990 if (!(flags & MDB_RDONLY)) {
4992 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
4993 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
4994 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
4995 (txn = calloc(1, size)))
4997 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
4998 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
4999 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
5000 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
5002 txn->mt_dbxs = env->me_dbxs;
5003 txn->mt_flags = MDB_TXN_FINISHED;
5013 mdb_env_close0(env, excl);
5015 mdb_fname_destroy(fname);
5019 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
5021 mdb_env_close0(MDB_env *env, int excl)
5025 if (!(env->me_flags & MDB_ENV_ACTIVE))
5028 /* Doing this here since me_dbxs may not exist during mdb_env_close */
5030 for (i = env->me_maxdbs; --i >= CORE_DBS; )
5031 free(env->me_dbxs[i].md_name.mv_data);
5036 free(env->me_dbiseqs);
5037 free(env->me_dbflags);
5039 free(env->me_dirty_list);
5041 mdb_midl_free(env->me_free_pgs);
5043 if (env->me_flags & MDB_ENV_TXKEY) {
5044 pthread_key_delete(env->me_txkey);
5046 /* Delete our key from the global list */
5047 for (i=0; i<mdb_tls_nkeys; i++)
5048 if (mdb_tls_keys[i] == env->me_txkey) {
5049 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
5057 munmap(env->me_map, env->me_mapsize);
5059 if (env->me_mfd != INVALID_HANDLE_VALUE)
5060 (void) close(env->me_mfd);
5061 if (env->me_fd != INVALID_HANDLE_VALUE)
5062 (void) close(env->me_fd);
5064 MDB_PID_T pid = env->me_pid;
5065 /* Clearing readers is done in this function because
5066 * me_txkey with its destructor must be disabled first.
5068 * We skip the the reader mutex, so we touch only
5069 * data owned by this process (me_close_readers and
5070 * our readers), and clear each reader atomically.
5072 for (i = env->me_close_readers; --i >= 0; )
5073 if (env->me_txns->mti_readers[i].mr_pid == pid)
5074 env->me_txns->mti_readers[i].mr_pid = 0;
5076 if (env->me_rmutex) {
5077 CloseHandle(env->me_rmutex);
5078 if (env->me_wmutex) CloseHandle(env->me_wmutex);
5080 /* Windows automatically destroys the mutexes when
5081 * the last handle closes.
5083 #elif defined(MDB_USE_POSIX_SEM)
5084 if (env->me_rmutex != SEM_FAILED) {
5085 sem_close(env->me_rmutex);
5086 if (env->me_wmutex != SEM_FAILED)
5087 sem_close(env->me_wmutex);
5088 /* If we have the filelock: If we are the
5089 * only remaining user, clean up semaphores.
5092 mdb_env_excl_lock(env, &excl);
5094 sem_unlink(env->me_txns->mti_rmname);
5095 sem_unlink(env->me_txns->mti_wmname);
5099 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
5101 if (env->me_lfd != INVALID_HANDLE_VALUE) {
5104 /* Unlock the lockfile. Windows would have unlocked it
5105 * after closing anyway, but not necessarily at once.
5107 UnlockFile(env->me_lfd, 0, 0, 1, 0);
5110 (void) close(env->me_lfd);
5113 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
5117 mdb_env_close(MDB_env *env)
5124 VGMEMP_DESTROY(env);
5125 while ((dp = env->me_dpages) != NULL) {
5126 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5127 env->me_dpages = dp->mp_next;
5131 mdb_env_close0(env, 0);
5135 /** Compare two items pointing at aligned size_t's */
5137 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5139 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
5140 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
5143 /** Compare two items pointing at aligned unsigned int's.
5145 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5146 * but #mdb_cmp_clong() is called instead if the data type is size_t.
5149 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5151 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5152 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5155 /** Compare two items pointing at unsigned ints of unknown alignment.
5156 * Nodes and keys are guaranteed to be 2-byte aligned.
5159 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5161 #if BYTE_ORDER == LITTLE_ENDIAN
5162 unsigned short *u, *c;
5165 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5166 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5169 } while(!x && u > (unsigned short *)a->mv_data);
5172 unsigned short *u, *c, *end;
5175 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5176 u = (unsigned short *)a->mv_data;
5177 c = (unsigned short *)b->mv_data;
5180 } while(!x && u < end);
5185 /** Compare two items lexically */
5187 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5194 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5200 diff = memcmp(a->mv_data, b->mv_data, len);
5201 return diff ? diff : len_diff<0 ? -1 : len_diff;
5204 /** Compare two items in reverse byte order */
5206 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5208 const unsigned char *p1, *p2, *p1_lim;
5212 p1_lim = (const unsigned char *)a->mv_data;
5213 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5214 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5216 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5222 while (p1 > p1_lim) {
5223 diff = *--p1 - *--p2;
5227 return len_diff<0 ? -1 : len_diff;
5230 /** Search for key within a page, using binary search.
5231 * Returns the smallest entry larger or equal to the key.
5232 * If exactp is non-null, stores whether the found entry was an exact match
5233 * in *exactp (1 or 0).
5234 * Updates the cursor index with the index of the found entry.
5235 * If no entry larger or equal to the key is found, returns NULL.
5238 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5240 unsigned int i = 0, nkeys;
5243 MDB_page *mp = mc->mc_pg[mc->mc_top];
5244 MDB_node *node = NULL;
5249 nkeys = NUMKEYS(mp);
5251 DPRINTF(("searching %u keys in %s %spage %"Z"u",
5252 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5255 low = IS_LEAF(mp) ? 0 : 1;
5257 cmp = mc->mc_dbx->md_cmp;
5259 /* Branch pages have no data, so if using integer keys,
5260 * alignment is guaranteed. Use faster mdb_cmp_int.
5262 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5263 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
5270 nodekey.mv_size = mc->mc_db->md_pad;
5271 node = NODEPTR(mp, 0); /* fake */
5272 while (low <= high) {
5273 i = (low + high) >> 1;
5274 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5275 rc = cmp(key, &nodekey);
5276 DPRINTF(("found leaf index %u [%s], rc = %i",
5277 i, DKEY(&nodekey), rc));
5286 while (low <= high) {
5287 i = (low + high) >> 1;
5289 node = NODEPTR(mp, i);
5290 nodekey.mv_size = NODEKSZ(node);
5291 nodekey.mv_data = NODEKEY(node);
5293 rc = cmp(key, &nodekey);
5296 DPRINTF(("found leaf index %u [%s], rc = %i",
5297 i, DKEY(&nodekey), rc));
5299 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
5300 i, DKEY(&nodekey), NODEPGNO(node), rc));
5311 if (rc > 0) { /* Found entry is less than the key. */
5312 i++; /* Skip to get the smallest entry larger than key. */
5314 node = NODEPTR(mp, i);
5317 *exactp = (rc == 0 && nkeys > 0);
5318 /* store the key index */
5319 mc->mc_ki[mc->mc_top] = i;
5321 /* There is no entry larger or equal to the key. */
5324 /* nodeptr is fake for LEAF2 */
5330 mdb_cursor_adjust(MDB_cursor *mc, func)
5334 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5335 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5342 /** Pop a page off the top of the cursor's stack. */
5344 mdb_cursor_pop(MDB_cursor *mc)
5347 DPRINTF(("popping page %"Z"u off db %d cursor %p",
5348 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5354 mc->mc_flags &= ~C_INITIALIZED;
5359 /** Push a page onto the top of the cursor's stack.
5360 * Set #MDB_TXN_ERROR on failure.
5363 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5365 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
5366 DDBI(mc), (void *) mc));
5368 if (mc->mc_snum >= CURSOR_STACK) {
5369 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5370 return MDB_CURSOR_FULL;
5373 mc->mc_top = mc->mc_snum++;
5374 mc->mc_pg[mc->mc_top] = mp;
5375 mc->mc_ki[mc->mc_top] = 0;
5380 /** Find the address of the page corresponding to a given page number.
5381 * Set #MDB_TXN_ERROR on failure.
5382 * @param[in] mc the cursor accessing the page.
5383 * @param[in] pgno the page number for the page to retrieve.
5384 * @param[out] ret address of a pointer where the page's address will be stored.
5385 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5386 * @return 0 on success, non-zero on failure.
5389 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
5391 MDB_txn *txn = mc->mc_txn;
5392 MDB_env *env = txn->mt_env;
5396 if (! (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_WRITEMAP))) {
5400 MDB_ID2L dl = tx2->mt_u.dirty_list;
5402 /* Spilled pages were dirtied in this txn and flushed
5403 * because the dirty list got full. Bring this page
5404 * back in from the map (but don't unspill it here,
5405 * leave that unless page_touch happens again).
5407 if (tx2->mt_spill_pgs) {
5408 MDB_ID pn = pgno << 1;
5409 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5410 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5411 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5416 unsigned x = mdb_mid2l_search(dl, pgno);
5417 if (x <= dl[0].mid && dl[x].mid == pgno) {
5423 } while ((tx2 = tx2->mt_parent) != NULL);
5426 if (pgno < txn->mt_next_pgno) {
5428 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5430 DPRINTF(("page %"Z"u not found", pgno));
5431 txn->mt_flags |= MDB_TXN_ERROR;
5432 return MDB_PAGE_NOTFOUND;
5442 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
5443 * The cursor is at the root page, set up the rest of it.
5446 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
5448 MDB_page *mp = mc->mc_pg[mc->mc_top];
5452 while (IS_BRANCH(mp)) {
5456 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
5457 /* Don't assert on branch pages in the FreeDB. We can get here
5458 * while in the process of rebalancing a FreeDB branch page; we must
5459 * let that proceed. ITS#8336
5461 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
5462 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
5464 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
5466 if (flags & MDB_PS_LAST) {
5467 i = NUMKEYS(mp) - 1;
5468 /* if already init'd, see if we're already in right place */
5469 if (mc->mc_flags & C_INITIALIZED) {
5470 if (mc->mc_ki[mc->mc_top] == i) {
5471 mc->mc_top = mc->mc_snum++;
5472 mp = mc->mc_pg[mc->mc_top];
5479 node = mdb_node_search(mc, key, &exact);
5481 i = NUMKEYS(mp) - 1;
5483 i = mc->mc_ki[mc->mc_top];
5485 mdb_cassert(mc, i > 0);
5489 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
5492 mdb_cassert(mc, i < NUMKEYS(mp));
5493 node = NODEPTR(mp, i);
5495 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
5498 mc->mc_ki[mc->mc_top] = i;
5499 if ((rc = mdb_cursor_push(mc, mp)))
5503 if (flags & MDB_PS_MODIFY) {
5504 if ((rc = mdb_page_touch(mc)) != 0)
5506 mp = mc->mc_pg[mc->mc_top];
5511 DPRINTF(("internal error, index points to a %02X page!?",
5513 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5514 return MDB_CORRUPTED;
5517 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
5518 key ? DKEY(key) : "null"));
5519 mc->mc_flags |= C_INITIALIZED;
5520 mc->mc_flags &= ~C_EOF;
5525 /** Search for the lowest key under the current branch page.
5526 * This just bypasses a NUMKEYS check in the current page
5527 * before calling mdb_page_search_root(), because the callers
5528 * are all in situations where the current page is known to
5532 mdb_page_search_lowest(MDB_cursor *mc)
5534 MDB_page *mp = mc->mc_pg[mc->mc_top];
5535 MDB_node *node = NODEPTR(mp, 0);
5538 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
5541 mc->mc_ki[mc->mc_top] = 0;
5542 if ((rc = mdb_cursor_push(mc, mp)))
5544 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5547 /** Search for the page a given key should be in.
5548 * Push it and its parent pages on the cursor stack.
5549 * @param[in,out] mc the cursor for this operation.
5550 * @param[in] key the key to search for, or NULL for first/last page.
5551 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5552 * are touched (updated with new page numbers).
5553 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5554 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5555 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5556 * @return 0 on success, non-zero on failure.
5559 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5564 /* Make sure the txn is still viable, then find the root from
5565 * the txn's db table and set it as the root of the cursor's stack.
5567 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
5568 DPUTS("transaction may not be used now");
5571 /* Make sure we're using an up-to-date root */
5572 if (*mc->mc_dbflag & DB_STALE) {
5574 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5576 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5577 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5584 MDB_node *leaf = mdb_node_search(&mc2,
5585 &mc->mc_dbx->md_name, &exact);
5587 return MDB_NOTFOUND;
5588 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
5589 return MDB_INCOMPATIBLE; /* not a named DB */
5590 rc = mdb_node_read(&mc2, leaf, &data);
5593 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5595 /* The txn may not know this DBI, or another process may
5596 * have dropped and recreated the DB with other flags.
5598 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5599 return MDB_INCOMPATIBLE;
5600 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5602 *mc->mc_dbflag &= ~DB_STALE;
5604 root = mc->mc_db->md_root;
5606 if (root == P_INVALID) { /* Tree is empty. */
5607 DPUTS("tree is empty");
5608 return MDB_NOTFOUND;
5612 mdb_cassert(mc, root > 1);
5613 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5614 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
5620 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5621 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5623 if (flags & MDB_PS_MODIFY) {
5624 if ((rc = mdb_page_touch(mc)))
5628 if (flags & MDB_PS_ROOTONLY)
5631 return mdb_page_search_root(mc, key, flags);
5635 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5637 MDB_txn *txn = mc->mc_txn;
5638 pgno_t pg = mp->mp_pgno;
5639 unsigned x = 0, ovpages = mp->mp_pages;
5640 MDB_env *env = txn->mt_env;
5641 MDB_IDL sl = txn->mt_spill_pgs;
5642 MDB_ID pn = pg << 1;
5645 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5646 /* If the page is dirty or on the spill list we just acquired it,
5647 * so we should give it back to our current free list, if any.
5648 * Otherwise put it onto the list of pages we freed in this txn.
5650 * Won't create me_pghead: me_pglast must be inited along with it.
5651 * Unsupported in nested txns: They would need to hide the page
5652 * range in ancestor txns' dirty and spilled lists.
5654 if (env->me_pghead &&
5656 ((mp->mp_flags & P_DIRTY) ||
5657 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5661 MDB_ID2 *dl, ix, iy;
5662 rc = mdb_midl_need(&env->me_pghead, ovpages);
5665 if (!(mp->mp_flags & P_DIRTY)) {
5666 /* This page is no longer spilled */
5673 /* Remove from dirty list */
5674 dl = txn->mt_u.dirty_list;
5676 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5682 mdb_cassert(mc, x > 1);
5684 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5685 txn->mt_flags |= MDB_TXN_ERROR;
5686 return MDB_CORRUPTED;
5689 txn->mt_dirty_room++;
5690 if (!(env->me_flags & MDB_WRITEMAP))
5691 mdb_dpage_free(env, mp);
5693 /* Insert in me_pghead */
5694 mop = env->me_pghead;
5695 j = mop[0] + ovpages;
5696 for (i = mop[0]; i && mop[i] < pg; i--)
5702 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5706 mc->mc_db->md_overflow_pages -= ovpages;
5710 /** Return the data associated with a given node.
5711 * @param[in] mc The cursor for this operation.
5712 * @param[in] leaf The node being read.
5713 * @param[out] data Updated to point to the node's data.
5714 * @return 0 on success, non-zero on failure.
5717 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
5719 MDB_page *omp; /* overflow page */
5723 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5724 data->mv_size = NODEDSZ(leaf);
5725 data->mv_data = NODEDATA(leaf);
5729 /* Read overflow data.
5731 data->mv_size = NODEDSZ(leaf);
5732 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5733 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
5734 DPRINTF(("read overflow page %"Z"u failed", pgno));
5737 data->mv_data = METADATA(omp);
5743 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5744 MDB_val *key, MDB_val *data)
5751 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5753 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
5756 if (txn->mt_flags & MDB_TXN_BLOCKED)
5759 mdb_cursor_init(&mc, txn, dbi, &mx);
5760 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5763 /** Find a sibling for a page.
5764 * Replaces the page at the top of the cursor's stack with the
5765 * specified sibling, if one exists.
5766 * @param[in] mc The cursor for this operation.
5767 * @param[in] move_right Non-zero if the right sibling is requested,
5768 * otherwise the left sibling.
5769 * @return 0 on success, non-zero on failure.
5772 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5778 if (mc->mc_snum < 2) {
5779 return MDB_NOTFOUND; /* root has no siblings */
5783 DPRINTF(("parent page is page %"Z"u, index %u",
5784 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5786 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5787 : (mc->mc_ki[mc->mc_top] == 0)) {
5788 DPRINTF(("no more keys left, moving to %s sibling",
5789 move_right ? "right" : "left"));
5790 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5791 /* undo cursor_pop before returning */
5798 mc->mc_ki[mc->mc_top]++;
5800 mc->mc_ki[mc->mc_top]--;
5801 DPRINTF(("just moving to %s index key %u",
5802 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5804 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5806 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5807 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
5808 /* mc will be inconsistent if caller does mc_snum++ as above */
5809 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5813 mdb_cursor_push(mc, mp);
5815 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5820 /** Move the cursor to the next data item. */
5822 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5828 if ((mc->mc_flags & C_DEL && op == MDB_NEXT_DUP))
5829 return MDB_NOTFOUND;
5831 if (!(mc->mc_flags & C_INITIALIZED))
5832 return mdb_cursor_first(mc, key, data);
5834 mp = mc->mc_pg[mc->mc_top];
5836 if (mc->mc_flags & C_EOF) {
5837 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mp)-1)
5838 return MDB_NOTFOUND;
5839 mc->mc_flags ^= C_EOF;
5842 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5843 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5844 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5845 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5846 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5847 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5848 if (rc == MDB_SUCCESS)
5849 MDB_GET_KEY(leaf, key);
5854 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5855 if (op == MDB_NEXT_DUP)
5856 return MDB_NOTFOUND;
5860 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5861 mdb_dbg_pgno(mp), (void *) mc));
5862 if (mc->mc_flags & C_DEL) {
5863 mc->mc_flags ^= C_DEL;
5867 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5868 DPUTS("=====> move to next sibling page");
5869 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5870 mc->mc_flags |= C_EOF;
5873 mp = mc->mc_pg[mc->mc_top];
5874 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5876 mc->mc_ki[mc->mc_top]++;
5879 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5880 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5883 key->mv_size = mc->mc_db->md_pad;
5884 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5888 mdb_cassert(mc, IS_LEAF(mp));
5889 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5891 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5892 mdb_xcursor_init1(mc, leaf);
5895 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
5898 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5899 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5900 if (rc != MDB_SUCCESS)
5905 MDB_GET_KEY(leaf, key);
5909 /** Move the cursor to the previous data item. */
5911 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5917 if (!(mc->mc_flags & C_INITIALIZED)) {
5918 rc = mdb_cursor_last(mc, key, data);
5921 mc->mc_ki[mc->mc_top]++;
5924 mp = mc->mc_pg[mc->mc_top];
5926 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5927 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5928 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5929 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5930 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5931 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5932 if (rc == MDB_SUCCESS) {
5933 MDB_GET_KEY(leaf, key);
5934 mc->mc_flags &= ~C_EOF;
5940 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5941 if (op == MDB_PREV_DUP)
5942 return MDB_NOTFOUND;
5946 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5947 mdb_dbg_pgno(mp), (void *) mc));
5949 mc->mc_flags &= ~(C_EOF|C_DEL);
5951 if (mc->mc_ki[mc->mc_top] == 0) {
5952 DPUTS("=====> move to prev sibling page");
5953 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5956 mp = mc->mc_pg[mc->mc_top];
5957 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5958 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5960 mc->mc_ki[mc->mc_top]--;
5962 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5963 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5966 key->mv_size = mc->mc_db->md_pad;
5967 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5971 mdb_cassert(mc, IS_LEAF(mp));
5972 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5974 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5975 mdb_xcursor_init1(mc, leaf);
5978 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
5981 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5982 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5983 if (rc != MDB_SUCCESS)
5988 MDB_GET_KEY(leaf, key);
5992 /** Set the cursor on a specific data item. */
5994 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5995 MDB_cursor_op op, int *exactp)
5999 MDB_node *leaf = NULL;
6002 if (key->mv_size == 0)
6003 return MDB_BAD_VALSIZE;
6006 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6008 /* See if we're already on the right page */
6009 if (mc->mc_flags & C_INITIALIZED) {
6012 mp = mc->mc_pg[mc->mc_top];
6014 mc->mc_ki[mc->mc_top] = 0;
6015 return MDB_NOTFOUND;
6017 if (mp->mp_flags & P_LEAF2) {
6018 nodekey.mv_size = mc->mc_db->md_pad;
6019 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
6021 leaf = NODEPTR(mp, 0);
6022 MDB_GET_KEY2(leaf, nodekey);
6024 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6026 /* Probably happens rarely, but first node on the page
6027 * was the one we wanted.
6029 mc->mc_ki[mc->mc_top] = 0;
6036 unsigned int nkeys = NUMKEYS(mp);
6038 if (mp->mp_flags & P_LEAF2) {
6039 nodekey.mv_data = LEAF2KEY(mp,
6040 nkeys-1, nodekey.mv_size);
6042 leaf = NODEPTR(mp, nkeys-1);
6043 MDB_GET_KEY2(leaf, nodekey);
6045 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6047 /* last node was the one we wanted */
6048 mc->mc_ki[mc->mc_top] = nkeys-1;
6054 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
6055 /* This is definitely the right page, skip search_page */
6056 if (mp->mp_flags & P_LEAF2) {
6057 nodekey.mv_data = LEAF2KEY(mp,
6058 mc->mc_ki[mc->mc_top], nodekey.mv_size);
6060 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6061 MDB_GET_KEY2(leaf, nodekey);
6063 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6065 /* current node was the one we wanted */
6072 mc->mc_flags &= ~C_EOF;
6076 /* If any parents have right-sibs, search.
6077 * Otherwise, there's nothing further.
6079 for (i=0; i<mc->mc_top; i++)
6081 NUMKEYS(mc->mc_pg[i])-1)
6083 if (i == mc->mc_top) {
6084 /* There are no other pages */
6085 mc->mc_ki[mc->mc_top] = nkeys;
6086 return MDB_NOTFOUND;
6090 /* There are no other pages */
6091 mc->mc_ki[mc->mc_top] = 0;
6092 if (op == MDB_SET_RANGE && !exactp) {
6096 return MDB_NOTFOUND;
6102 rc = mdb_page_search(mc, key, 0);
6103 if (rc != MDB_SUCCESS)
6106 mp = mc->mc_pg[mc->mc_top];
6107 mdb_cassert(mc, IS_LEAF(mp));
6110 leaf = mdb_node_search(mc, key, exactp);
6111 if (exactp != NULL && !*exactp) {
6112 /* MDB_SET specified and not an exact match. */
6113 return MDB_NOTFOUND;
6117 DPUTS("===> inexact leaf not found, goto sibling");
6118 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6119 mc->mc_flags |= C_EOF;
6120 return rc; /* no entries matched */
6122 mp = mc->mc_pg[mc->mc_top];
6123 mdb_cassert(mc, IS_LEAF(mp));
6124 leaf = NODEPTR(mp, 0);
6128 mc->mc_flags |= C_INITIALIZED;
6129 mc->mc_flags &= ~C_EOF;
6132 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
6133 key->mv_size = mc->mc_db->md_pad;
6134 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6139 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6140 mdb_xcursor_init1(mc, leaf);
6143 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6144 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
6145 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6148 if (op == MDB_GET_BOTH) {
6154 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
6155 if (rc != MDB_SUCCESS)
6158 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
6161 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
6163 dcmp = mc->mc_dbx->md_dcmp;
6164 #if UINT_MAX < SIZE_MAX
6165 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6166 dcmp = mdb_cmp_clong;
6168 rc = dcmp(data, &olddata);
6170 if (op == MDB_GET_BOTH || rc > 0)
6171 return MDB_NOTFOUND;
6178 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6179 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6184 /* The key already matches in all other cases */
6185 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6186 MDB_GET_KEY(leaf, key);
6187 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6192 /** Move the cursor to the first item in the database. */
6194 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6200 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6202 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6203 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6204 if (rc != MDB_SUCCESS)
6207 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6209 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6210 mc->mc_flags |= C_INITIALIZED;
6211 mc->mc_flags &= ~C_EOF;
6213 mc->mc_ki[mc->mc_top] = 0;
6215 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6216 key->mv_size = mc->mc_db->md_pad;
6217 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
6222 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6223 mdb_xcursor_init1(mc, leaf);
6224 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6228 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6232 MDB_GET_KEY(leaf, key);
6236 /** Move the cursor to the last item in the database. */
6238 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6244 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6246 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6247 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
6248 if (rc != MDB_SUCCESS)
6251 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6253 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
6254 mc->mc_flags |= C_INITIALIZED|C_EOF;
6255 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6257 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6258 key->mv_size = mc->mc_db->md_pad;
6259 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
6264 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6265 mdb_xcursor_init1(mc, leaf);
6266 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6270 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6275 MDB_GET_KEY(leaf, key);
6280 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6285 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
6290 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
6294 case MDB_GET_CURRENT:
6295 if (!(mc->mc_flags & C_INITIALIZED)) {
6298 MDB_page *mp = mc->mc_pg[mc->mc_top];
6299 int nkeys = NUMKEYS(mp);
6300 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
6301 mc->mc_ki[mc->mc_top] = nkeys;
6307 key->mv_size = mc->mc_db->md_pad;
6308 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6310 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6311 MDB_GET_KEY(leaf, key);
6313 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6314 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
6316 rc = mdb_node_read(mc, leaf, data);
6323 case MDB_GET_BOTH_RANGE:
6328 if (mc->mc_xcursor == NULL) {
6329 rc = MDB_INCOMPATIBLE;
6339 rc = mdb_cursor_set(mc, key, data, op,
6340 op == MDB_SET_RANGE ? NULL : &exact);
6343 case MDB_GET_MULTIPLE:
6344 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6348 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6349 rc = MDB_INCOMPATIBLE;
6353 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6354 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6357 case MDB_NEXT_MULTIPLE:
6362 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6363 rc = MDB_INCOMPATIBLE;
6366 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6367 if (rc == MDB_SUCCESS) {
6368 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6371 mx = &mc->mc_xcursor->mx_cursor;
6372 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
6374 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
6375 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
6381 case MDB_PREV_MULTIPLE:
6386 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6387 rc = MDB_INCOMPATIBLE;
6390 if (!(mc->mc_flags & C_INITIALIZED))
6391 rc = mdb_cursor_last(mc, key, data);
6394 if (rc == MDB_SUCCESS) {
6395 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
6396 if (mx->mc_flags & C_INITIALIZED) {
6397 rc = mdb_cursor_sibling(mx, 0);
6398 if (rc == MDB_SUCCESS)
6407 case MDB_NEXT_NODUP:
6408 rc = mdb_cursor_next(mc, key, data, op);
6412 case MDB_PREV_NODUP:
6413 rc = mdb_cursor_prev(mc, key, data, op);
6416 rc = mdb_cursor_first(mc, key, data);
6419 mfunc = mdb_cursor_first;
6421 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6425 if (mc->mc_xcursor == NULL) {
6426 rc = MDB_INCOMPATIBLE;
6429 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top])) {
6430 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
6435 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6436 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6437 MDB_GET_KEY(leaf, key);
6438 rc = mdb_node_read(mc, leaf, data);
6442 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6446 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
6449 rc = mdb_cursor_last(mc, key, data);
6452 mfunc = mdb_cursor_last;
6455 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
6460 if (mc->mc_flags & C_DEL)
6461 mc->mc_flags ^= C_DEL;
6466 /** Touch all the pages in the cursor stack. Set mc_top.
6467 * Makes sure all the pages are writable, before attempting a write operation.
6468 * @param[in] mc The cursor to operate on.
6471 mdb_cursor_touch(MDB_cursor *mc)
6473 int rc = MDB_SUCCESS;
6475 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & (DB_DIRTY|DB_DUPDATA))) {
6476 /* Touch DB record of named DB */
6479 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6481 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
6482 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
6485 *mc->mc_dbflag |= DB_DIRTY;
6490 rc = mdb_page_touch(mc);
6491 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
6492 mc->mc_top = mc->mc_snum-1;
6497 /** Do not spill pages to disk if txn is getting full, may fail instead */
6498 #define MDB_NOSPILL 0x8000
6501 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6505 MDB_node *leaf = NULL;
6506 MDB_page *fp, *mp, *sub_root = NULL;
6508 MDB_val xdata, *rdata, dkey, olddata;
6510 int do_sub = 0, insert_key, insert_data;
6511 unsigned int mcount = 0, dcount = 0, nospill;
6514 unsigned int nflags;
6517 if (mc == NULL || key == NULL)
6520 env = mc->mc_txn->mt_env;
6522 /* Check this first so counter will always be zero on any
6525 if (flags & MDB_MULTIPLE) {
6526 dcount = data[1].mv_size;
6527 data[1].mv_size = 0;
6528 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
6529 return MDB_INCOMPATIBLE;
6532 nospill = flags & MDB_NOSPILL;
6533 flags &= ~MDB_NOSPILL;
6535 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6536 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6538 if (key->mv_size-1 >= ENV_MAXKEY(env))
6539 return MDB_BAD_VALSIZE;
6541 #if SIZE_MAX > MAXDATASIZE
6542 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
6543 return MDB_BAD_VALSIZE;
6545 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
6546 return MDB_BAD_VALSIZE;
6549 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
6550 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
6554 if (flags == MDB_CURRENT) {
6555 if (!(mc->mc_flags & C_INITIALIZED))
6558 } else if (mc->mc_db->md_root == P_INVALID) {
6559 /* new database, cursor has nothing to point to */
6562 mc->mc_flags &= ~C_INITIALIZED;
6567 if (flags & MDB_APPEND) {
6569 rc = mdb_cursor_last(mc, &k2, &d2);
6571 rc = mc->mc_dbx->md_cmp(key, &k2);
6574 mc->mc_ki[mc->mc_top]++;
6576 /* new key is <= last key */
6581 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6583 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6584 DPRINTF(("duplicate key [%s]", DKEY(key)));
6586 return MDB_KEYEXIST;
6588 if (rc && rc != MDB_NOTFOUND)
6592 if (mc->mc_flags & C_DEL)
6593 mc->mc_flags ^= C_DEL;
6595 /* Cursor is positioned, check for room in the dirty list */
6597 if (flags & MDB_MULTIPLE) {
6599 xdata.mv_size = data->mv_size * dcount;
6603 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6607 if (rc == MDB_NO_ROOT) {
6609 /* new database, write a root leaf page */
6610 DPUTS("allocating new root leaf page");
6611 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6614 mdb_cursor_push(mc, np);
6615 mc->mc_db->md_root = np->mp_pgno;
6616 mc->mc_db->md_depth++;
6617 *mc->mc_dbflag |= DB_DIRTY;
6618 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6620 np->mp_flags |= P_LEAF2;
6621 mc->mc_flags |= C_INITIALIZED;
6623 /* make sure all cursor pages are writable */
6624 rc2 = mdb_cursor_touch(mc);
6629 insert_key = insert_data = rc;
6631 /* The key does not exist */
6632 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6633 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6634 LEAFSIZE(key, data) > env->me_nodemax)
6636 /* Too big for a node, insert in sub-DB. Set up an empty
6637 * "old sub-page" for prep_subDB to expand to a full page.
6639 fp_flags = P_LEAF|P_DIRTY;
6641 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6642 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6643 olddata.mv_size = PAGEHDRSZ;
6647 /* there's only a key anyway, so this is a no-op */
6648 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6650 unsigned int ksize = mc->mc_db->md_pad;
6651 if (key->mv_size != ksize)
6652 return MDB_BAD_VALSIZE;
6653 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6654 memcpy(ptr, key->mv_data, ksize);
6656 /* if overwriting slot 0 of leaf, need to
6657 * update branch key if there is a parent page
6659 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6660 unsigned short dtop = 1;
6662 /* slot 0 is always an empty key, find real slot */
6663 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6667 if (mc->mc_ki[mc->mc_top])
6668 rc2 = mdb_update_key(mc, key);
6679 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6680 olddata.mv_size = NODEDSZ(leaf);
6681 olddata.mv_data = NODEDATA(leaf);
6684 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6685 /* Prepare (sub-)page/sub-DB to accept the new item,
6686 * if needed. fp: old sub-page or a header faking
6687 * it. mp: new (sub-)page. offset: growth in page
6688 * size. xdata: node data with new page or DB.
6690 unsigned i, offset = 0;
6691 mp = fp = xdata.mv_data = env->me_pbuf;
6692 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6694 /* Was a single item before, must convert now */
6695 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6697 /* Just overwrite the current item */
6698 if (flags == MDB_CURRENT)
6700 dcmp = mc->mc_dbx->md_dcmp;
6701 #if UINT_MAX < SIZE_MAX
6702 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6703 dcmp = mdb_cmp_clong;
6705 /* does data match? */
6706 if (!dcmp(data, &olddata)) {
6707 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
6708 return MDB_KEYEXIST;
6713 /* Back up original data item */
6714 dkey.mv_size = olddata.mv_size;
6715 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6717 /* Make sub-page header for the dup items, with dummy body */
6718 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6719 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6720 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6721 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6722 fp->mp_flags |= P_LEAF2;
6723 fp->mp_pad = data->mv_size;
6724 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6726 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6727 (dkey.mv_size & 1) + (data->mv_size & 1);
6729 fp->mp_upper = xdata.mv_size - PAGEBASE;
6730 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6731 } else if (leaf->mn_flags & F_SUBDATA) {
6732 /* Data is on sub-DB, just store it */
6733 flags |= F_DUPDATA|F_SUBDATA;
6736 /* Data is on sub-page */
6737 fp = olddata.mv_data;
6740 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6741 offset = EVEN(NODESIZE + sizeof(indx_t) +
6745 offset = fp->mp_pad;
6746 if (SIZELEFT(fp) < offset) {
6747 offset *= 4; /* space for 4 more */
6750 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6752 fp->mp_flags |= P_DIRTY;
6753 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6754 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6758 xdata.mv_size = olddata.mv_size + offset;
6761 fp_flags = fp->mp_flags;
6762 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6763 /* Too big for a sub-page, convert to sub-DB */
6764 fp_flags &= ~P_SUBP;
6766 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6767 fp_flags |= P_LEAF2;
6768 dummy.md_pad = fp->mp_pad;
6769 dummy.md_flags = MDB_DUPFIXED;
6770 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6771 dummy.md_flags |= MDB_INTEGERKEY;
6777 dummy.md_branch_pages = 0;
6778 dummy.md_leaf_pages = 1;
6779 dummy.md_overflow_pages = 0;
6780 dummy.md_entries = NUMKEYS(fp);
6781 xdata.mv_size = sizeof(MDB_db);
6782 xdata.mv_data = &dummy;
6783 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6785 offset = env->me_psize - olddata.mv_size;
6786 flags |= F_DUPDATA|F_SUBDATA;
6787 dummy.md_root = mp->mp_pgno;
6791 mp->mp_flags = fp_flags | P_DIRTY;
6792 mp->mp_pad = fp->mp_pad;
6793 mp->mp_lower = fp->mp_lower;
6794 mp->mp_upper = fp->mp_upper + offset;
6795 if (fp_flags & P_LEAF2) {
6796 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6798 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6799 olddata.mv_size - fp->mp_upper - PAGEBASE);
6800 for (i=0; i<NUMKEYS(fp); i++)
6801 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6809 mdb_node_del(mc, 0);
6813 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
6814 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
6815 return MDB_INCOMPATIBLE;
6816 /* overflow page overwrites need special handling */
6817 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6820 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6822 memcpy(&pg, olddata.mv_data, sizeof(pg));
6823 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
6825 ovpages = omp->mp_pages;
6827 /* Is the ov page large enough? */
6828 if (ovpages >= dpages) {
6829 if (!(omp->mp_flags & P_DIRTY) &&
6830 (level || (env->me_flags & MDB_WRITEMAP)))
6832 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6835 level = 0; /* dirty in this txn or clean */
6838 if (omp->mp_flags & P_DIRTY) {
6839 /* yes, overwrite it. Note in this case we don't
6840 * bother to try shrinking the page if the new data
6841 * is smaller than the overflow threshold.
6844 /* It is writable only in a parent txn */
6845 size_t sz = (size_t) env->me_psize * ovpages, off;
6846 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6852 /* Note - this page is already counted in parent's dirty_room */
6853 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6854 mdb_cassert(mc, rc2 == 0);
6855 /* Currently we make the page look as with put() in the
6856 * parent txn, in case the user peeks at MDB_RESERVEd
6857 * or unused parts. Some users treat ovpages specially.
6859 if (!(flags & MDB_RESERVE)) {
6860 /* Skip the part where LMDB will put *data.
6861 * Copy end of page, adjusting alignment so
6862 * compiler may copy words instead of bytes.
6864 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6865 memcpy((size_t *)((char *)np + off),
6866 (size_t *)((char *)omp + off), sz - off);
6869 memcpy(np, omp, sz); /* Copy beginning of page */
6872 SETDSZ(leaf, data->mv_size);
6873 if (F_ISSET(flags, MDB_RESERVE))
6874 data->mv_data = METADATA(omp);
6876 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6880 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6882 } else if (data->mv_size == olddata.mv_size) {
6883 /* same size, just replace it. Note that we could
6884 * also reuse this node if the new data is smaller,
6885 * but instead we opt to shrink the node in that case.
6887 if (F_ISSET(flags, MDB_RESERVE))
6888 data->mv_data = olddata.mv_data;
6889 else if (!(mc->mc_flags & C_SUB))
6890 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6892 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6897 mdb_node_del(mc, 0);
6903 nflags = flags & NODE_ADD_FLAGS;
6904 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6905 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6906 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6907 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6909 nflags |= MDB_SPLIT_REPLACE;
6910 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6912 /* There is room already in this leaf page. */
6913 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6915 /* Adjust other cursors pointing to mp */
6916 MDB_cursor *m2, *m3;
6917 MDB_dbi dbi = mc->mc_dbi;
6918 unsigned i = mc->mc_top;
6919 MDB_page *mp = mc->mc_pg[i];
6921 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6922 if (mc->mc_flags & C_SUB)
6923 m3 = &m2->mc_xcursor->mx_cursor;
6926 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
6927 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
6930 if (XCURSOR_INITED(m3))
6931 XCURSOR_REFRESH(m3, mp, m3->mc_ki[i]);
6936 if (rc == MDB_SUCCESS) {
6937 /* Now store the actual data in the child DB. Note that we're
6938 * storing the user data in the keys field, so there are strict
6939 * size limits on dupdata. The actual data fields of the child
6940 * DB are all zero size.
6943 int xflags, new_dupdata;
6948 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6949 if (flags & MDB_CURRENT) {
6950 xflags = MDB_CURRENT|MDB_NOSPILL;
6952 mdb_xcursor_init1(mc, leaf);
6953 xflags = (flags & MDB_NODUPDATA) ?
6954 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6957 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
6958 new_dupdata = (int)dkey.mv_size;
6959 /* converted, write the original data first */
6961 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6964 /* we've done our job */
6967 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
6968 /* Adjust other cursors pointing to mp */
6970 MDB_xcursor *mx = mc->mc_xcursor;
6971 unsigned i = mc->mc_top;
6972 MDB_page *mp = mc->mc_pg[i];
6973 int nkeys = NUMKEYS(mp);
6975 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6976 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6977 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6978 if (m2->mc_pg[i] == mp) {
6979 if (m2->mc_ki[i] == mc->mc_ki[i]) {
6980 mdb_xcursor_init2(m2, mx, new_dupdata);
6981 } else if (!insert_key && m2->mc_ki[i] < nkeys) {
6982 XCURSOR_REFRESH(m2, mp, m2->mc_ki[i]);
6987 ecount = mc->mc_xcursor->mx_db.md_entries;
6988 if (flags & MDB_APPENDDUP)
6989 xflags |= MDB_APPEND;
6990 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6991 if (flags & F_SUBDATA) {
6992 void *db = NODEDATA(leaf);
6993 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6995 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6997 /* Increment count unless we just replaced an existing item. */
6999 mc->mc_db->md_entries++;
7001 /* Invalidate txn if we created an empty sub-DB */
7004 /* If we succeeded and the key didn't exist before,
7005 * make sure the cursor is marked valid.
7007 mc->mc_flags |= C_INITIALIZED;
7009 if (flags & MDB_MULTIPLE) {
7012 /* let caller know how many succeeded, if any */
7013 data[1].mv_size = mcount;
7014 if (mcount < dcount) {
7015 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
7016 insert_key = insert_data = 0;
7023 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
7026 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7031 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
7037 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7038 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7040 if (!(mc->mc_flags & C_INITIALIZED))
7043 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
7044 return MDB_NOTFOUND;
7046 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
7049 rc = mdb_cursor_touch(mc);
7053 mp = mc->mc_pg[mc->mc_top];
7056 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7058 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7059 if (flags & MDB_NODUPDATA) {
7060 /* mdb_cursor_del0() will subtract the final entry */
7061 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
7062 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7064 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
7065 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7067 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
7070 /* If sub-DB still has entries, we're done */
7071 if (mc->mc_xcursor->mx_db.md_entries) {
7072 if (leaf->mn_flags & F_SUBDATA) {
7073 /* update subDB info */
7074 void *db = NODEDATA(leaf);
7075 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7078 /* shrink fake page */
7079 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
7080 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7081 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7082 /* fix other sub-DB cursors pointed at fake pages on this page */
7083 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7084 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7085 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7086 if (m2->mc_pg[mc->mc_top] == mp) {
7087 MDB_node *n2 = leaf;
7088 if (m2->mc_ki[mc->mc_top] >= NUMKEYS(mp)) continue;
7089 if (m2->mc_ki[mc->mc_top] != mc->mc_ki[mc->mc_top]) {
7090 n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
7091 if (n2->mn_flags & F_SUBDATA) continue;
7093 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7097 mc->mc_db->md_entries--;
7100 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7102 /* otherwise fall thru and delete the sub-DB */
7105 if (leaf->mn_flags & F_SUBDATA) {
7106 /* add all the child DB's pages to the free list */
7107 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7112 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
7113 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
7114 rc = MDB_INCOMPATIBLE;
7118 /* add overflow pages to free list */
7119 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7123 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7124 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
7125 (rc = mdb_ovpage_free(mc, omp)))
7130 return mdb_cursor_del0(mc);
7133 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7137 /** Allocate and initialize new pages for a database.
7138 * Set #MDB_TXN_ERROR on failure.
7139 * @param[in] mc a cursor on the database being added to.
7140 * @param[in] flags flags defining what type of page is being allocated.
7141 * @param[in] num the number of pages to allocate. This is usually 1,
7142 * unless allocating overflow pages for a large record.
7143 * @param[out] mp Address of a page, or NULL on failure.
7144 * @return 0 on success, non-zero on failure.
7147 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
7152 if ((rc = mdb_page_alloc(mc, num, &np)))
7154 DPRINTF(("allocated new mpage %"Z"u, page size %u",
7155 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
7156 np->mp_flags = flags | P_DIRTY;
7157 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
7158 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
7161 mc->mc_db->md_branch_pages++;
7162 else if (IS_LEAF(np))
7163 mc->mc_db->md_leaf_pages++;
7164 else if (IS_OVERFLOW(np)) {
7165 mc->mc_db->md_overflow_pages += num;
7173 /** Calculate the size of a leaf node.
7174 * The size depends on the environment's page size; if a data item
7175 * is too large it will be put onto an overflow page and the node
7176 * size will only include the key and not the data. Sizes are always
7177 * rounded up to an even number of bytes, to guarantee 2-byte alignment
7178 * of the #MDB_node headers.
7179 * @param[in] env The environment handle.
7180 * @param[in] key The key for the node.
7181 * @param[in] data The data for the node.
7182 * @return The number of bytes needed to store the node.
7185 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
7189 sz = LEAFSIZE(key, data);
7190 if (sz > env->me_nodemax) {
7191 /* put on overflow page */
7192 sz -= data->mv_size - sizeof(pgno_t);
7195 return EVEN(sz + sizeof(indx_t));
7198 /** Calculate the size of a branch node.
7199 * The size should depend on the environment's page size but since
7200 * we currently don't support spilling large keys onto overflow
7201 * pages, it's simply the size of the #MDB_node header plus the
7202 * size of the key. Sizes are always rounded up to an even number
7203 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7204 * @param[in] env The environment handle.
7205 * @param[in] key The key for the node.
7206 * @return The number of bytes needed to store the node.
7209 mdb_branch_size(MDB_env *env, MDB_val *key)
7214 if (sz > env->me_nodemax) {
7215 /* put on overflow page */
7216 /* not implemented */
7217 /* sz -= key->size - sizeof(pgno_t); */
7220 return sz + sizeof(indx_t);
7223 /** Add a node to the page pointed to by the cursor.
7224 * Set #MDB_TXN_ERROR on failure.
7225 * @param[in] mc The cursor for this operation.
7226 * @param[in] indx The index on the page where the new node should be added.
7227 * @param[in] key The key for the new node.
7228 * @param[in] data The data for the new node, if any.
7229 * @param[in] pgno The page number, if adding a branch node.
7230 * @param[in] flags Flags for the node.
7231 * @return 0 on success, non-zero on failure. Possible errors are:
7233 * <li>ENOMEM - failed to allocate overflow pages for the node.
7234 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
7235 * should never happen since all callers already calculate the
7236 * page's free space before calling this function.
7240 mdb_node_add(MDB_cursor *mc, indx_t indx,
7241 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
7244 size_t node_size = NODESIZE;
7248 MDB_page *mp = mc->mc_pg[mc->mc_top];
7249 MDB_page *ofp = NULL; /* overflow page */
7253 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
7255 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
7256 IS_LEAF(mp) ? "leaf" : "branch",
7257 IS_SUBP(mp) ? "sub-" : "",
7258 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
7259 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
7262 /* Move higher keys up one slot. */
7263 int ksize = mc->mc_db->md_pad, dif;
7264 char *ptr = LEAF2KEY(mp, indx, ksize);
7265 dif = NUMKEYS(mp) - indx;
7267 memmove(ptr+ksize, ptr, dif*ksize);
7268 /* insert new key */
7269 memcpy(ptr, key->mv_data, ksize);
7271 /* Just using these for counting */
7272 mp->mp_lower += sizeof(indx_t);
7273 mp->mp_upper -= ksize - sizeof(indx_t);
7277 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
7279 node_size += key->mv_size;
7281 mdb_cassert(mc, key && data);
7282 if (F_ISSET(flags, F_BIGDATA)) {
7283 /* Data already on overflow page. */
7284 node_size += sizeof(pgno_t);
7285 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
7286 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
7288 /* Put data on overflow page. */
7289 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
7290 data->mv_size, node_size+data->mv_size));
7291 node_size = EVEN(node_size + sizeof(pgno_t));
7292 if ((ssize_t)node_size > room)
7294 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
7296 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
7300 node_size += data->mv_size;
7303 node_size = EVEN(node_size);
7304 if ((ssize_t)node_size > room)
7308 /* Move higher pointers up one slot. */
7309 for (i = NUMKEYS(mp); i > indx; i--)
7310 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
7312 /* Adjust free space offsets. */
7313 ofs = mp->mp_upper - node_size;
7314 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
7315 mp->mp_ptrs[indx] = ofs;
7317 mp->mp_lower += sizeof(indx_t);
7319 /* Write the node data. */
7320 node = NODEPTR(mp, indx);
7321 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
7322 node->mn_flags = flags;
7324 SETDSZ(node,data->mv_size);
7329 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7332 ndata = NODEDATA(node);
7334 if (F_ISSET(flags, F_BIGDATA))
7335 memcpy(ndata, data->mv_data, sizeof(pgno_t));
7336 else if (F_ISSET(flags, MDB_RESERVE))
7337 data->mv_data = ndata;
7339 memcpy(ndata, data->mv_data, data->mv_size);
7341 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
7342 ndata = METADATA(ofp);
7343 if (F_ISSET(flags, MDB_RESERVE))
7344 data->mv_data = ndata;
7346 memcpy(ndata, data->mv_data, data->mv_size);
7353 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
7354 mdb_dbg_pgno(mp), NUMKEYS(mp)));
7355 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
7356 DPRINTF(("node size = %"Z"u", node_size));
7357 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7358 return MDB_PAGE_FULL;
7361 /** Delete the specified node from a page.
7362 * @param[in] mc Cursor pointing to the node to delete.
7363 * @param[in] ksize The size of a node. Only used if the page is
7364 * part of a #MDB_DUPFIXED database.
7367 mdb_node_del(MDB_cursor *mc, int ksize)
7369 MDB_page *mp = mc->mc_pg[mc->mc_top];
7370 indx_t indx = mc->mc_ki[mc->mc_top];
7372 indx_t i, j, numkeys, ptr;
7376 DPRINTF(("delete node %u on %s page %"Z"u", indx,
7377 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
7378 numkeys = NUMKEYS(mp);
7379 mdb_cassert(mc, indx < numkeys);
7382 int x = numkeys - 1 - indx;
7383 base = LEAF2KEY(mp, indx, ksize);
7385 memmove(base, base + ksize, x * ksize);
7386 mp->mp_lower -= sizeof(indx_t);
7387 mp->mp_upper += ksize - sizeof(indx_t);
7391 node = NODEPTR(mp, indx);
7392 sz = NODESIZE + node->mn_ksize;
7394 if (F_ISSET(node->mn_flags, F_BIGDATA))
7395 sz += sizeof(pgno_t);
7397 sz += NODEDSZ(node);
7401 ptr = mp->mp_ptrs[indx];
7402 for (i = j = 0; i < numkeys; i++) {
7404 mp->mp_ptrs[j] = mp->mp_ptrs[i];
7405 if (mp->mp_ptrs[i] < ptr)
7406 mp->mp_ptrs[j] += sz;
7411 base = (char *)mp + mp->mp_upper + PAGEBASE;
7412 memmove(base + sz, base, ptr - mp->mp_upper);
7414 mp->mp_lower -= sizeof(indx_t);
7418 /** Compact the main page after deleting a node on a subpage.
7419 * @param[in] mp The main page to operate on.
7420 * @param[in] indx The index of the subpage on the main page.
7423 mdb_node_shrink(MDB_page *mp, indx_t indx)
7428 indx_t delta, nsize, len, ptr;
7431 node = NODEPTR(mp, indx);
7432 sp = (MDB_page *)NODEDATA(node);
7433 delta = SIZELEFT(sp);
7434 nsize = NODEDSZ(node) - delta;
7436 /* Prepare to shift upward, set len = length(subpage part to shift) */
7440 return; /* do not make the node uneven-sized */
7442 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
7443 for (i = NUMKEYS(sp); --i >= 0; )
7444 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
7447 sp->mp_upper = sp->mp_lower;
7448 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
7449 SETDSZ(node, nsize);
7451 /* Shift <lower nodes...initial part of subpage> upward */
7452 base = (char *)mp + mp->mp_upper + PAGEBASE;
7453 memmove(base + delta, base, (char *)sp + len - base);
7455 ptr = mp->mp_ptrs[indx];
7456 for (i = NUMKEYS(mp); --i >= 0; ) {
7457 if (mp->mp_ptrs[i] <= ptr)
7458 mp->mp_ptrs[i] += delta;
7460 mp->mp_upper += delta;
7463 /** Initial setup of a sorted-dups cursor.
7464 * Sorted duplicates are implemented as a sub-database for the given key.
7465 * The duplicate data items are actually keys of the sub-database.
7466 * Operations on the duplicate data items are performed using a sub-cursor
7467 * initialized when the sub-database is first accessed. This function does
7468 * the preliminary setup of the sub-cursor, filling in the fields that
7469 * depend only on the parent DB.
7470 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7473 mdb_xcursor_init0(MDB_cursor *mc)
7475 MDB_xcursor *mx = mc->mc_xcursor;
7477 mx->mx_cursor.mc_xcursor = NULL;
7478 mx->mx_cursor.mc_txn = mc->mc_txn;
7479 mx->mx_cursor.mc_db = &mx->mx_db;
7480 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
7481 mx->mx_cursor.mc_dbi = mc->mc_dbi;
7482 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
7483 mx->mx_cursor.mc_snum = 0;
7484 mx->mx_cursor.mc_top = 0;
7485 mx->mx_cursor.mc_flags = C_SUB;
7486 mx->mx_dbx.md_name.mv_size = 0;
7487 mx->mx_dbx.md_name.mv_data = NULL;
7488 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
7489 mx->mx_dbx.md_dcmp = NULL;
7490 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
7493 /** Final setup of a sorted-dups cursor.
7494 * Sets up the fields that depend on the data from the main cursor.
7495 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7496 * @param[in] node The data containing the #MDB_db record for the
7497 * sorted-dup database.
7500 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
7502 MDB_xcursor *mx = mc->mc_xcursor;
7504 if (node->mn_flags & F_SUBDATA) {
7505 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
7506 mx->mx_cursor.mc_pg[0] = 0;
7507 mx->mx_cursor.mc_snum = 0;
7508 mx->mx_cursor.mc_top = 0;
7509 mx->mx_cursor.mc_flags = C_SUB;
7511 MDB_page *fp = NODEDATA(node);
7512 mx->mx_db.md_pad = 0;
7513 mx->mx_db.md_flags = 0;
7514 mx->mx_db.md_depth = 1;
7515 mx->mx_db.md_branch_pages = 0;
7516 mx->mx_db.md_leaf_pages = 1;
7517 mx->mx_db.md_overflow_pages = 0;
7518 mx->mx_db.md_entries = NUMKEYS(fp);
7519 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
7520 mx->mx_cursor.mc_snum = 1;
7521 mx->mx_cursor.mc_top = 0;
7522 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
7523 mx->mx_cursor.mc_pg[0] = fp;
7524 mx->mx_cursor.mc_ki[0] = 0;
7525 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7526 mx->mx_db.md_flags = MDB_DUPFIXED;
7527 mx->mx_db.md_pad = fp->mp_pad;
7528 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7529 mx->mx_db.md_flags |= MDB_INTEGERKEY;
7532 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7533 mx->mx_db.md_root));
7534 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
7535 #if UINT_MAX < SIZE_MAX
7536 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
7537 mx->mx_dbx.md_cmp = mdb_cmp_clong;
7542 /** Fixup a sorted-dups cursor due to underlying update.
7543 * Sets up some fields that depend on the data from the main cursor.
7544 * Almost the same as init1, but skips initialization steps if the
7545 * xcursor had already been used.
7546 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
7547 * @param[in] src_mx The xcursor of an up-to-date cursor.
7548 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
7551 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
7553 MDB_xcursor *mx = mc->mc_xcursor;
7556 mx->mx_cursor.mc_snum = 1;
7557 mx->mx_cursor.mc_top = 0;
7558 mx->mx_cursor.mc_flags |= C_INITIALIZED;
7559 mx->mx_cursor.mc_ki[0] = 0;
7560 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
7561 #if UINT_MAX < SIZE_MAX
7562 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
7564 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
7567 mx->mx_db = src_mx->mx_db;
7568 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
7569 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7570 mx->mx_db.md_root));
7573 /** Initialize a cursor for a given transaction and database. */
7575 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
7578 mc->mc_backup = NULL;
7581 mc->mc_db = &txn->mt_dbs[dbi];
7582 mc->mc_dbx = &txn->mt_dbxs[dbi];
7583 mc->mc_dbflag = &txn->mt_dbflags[dbi];
7589 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
7590 mdb_tassert(txn, mx != NULL);
7591 mc->mc_xcursor = mx;
7592 mdb_xcursor_init0(mc);
7594 mc->mc_xcursor = NULL;
7596 if (*mc->mc_dbflag & DB_STALE) {
7597 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
7602 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
7605 size_t size = sizeof(MDB_cursor);
7607 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
7610 if (txn->mt_flags & MDB_TXN_BLOCKED)
7613 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7616 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
7617 size += sizeof(MDB_xcursor);
7619 if ((mc = malloc(size)) != NULL) {
7620 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
7621 if (txn->mt_cursors) {
7622 mc->mc_next = txn->mt_cursors[dbi];
7623 txn->mt_cursors[dbi] = mc;
7624 mc->mc_flags |= C_UNTRACK;
7636 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
7638 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
7641 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
7644 if (txn->mt_flags & MDB_TXN_BLOCKED)
7647 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
7651 /* Return the count of duplicate data items for the current key */
7653 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7657 if (mc == NULL || countp == NULL)
7660 if (mc->mc_xcursor == NULL)
7661 return MDB_INCOMPATIBLE;
7663 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
7666 if (!(mc->mc_flags & C_INITIALIZED))
7670 return MDB_NOTFOUND;
7672 if (mc->mc_flags & C_EOF) {
7673 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
7674 return MDB_NOTFOUND;
7675 mc->mc_flags ^= C_EOF;
7678 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7679 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7682 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7685 *countp = mc->mc_xcursor->mx_db.md_entries;
7691 mdb_cursor_close(MDB_cursor *mc)
7693 if (mc && !mc->mc_backup) {
7694 /* remove from txn, if tracked */
7695 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7696 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7697 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7699 *prev = mc->mc_next;
7706 mdb_cursor_txn(MDB_cursor *mc)
7708 if (!mc) return NULL;
7713 mdb_cursor_dbi(MDB_cursor *mc)
7718 /** Replace the key for a branch node with a new key.
7719 * Set #MDB_TXN_ERROR on failure.
7720 * @param[in] mc Cursor pointing to the node to operate on.
7721 * @param[in] key The new key to use.
7722 * @return 0 on success, non-zero on failure.
7725 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7731 int delta, ksize, oksize;
7732 indx_t ptr, i, numkeys, indx;
7735 indx = mc->mc_ki[mc->mc_top];
7736 mp = mc->mc_pg[mc->mc_top];
7737 node = NODEPTR(mp, indx);
7738 ptr = mp->mp_ptrs[indx];
7742 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7743 k2.mv_data = NODEKEY(node);
7744 k2.mv_size = node->mn_ksize;
7745 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7747 mdb_dkey(&k2, kbuf2),
7753 /* Sizes must be 2-byte aligned. */
7754 ksize = EVEN(key->mv_size);
7755 oksize = EVEN(node->mn_ksize);
7756 delta = ksize - oksize;
7758 /* Shift node contents if EVEN(key length) changed. */
7760 if (delta > 0 && SIZELEFT(mp) < delta) {
7762 /* not enough space left, do a delete and split */
7763 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7764 pgno = NODEPGNO(node);
7765 mdb_node_del(mc, 0);
7766 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7769 numkeys = NUMKEYS(mp);
7770 for (i = 0; i < numkeys; i++) {
7771 if (mp->mp_ptrs[i] <= ptr)
7772 mp->mp_ptrs[i] -= delta;
7775 base = (char *)mp + mp->mp_upper + PAGEBASE;
7776 len = ptr - mp->mp_upper + NODESIZE;
7777 memmove(base - delta, base, len);
7778 mp->mp_upper -= delta;
7780 node = NODEPTR(mp, indx);
7783 /* But even if no shift was needed, update ksize */
7784 if (node->mn_ksize != key->mv_size)
7785 node->mn_ksize = key->mv_size;
7788 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7794 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7796 /** Perform \b act while tracking temporary cursor \b mn */
7797 #define WITH_CURSOR_TRACKING(mn, act) do { \
7798 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
7799 if ((mn).mc_flags & C_SUB) { \
7800 dummy.mc_flags = C_INITIALIZED; \
7801 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
7806 tracked->mc_next = *tp; \
7809 *tp = tracked->mc_next; \
7812 /** Move a node from csrc to cdst.
7815 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
7822 unsigned short flags;
7826 /* Mark src and dst as dirty. */
7827 if ((rc = mdb_page_touch(csrc)) ||
7828 (rc = mdb_page_touch(cdst)))
7831 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7832 key.mv_size = csrc->mc_db->md_pad;
7833 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7835 data.mv_data = NULL;
7839 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7840 mdb_cassert(csrc, !((size_t)srcnode & 1));
7841 srcpg = NODEPGNO(srcnode);
7842 flags = srcnode->mn_flags;
7843 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7844 unsigned int snum = csrc->mc_snum;
7846 /* must find the lowest key below src */
7847 rc = mdb_page_search_lowest(csrc);
7850 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7851 key.mv_size = csrc->mc_db->md_pad;
7852 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7854 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7855 key.mv_size = NODEKSZ(s2);
7856 key.mv_data = NODEKEY(s2);
7858 csrc->mc_snum = snum--;
7859 csrc->mc_top = snum;
7861 key.mv_size = NODEKSZ(srcnode);
7862 key.mv_data = NODEKEY(srcnode);
7864 data.mv_size = NODEDSZ(srcnode);
7865 data.mv_data = NODEDATA(srcnode);
7867 mn.mc_xcursor = NULL;
7868 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7869 unsigned int snum = cdst->mc_snum;
7872 /* must find the lowest key below dst */
7873 mdb_cursor_copy(cdst, &mn);
7874 rc = mdb_page_search_lowest(&mn);
7877 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7878 bkey.mv_size = mn.mc_db->md_pad;
7879 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7881 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7882 bkey.mv_size = NODEKSZ(s2);
7883 bkey.mv_data = NODEKEY(s2);
7885 mn.mc_snum = snum--;
7888 rc = mdb_update_key(&mn, &bkey);
7893 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7894 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7895 csrc->mc_ki[csrc->mc_top],
7897 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7898 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7900 /* Add the node to the destination page.
7902 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7903 if (rc != MDB_SUCCESS)
7906 /* Delete the node from the source page.
7908 mdb_node_del(csrc, key.mv_size);
7911 /* Adjust other cursors pointing to mp */
7912 MDB_cursor *m2, *m3;
7913 MDB_dbi dbi = csrc->mc_dbi;
7914 MDB_page *mpd, *mps;
7916 mps = csrc->mc_pg[csrc->mc_top];
7917 /* If we're adding on the left, bump others up */
7919 mpd = cdst->mc_pg[csrc->mc_top];
7920 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7921 if (csrc->mc_flags & C_SUB)
7922 m3 = &m2->mc_xcursor->mx_cursor;
7925 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
7928 m3->mc_pg[csrc->mc_top] == mpd &&
7929 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
7930 m3->mc_ki[csrc->mc_top]++;
7933 m3->mc_pg[csrc->mc_top] == mps &&
7934 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
7935 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7936 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7937 m3->mc_ki[csrc->mc_top-1]++;
7939 if (XCURSOR_INITED(m3) && IS_LEAF(mps))
7940 XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
7943 /* Adding on the right, bump others down */
7945 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7946 if (csrc->mc_flags & C_SUB)
7947 m3 = &m2->mc_xcursor->mx_cursor;
7950 if (m3 == csrc) continue;
7951 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
7953 if (m3->mc_pg[csrc->mc_top] == mps) {
7954 if (!m3->mc_ki[csrc->mc_top]) {
7955 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7956 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7957 m3->mc_ki[csrc->mc_top-1]--;
7959 m3->mc_ki[csrc->mc_top]--;
7961 if (XCURSOR_INITED(m3) && IS_LEAF(mps))
7962 XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
7968 /* Update the parent separators.
7970 if (csrc->mc_ki[csrc->mc_top] == 0) {
7971 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7972 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7973 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7975 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7976 key.mv_size = NODEKSZ(srcnode);
7977 key.mv_data = NODEKEY(srcnode);
7979 DPRINTF(("update separator for source page %"Z"u to [%s]",
7980 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7981 mdb_cursor_copy(csrc, &mn);
7984 /* We want mdb_rebalance to find mn when doing fixups */
7985 WITH_CURSOR_TRACKING(mn,
7986 rc = mdb_update_key(&mn, &key));
7990 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7992 indx_t ix = csrc->mc_ki[csrc->mc_top];
7993 nullkey.mv_size = 0;
7994 csrc->mc_ki[csrc->mc_top] = 0;
7995 rc = mdb_update_key(csrc, &nullkey);
7996 csrc->mc_ki[csrc->mc_top] = ix;
7997 mdb_cassert(csrc, rc == MDB_SUCCESS);
8001 if (cdst->mc_ki[cdst->mc_top] == 0) {
8002 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
8003 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8004 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
8006 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
8007 key.mv_size = NODEKSZ(srcnode);
8008 key.mv_data = NODEKEY(srcnode);
8010 DPRINTF(("update separator for destination page %"Z"u to [%s]",
8011 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
8012 mdb_cursor_copy(cdst, &mn);
8015 /* We want mdb_rebalance to find mn when doing fixups */
8016 WITH_CURSOR_TRACKING(mn,
8017 rc = mdb_update_key(&mn, &key));
8021 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
8023 indx_t ix = cdst->mc_ki[cdst->mc_top];
8024 nullkey.mv_size = 0;
8025 cdst->mc_ki[cdst->mc_top] = 0;
8026 rc = mdb_update_key(cdst, &nullkey);
8027 cdst->mc_ki[cdst->mc_top] = ix;
8028 mdb_cassert(cdst, rc == MDB_SUCCESS);
8035 /** Merge one page into another.
8036 * The nodes from the page pointed to by \b csrc will
8037 * be copied to the page pointed to by \b cdst and then
8038 * the \b csrc page will be freed.
8039 * @param[in] csrc Cursor pointing to the source page.
8040 * @param[in] cdst Cursor pointing to the destination page.
8041 * @return 0 on success, non-zero on failure.
8044 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
8046 MDB_page *psrc, *pdst;
8053 psrc = csrc->mc_pg[csrc->mc_top];
8054 pdst = cdst->mc_pg[cdst->mc_top];
8056 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
8058 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
8059 mdb_cassert(csrc, cdst->mc_snum > 1);
8061 /* Mark dst as dirty. */
8062 if ((rc = mdb_page_touch(cdst)))
8065 /* get dst page again now that we've touched it. */
8066 pdst = cdst->mc_pg[cdst->mc_top];
8068 /* Move all nodes from src to dst.
8070 j = nkeys = NUMKEYS(pdst);
8071 if (IS_LEAF2(psrc)) {
8072 key.mv_size = csrc->mc_db->md_pad;
8073 key.mv_data = METADATA(psrc);
8074 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8075 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
8076 if (rc != MDB_SUCCESS)
8078 key.mv_data = (char *)key.mv_data + key.mv_size;
8081 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8082 srcnode = NODEPTR(psrc, i);
8083 if (i == 0 && IS_BRANCH(psrc)) {
8086 mdb_cursor_copy(csrc, &mn);
8087 mn.mc_xcursor = NULL;
8088 /* must find the lowest key below src */
8089 rc = mdb_page_search_lowest(&mn);
8092 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8093 key.mv_size = mn.mc_db->md_pad;
8094 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
8096 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8097 key.mv_size = NODEKSZ(s2);
8098 key.mv_data = NODEKEY(s2);
8101 key.mv_size = srcnode->mn_ksize;
8102 key.mv_data = NODEKEY(srcnode);
8105 data.mv_size = NODEDSZ(srcnode);
8106 data.mv_data = NODEDATA(srcnode);
8107 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
8108 if (rc != MDB_SUCCESS)
8113 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
8114 pdst->mp_pgno, NUMKEYS(pdst),
8115 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
8117 /* Unlink the src page from parent and add to free list.
8120 mdb_node_del(csrc, 0);
8121 if (csrc->mc_ki[csrc->mc_top] == 0) {
8123 rc = mdb_update_key(csrc, &key);
8131 psrc = csrc->mc_pg[csrc->mc_top];
8132 /* If not operating on FreeDB, allow this page to be reused
8133 * in this txn. Otherwise just add to free list.
8135 rc = mdb_page_loose(csrc, psrc);
8139 csrc->mc_db->md_leaf_pages--;
8141 csrc->mc_db->md_branch_pages--;
8143 /* Adjust other cursors pointing to mp */
8144 MDB_cursor *m2, *m3;
8145 MDB_dbi dbi = csrc->mc_dbi;
8146 unsigned int top = csrc->mc_top;
8148 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8149 if (csrc->mc_flags & C_SUB)
8150 m3 = &m2->mc_xcursor->mx_cursor;
8153 if (m3 == csrc) continue;
8154 if (m3->mc_snum < csrc->mc_snum) continue;
8155 if (m3->mc_pg[top] == psrc) {
8156 m3->mc_pg[top] = pdst;
8157 m3->mc_ki[top] += nkeys;
8158 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
8159 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
8160 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
8163 if (XCURSOR_INITED(m3) && IS_LEAF(psrc))
8164 XCURSOR_REFRESH(m3, m3->mc_pg[top], m3->mc_ki[top]);
8168 unsigned int snum = cdst->mc_snum;
8169 uint16_t depth = cdst->mc_db->md_depth;
8170 mdb_cursor_pop(cdst);
8171 rc = mdb_rebalance(cdst);
8172 /* Did the tree height change? */
8173 if (depth != cdst->mc_db->md_depth)
8174 snum += cdst->mc_db->md_depth - depth;
8175 cdst->mc_snum = snum;
8176 cdst->mc_top = snum-1;
8181 /** Copy the contents of a cursor.
8182 * @param[in] csrc The cursor to copy from.
8183 * @param[out] cdst The cursor to copy to.
8186 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
8190 cdst->mc_txn = csrc->mc_txn;
8191 cdst->mc_dbi = csrc->mc_dbi;
8192 cdst->mc_db = csrc->mc_db;
8193 cdst->mc_dbx = csrc->mc_dbx;
8194 cdst->mc_snum = csrc->mc_snum;
8195 cdst->mc_top = csrc->mc_top;
8196 cdst->mc_flags = csrc->mc_flags;
8198 for (i=0; i<csrc->mc_snum; i++) {
8199 cdst->mc_pg[i] = csrc->mc_pg[i];
8200 cdst->mc_ki[i] = csrc->mc_ki[i];
8204 /** Rebalance the tree after a delete operation.
8205 * @param[in] mc Cursor pointing to the page where rebalancing
8207 * @return 0 on success, non-zero on failure.
8210 mdb_rebalance(MDB_cursor *mc)
8214 unsigned int ptop, minkeys, thresh;
8218 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
8223 thresh = FILL_THRESHOLD;
8225 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
8226 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
8227 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
8228 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
8230 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
8231 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
8232 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
8233 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
8237 if (mc->mc_snum < 2) {
8238 MDB_page *mp = mc->mc_pg[0];
8240 DPUTS("Can't rebalance a subpage, ignoring");
8243 if (NUMKEYS(mp) == 0) {
8244 DPUTS("tree is completely empty");
8245 mc->mc_db->md_root = P_INVALID;
8246 mc->mc_db->md_depth = 0;
8247 mc->mc_db->md_leaf_pages = 0;
8248 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8251 /* Adjust cursors pointing to mp */
8254 mc->mc_flags &= ~C_INITIALIZED;
8256 MDB_cursor *m2, *m3;
8257 MDB_dbi dbi = mc->mc_dbi;
8259 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8260 if (mc->mc_flags & C_SUB)
8261 m3 = &m2->mc_xcursor->mx_cursor;
8264 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
8266 if (m3->mc_pg[0] == mp) {
8269 m3->mc_flags &= ~C_INITIALIZED;
8273 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
8275 DPUTS("collapsing root page!");
8276 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8279 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
8280 rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
8283 mc->mc_db->md_depth--;
8284 mc->mc_db->md_branch_pages--;
8285 mc->mc_ki[0] = mc->mc_ki[1];
8286 for (i = 1; i<mc->mc_db->md_depth; i++) {
8287 mc->mc_pg[i] = mc->mc_pg[i+1];
8288 mc->mc_ki[i] = mc->mc_ki[i+1];
8291 /* Adjust other cursors pointing to mp */
8292 MDB_cursor *m2, *m3;
8293 MDB_dbi dbi = mc->mc_dbi;
8295 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8296 if (mc->mc_flags & C_SUB)
8297 m3 = &m2->mc_xcursor->mx_cursor;
8300 if (m3 == mc) continue;
8301 if (!(m3->mc_flags & C_INITIALIZED))
8303 if (m3->mc_pg[0] == mp) {
8304 for (i=0; i<mc->mc_db->md_depth; i++) {
8305 m3->mc_pg[i] = m3->mc_pg[i+1];
8306 m3->mc_ki[i] = m3->mc_ki[i+1];
8314 DPUTS("root page doesn't need rebalancing");
8318 /* The parent (branch page) must have at least 2 pointers,
8319 * otherwise the tree is invalid.
8321 ptop = mc->mc_top-1;
8322 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
8324 /* Leaf page fill factor is below the threshold.
8325 * Try to move keys from left or right neighbor, or
8326 * merge with a neighbor page.
8331 mdb_cursor_copy(mc, &mn);
8332 mn.mc_xcursor = NULL;
8334 oldki = mc->mc_ki[mc->mc_top];
8335 if (mc->mc_ki[ptop] == 0) {
8336 /* We're the leftmost leaf in our parent.
8338 DPUTS("reading right neighbor");
8340 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8341 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8344 mn.mc_ki[mn.mc_top] = 0;
8345 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
8348 /* There is at least one neighbor to the left.
8350 DPUTS("reading left neighbor");
8352 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8353 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8356 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
8357 mc->mc_ki[mc->mc_top] = 0;
8361 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
8362 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
8363 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
8365 /* If the neighbor page is above threshold and has enough keys,
8366 * move one key from it. Otherwise we should try to merge them.
8367 * (A branch page must never have less than 2 keys.)
8369 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
8370 rc = mdb_node_move(&mn, mc, fromleft);
8372 /* if we inserted on left, bump position up */
8377 rc = mdb_page_merge(&mn, mc);
8379 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
8380 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
8381 /* We want mdb_rebalance to find mn when doing fixups */
8382 WITH_CURSOR_TRACKING(mn,
8383 rc = mdb_page_merge(mc, &mn));
8384 mdb_cursor_copy(&mn, mc);
8386 mc->mc_flags &= ~C_EOF;
8388 mc->mc_ki[mc->mc_top] = oldki;
8392 /** Complete a delete operation started by #mdb_cursor_del(). */
8394 mdb_cursor_del0(MDB_cursor *mc)
8400 MDB_cursor *m2, *m3;
8401 MDB_dbi dbi = mc->mc_dbi;
8403 ki = mc->mc_ki[mc->mc_top];
8404 mp = mc->mc_pg[mc->mc_top];
8405 mdb_node_del(mc, mc->mc_db->md_pad);
8406 mc->mc_db->md_entries--;
8408 /* Adjust other cursors pointing to mp */
8409 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8410 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8411 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8413 if (m3 == mc || m3->mc_snum < mc->mc_snum)
8415 if (m3->mc_pg[mc->mc_top] == mp) {
8416 if (m3->mc_ki[mc->mc_top] == ki) {
8417 m3->mc_flags |= C_DEL;
8418 if (mc->mc_db->md_flags & MDB_DUPSORT) {
8419 /* Sub-cursor referred into dataset which is gone */
8420 m3->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
8423 } else if (m3->mc_ki[mc->mc_top] > ki) {
8424 m3->mc_ki[mc->mc_top]--;
8426 if (XCURSOR_INITED(m3))
8427 XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
8431 rc = mdb_rebalance(mc);
8433 if (rc == MDB_SUCCESS) {
8434 /* DB is totally empty now, just bail out.
8435 * Other cursors adjustments were already done
8436 * by mdb_rebalance and aren't needed here.
8441 mp = mc->mc_pg[mc->mc_top];
8442 nkeys = NUMKEYS(mp);
8444 /* Adjust other cursors pointing to mp */
8445 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
8446 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8447 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8449 if (m3->mc_snum < mc->mc_snum)
8451 if (m3->mc_pg[mc->mc_top] == mp) {
8452 /* if m3 points past last node in page, find next sibling */
8453 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
8454 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8455 rc = mdb_cursor_sibling(m3, 1);
8456 if (rc == MDB_NOTFOUND) {
8457 m3->mc_flags |= C_EOF;
8462 if (mc->mc_db->md_flags & MDB_DUPSORT) {
8463 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
8464 /* If this node has dupdata, it may need to be reinited
8465 * because its data has moved.
8466 * If the xcursor was not initd it must be reinited.
8467 * Else if node points to a subDB, nothing is needed.
8468 * Else (xcursor was initd, not a subDB) needs mc_pg[0] reset.
8470 if (node->mn_flags & F_DUPDATA) {
8471 if (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
8472 if (!(node->mn_flags & F_SUBDATA))
8473 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8475 mdb_xcursor_init1(m3, node);
8476 m3->mc_xcursor->mx_cursor.mc_flags |= C_DEL;
8483 mc->mc_flags |= C_DEL;
8487 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8492 mdb_del(MDB_txn *txn, MDB_dbi dbi,
8493 MDB_val *key, MDB_val *data)
8495 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8498 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8499 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8501 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
8502 /* must ignore any data */
8506 return mdb_del0(txn, dbi, key, data, 0);
8510 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
8511 MDB_val *key, MDB_val *data, unsigned flags)
8516 MDB_val rdata, *xdata;
8520 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
8522 mdb_cursor_init(&mc, txn, dbi, &mx);
8531 flags |= MDB_NODUPDATA;
8533 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
8535 /* let mdb_page_split know about this cursor if needed:
8536 * delete will trigger a rebalance; if it needs to move
8537 * a node from one page to another, it will have to
8538 * update the parent's separator key(s). If the new sepkey
8539 * is larger than the current one, the parent page may
8540 * run out of space, triggering a split. We need this
8541 * cursor to be consistent until the end of the rebalance.
8543 mc.mc_flags |= C_UNTRACK;
8544 mc.mc_next = txn->mt_cursors[dbi];
8545 txn->mt_cursors[dbi] = &mc;
8546 rc = mdb_cursor_del(&mc, flags);
8547 txn->mt_cursors[dbi] = mc.mc_next;
8552 /** Split a page and insert a new node.
8553 * Set #MDB_TXN_ERROR on failure.
8554 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
8555 * The cursor will be updated to point to the actual page and index where
8556 * the node got inserted after the split.
8557 * @param[in] newkey The key for the newly inserted node.
8558 * @param[in] newdata The data for the newly inserted node.
8559 * @param[in] newpgno The page number, if the new node is a branch node.
8560 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
8561 * @return 0 on success, non-zero on failure.
8564 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
8565 unsigned int nflags)
8568 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
8571 int i, j, split_indx, nkeys, pmax;
8572 MDB_env *env = mc->mc_txn->mt_env;
8574 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
8575 MDB_page *copy = NULL;
8576 MDB_page *mp, *rp, *pp;
8581 mp = mc->mc_pg[mc->mc_top];
8582 newindx = mc->mc_ki[mc->mc_top];
8583 nkeys = NUMKEYS(mp);
8585 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
8586 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
8587 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
8589 /* Create a right sibling. */
8590 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
8592 rp->mp_pad = mp->mp_pad;
8593 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
8595 /* Usually when splitting the root page, the cursor
8596 * height is 1. But when called from mdb_update_key,
8597 * the cursor height may be greater because it walks
8598 * up the stack while finding the branch slot to update.
8600 if (mc->mc_top < 1) {
8601 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
8603 /* shift current top to make room for new parent */
8604 for (i=mc->mc_snum; i>0; i--) {
8605 mc->mc_pg[i] = mc->mc_pg[i-1];
8606 mc->mc_ki[i] = mc->mc_ki[i-1];
8610 mc->mc_db->md_root = pp->mp_pgno;
8611 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
8612 new_root = mc->mc_db->md_depth++;
8614 /* Add left (implicit) pointer. */
8615 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
8616 /* undo the pre-push */
8617 mc->mc_pg[0] = mc->mc_pg[1];
8618 mc->mc_ki[0] = mc->mc_ki[1];
8619 mc->mc_db->md_root = mp->mp_pgno;
8620 mc->mc_db->md_depth--;
8627 ptop = mc->mc_top-1;
8628 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
8631 mdb_cursor_copy(mc, &mn);
8632 mn.mc_xcursor = NULL;
8633 mn.mc_pg[mn.mc_top] = rp;
8634 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
8636 if (nflags & MDB_APPEND) {
8637 mn.mc_ki[mn.mc_top] = 0;
8639 split_indx = newindx;
8643 split_indx = (nkeys+1) / 2;
8648 unsigned int lsize, rsize, ksize;
8649 /* Move half of the keys to the right sibling */
8650 x = mc->mc_ki[mc->mc_top] - split_indx;
8651 ksize = mc->mc_db->md_pad;
8652 split = LEAF2KEY(mp, split_indx, ksize);
8653 rsize = (nkeys - split_indx) * ksize;
8654 lsize = (nkeys - split_indx) * sizeof(indx_t);
8655 mp->mp_lower -= lsize;
8656 rp->mp_lower += lsize;
8657 mp->mp_upper += rsize - lsize;
8658 rp->mp_upper -= rsize - lsize;
8659 sepkey.mv_size = ksize;
8660 if (newindx == split_indx) {
8661 sepkey.mv_data = newkey->mv_data;
8663 sepkey.mv_data = split;
8666 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
8667 memcpy(rp->mp_ptrs, split, rsize);
8668 sepkey.mv_data = rp->mp_ptrs;
8669 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
8670 memcpy(ins, newkey->mv_data, ksize);
8671 mp->mp_lower += sizeof(indx_t);
8672 mp->mp_upper -= ksize - sizeof(indx_t);
8675 memcpy(rp->mp_ptrs, split, x * ksize);
8676 ins = LEAF2KEY(rp, x, ksize);
8677 memcpy(ins, newkey->mv_data, ksize);
8678 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
8679 rp->mp_lower += sizeof(indx_t);
8680 rp->mp_upper -= ksize - sizeof(indx_t);
8681 mc->mc_ki[mc->mc_top] = x;
8684 int psize, nsize, k;
8685 /* Maximum free space in an empty page */
8686 pmax = env->me_psize - PAGEHDRSZ;
8688 nsize = mdb_leaf_size(env, newkey, newdata);
8690 nsize = mdb_branch_size(env, newkey);
8691 nsize = EVEN(nsize);
8693 /* grab a page to hold a temporary copy */
8694 copy = mdb_page_malloc(mc->mc_txn, 1);
8699 copy->mp_pgno = mp->mp_pgno;
8700 copy->mp_flags = mp->mp_flags;
8701 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
8702 copy->mp_upper = env->me_psize - PAGEBASE;
8704 /* prepare to insert */
8705 for (i=0, j=0; i<nkeys; i++) {
8707 copy->mp_ptrs[j++] = 0;
8709 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
8712 /* When items are relatively large the split point needs
8713 * to be checked, because being off-by-one will make the
8714 * difference between success or failure in mdb_node_add.
8716 * It's also relevant if a page happens to be laid out
8717 * such that one half of its nodes are all "small" and
8718 * the other half of its nodes are "large." If the new
8719 * item is also "large" and falls on the half with
8720 * "large" nodes, it also may not fit.
8722 * As a final tweak, if the new item goes on the last
8723 * spot on the page (and thus, onto the new page), bias
8724 * the split so the new page is emptier than the old page.
8725 * This yields better packing during sequential inserts.
8727 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
8728 /* Find split point */
8730 if (newindx <= split_indx || newindx >= nkeys) {
8732 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
8737 for (; i!=k; i+=j) {
8742 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8743 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
8745 if (F_ISSET(node->mn_flags, F_BIGDATA))
8746 psize += sizeof(pgno_t);
8748 psize += NODEDSZ(node);
8750 psize = EVEN(psize);
8752 if (psize > pmax || i == k-j) {
8753 split_indx = i + (j<0);
8758 if (split_indx == newindx) {
8759 sepkey.mv_size = newkey->mv_size;
8760 sepkey.mv_data = newkey->mv_data;
8762 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
8763 sepkey.mv_size = node->mn_ksize;
8764 sepkey.mv_data = NODEKEY(node);
8769 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
8771 /* Copy separator key to the parent.
8773 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
8774 int snum = mc->mc_snum;
8778 /* We want other splits to find mn when doing fixups */
8779 WITH_CURSOR_TRACKING(mn,
8780 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
8785 if (mc->mc_snum > snum) {
8788 /* Right page might now have changed parent.
8789 * Check if left page also changed parent.
8791 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8792 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8793 for (i=0; i<ptop; i++) {
8794 mc->mc_pg[i] = mn.mc_pg[i];
8795 mc->mc_ki[i] = mn.mc_ki[i];
8797 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8798 if (mn.mc_ki[ptop]) {
8799 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8801 /* find right page's left sibling */
8802 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8803 mdb_cursor_sibling(mc, 0);
8808 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8811 if (rc != MDB_SUCCESS) {
8814 if (nflags & MDB_APPEND) {
8815 mc->mc_pg[mc->mc_top] = rp;
8816 mc->mc_ki[mc->mc_top] = 0;
8817 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8820 for (i=0; i<mc->mc_top; i++)
8821 mc->mc_ki[i] = mn.mc_ki[i];
8822 } else if (!IS_LEAF2(mp)) {
8824 mc->mc_pg[mc->mc_top] = rp;
8829 rkey.mv_data = newkey->mv_data;
8830 rkey.mv_size = newkey->mv_size;
8836 /* Update index for the new key. */
8837 mc->mc_ki[mc->mc_top] = j;
8839 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8840 rkey.mv_data = NODEKEY(node);
8841 rkey.mv_size = node->mn_ksize;
8843 xdata.mv_data = NODEDATA(node);
8844 xdata.mv_size = NODEDSZ(node);
8847 pgno = NODEPGNO(node);
8848 flags = node->mn_flags;
8851 if (!IS_LEAF(mp) && j == 0) {
8852 /* First branch index doesn't need key data. */
8856 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8862 mc->mc_pg[mc->mc_top] = copy;
8867 } while (i != split_indx);
8869 nkeys = NUMKEYS(copy);
8870 for (i=0; i<nkeys; i++)
8871 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8872 mp->mp_lower = copy->mp_lower;
8873 mp->mp_upper = copy->mp_upper;
8874 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8875 env->me_psize - copy->mp_upper - PAGEBASE);
8877 /* reset back to original page */
8878 if (newindx < split_indx) {
8879 mc->mc_pg[mc->mc_top] = mp;
8881 mc->mc_pg[mc->mc_top] = rp;
8883 /* Make sure mc_ki is still valid.
8885 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8886 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8887 for (i=0; i<=ptop; i++) {
8888 mc->mc_pg[i] = mn.mc_pg[i];
8889 mc->mc_ki[i] = mn.mc_ki[i];
8893 if (nflags & MDB_RESERVE) {
8894 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8895 if (!(node->mn_flags & F_BIGDATA))
8896 newdata->mv_data = NODEDATA(node);
8899 if (newindx >= split_indx) {
8900 mc->mc_pg[mc->mc_top] = rp;
8902 /* Make sure mc_ki is still valid.
8904 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8905 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8906 for (i=0; i<=ptop; i++) {
8907 mc->mc_pg[i] = mn.mc_pg[i];
8908 mc->mc_ki[i] = mn.mc_ki[i];
8915 /* Adjust other cursors pointing to mp */
8916 MDB_cursor *m2, *m3;
8917 MDB_dbi dbi = mc->mc_dbi;
8918 nkeys = NUMKEYS(mp);
8920 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8921 if (mc->mc_flags & C_SUB)
8922 m3 = &m2->mc_xcursor->mx_cursor;
8927 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8931 /* sub cursors may be on different DB */
8932 if (m3->mc_pg[0] != mp)
8935 for (k=new_root; k>=0; k--) {
8936 m3->mc_ki[k+1] = m3->mc_ki[k];
8937 m3->mc_pg[k+1] = m3->mc_pg[k];
8939 if (m3->mc_ki[0] >= nkeys) {
8944 m3->mc_pg[0] = mc->mc_pg[0];
8948 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8949 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8950 m3->mc_ki[mc->mc_top]++;
8951 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8952 m3->mc_pg[mc->mc_top] = rp;
8953 m3->mc_ki[mc->mc_top] -= nkeys;
8954 for (i=0; i<mc->mc_top; i++) {
8955 m3->mc_ki[i] = mn.mc_ki[i];
8956 m3->mc_pg[i] = mn.mc_pg[i];
8959 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8960 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8963 if (XCURSOR_INITED(m3) && IS_LEAF(mp))
8964 XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
8967 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8970 if (copy) /* tmp page */
8971 mdb_page_free(env, copy);
8973 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8978 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8979 MDB_val *key, MDB_val *data, unsigned int flags)
8985 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8988 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
8991 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8992 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8994 mdb_cursor_init(&mc, txn, dbi, &mx);
8995 mc.mc_next = txn->mt_cursors[dbi];
8996 txn->mt_cursors[dbi] = &mc;
8997 rc = mdb_cursor_put(&mc, key, data, flags);
8998 txn->mt_cursors[dbi] = mc.mc_next;
9003 #define MDB_WBUF (1024*1024)
9005 #define MDB_EOF 0x10 /**< #mdb_env_copyfd1() is done reading */
9007 /** State needed for a double-buffering compacting copy. */
9008 typedef struct mdb_copy {
9011 pthread_mutex_t mc_mutex;
9012 pthread_cond_t mc_cond; /**< Condition variable for #mc_new */
9017 pgno_t mc_next_pgno;
9019 int mc_toggle; /**< Buffer number in provider */
9020 int mc_new; /**< (0-2 buffers to write) | (#MDB_EOF at end) */
9021 /** Error code. Never cleared if set. Both threads can set nonzero
9022 * to fail the copy. Not mutex-protected, LMDB expects atomic int.
9024 volatile int mc_error;
9027 /** Dedicated writer thread for compacting copy. */
9028 static THREAD_RET ESECT CALL_CONV
9029 mdb_env_copythr(void *arg)
9033 int toggle = 0, wsize, rc;
9036 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9039 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9043 sigaddset(&set, SIGPIPE);
9044 if ((rc = pthread_sigmask(SIG_BLOCK, &set, NULL)) != 0)
9049 pthread_mutex_lock(&my->mc_mutex);
9052 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9053 if (my->mc_new == 0 + MDB_EOF) /* 0 buffers, just EOF */
9055 wsize = my->mc_wlen[toggle];
9056 ptr = my->mc_wbuf[toggle];
9059 while (wsize > 0 && !my->mc_error) {
9060 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
9063 #if defined(SIGPIPE) && !defined(_WIN32)
9065 /* Collect the pending SIGPIPE, otherwise at least OS X
9066 * gives it to the process on thread-exit (ITS#8504).
9069 sigwait(&set, &tmp);
9073 } else if (len > 0) {
9086 /* If there's an overflow page tail, write it too */
9087 if (my->mc_olen[toggle]) {
9088 wsize = my->mc_olen[toggle];
9089 ptr = my->mc_over[toggle];
9090 my->mc_olen[toggle] = 0;
9093 my->mc_wlen[toggle] = 0;
9095 /* Return the empty buffer to provider */
9097 pthread_cond_signal(&my->mc_cond);
9099 pthread_mutex_unlock(&my->mc_mutex);
9100 return (THREAD_RET)0;
9104 /** Give buffer and/or #MDB_EOF to writer thread, await unused buffer.
9106 * @param[in] my control structure.
9107 * @param[in] adjust (1 to hand off 1 buffer) | (MDB_EOF when ending).
9110 mdb_env_cthr_toggle(mdb_copy *my, int adjust)
9112 pthread_mutex_lock(&my->mc_mutex);
9113 my->mc_new += adjust;
9114 pthread_cond_signal(&my->mc_cond);
9115 while (my->mc_new & 2) /* both buffers in use */
9116 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9117 pthread_mutex_unlock(&my->mc_mutex);
9119 my->mc_toggle ^= (adjust & 1);
9120 /* Both threads reset mc_wlen, to be safe from threading errors */
9121 my->mc_wlen[my->mc_toggle] = 0;
9122 return my->mc_error;
9125 /** Depth-first tree traversal for compacting copy.
9126 * @param[in] my control structure.
9127 * @param[in,out] pg database root.
9128 * @param[in] flags includes #F_DUPDATA if it is a sorted-duplicate sub-DB.
9131 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
9133 MDB_cursor mc = {0};
9135 MDB_page *mo, *mp, *leaf;
9140 /* Empty DB, nothing to do */
9141 if (*pg == P_INVALID)
9145 mc.mc_txn = my->mc_txn;
9147 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
9150 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
9154 /* Make cursor pages writable */
9155 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
9159 for (i=0; i<mc.mc_top; i++) {
9160 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
9161 mc.mc_pg[i] = (MDB_page *)ptr;
9162 ptr += my->mc_env->me_psize;
9165 /* This is writable space for a leaf page. Usually not needed. */
9166 leaf = (MDB_page *)ptr;
9168 toggle = my->mc_toggle;
9169 while (mc.mc_snum > 0) {
9171 mp = mc.mc_pg[mc.mc_top];
9175 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
9176 for (i=0; i<n; i++) {
9177 ni = NODEPTR(mp, i);
9178 if (ni->mn_flags & F_BIGDATA) {
9182 /* Need writable leaf */
9184 mc.mc_pg[mc.mc_top] = leaf;
9185 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9187 ni = NODEPTR(mp, i);
9190 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9191 memcpy(NODEDATA(ni), &my->mc_next_pgno, sizeof(pgno_t));
9192 rc = mdb_page_get(&mc, pg, &omp, NULL);
9195 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9196 rc = mdb_env_cthr_toggle(my, 1);
9199 toggle = my->mc_toggle;
9201 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9202 memcpy(mo, omp, my->mc_env->me_psize);
9203 mo->mp_pgno = my->mc_next_pgno;
9204 my->mc_next_pgno += omp->mp_pages;
9205 my->mc_wlen[toggle] += my->mc_env->me_psize;
9206 if (omp->mp_pages > 1) {
9207 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
9208 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
9209 rc = mdb_env_cthr_toggle(my, 1);
9212 toggle = my->mc_toggle;
9214 } else if (ni->mn_flags & F_SUBDATA) {
9217 /* Need writable leaf */
9219 mc.mc_pg[mc.mc_top] = leaf;
9220 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9222 ni = NODEPTR(mp, i);
9225 memcpy(&db, NODEDATA(ni), sizeof(db));
9226 my->mc_toggle = toggle;
9227 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
9230 toggle = my->mc_toggle;
9231 memcpy(NODEDATA(ni), &db, sizeof(db));
9236 mc.mc_ki[mc.mc_top]++;
9237 if (mc.mc_ki[mc.mc_top] < n) {
9240 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
9242 rc = mdb_page_get(&mc, pg, &mp, NULL);
9247 mc.mc_ki[mc.mc_top] = 0;
9248 if (IS_BRANCH(mp)) {
9249 /* Whenever we advance to a sibling branch page,
9250 * we must proceed all the way down to its first leaf.
9252 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
9255 mc.mc_pg[mc.mc_top] = mp;
9259 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9260 rc = mdb_env_cthr_toggle(my, 1);
9263 toggle = my->mc_toggle;
9265 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9266 mdb_page_copy(mo, mp, my->mc_env->me_psize);
9267 mo->mp_pgno = my->mc_next_pgno++;
9268 my->mc_wlen[toggle] += my->mc_env->me_psize;
9270 /* Update parent if there is one */
9271 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
9272 SETPGNO(ni, mo->mp_pgno);
9273 mdb_cursor_pop(&mc);
9275 /* Otherwise we're done */
9285 /** Copy environment with compaction. */
9287 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
9292 MDB_txn *txn = NULL;
9294 pgno_t root, new_root;
9295 int rc = MDB_SUCCESS;
9298 if (!(my.mc_mutex = CreateMutex(NULL, FALSE, NULL)) ||
9299 !(my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL))) {
9303 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
9304 if (my.mc_wbuf[0] == NULL) {
9305 /* _aligned_malloc() sets errno, but we use Windows error codes */
9306 rc = ERROR_NOT_ENOUGH_MEMORY;
9310 if ((rc = pthread_mutex_init(&my.mc_mutex, NULL)) != 0)
9312 if ((rc = pthread_cond_init(&my.mc_cond, NULL)) != 0)
9314 #ifdef HAVE_MEMALIGN
9315 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
9316 if (my.mc_wbuf[0] == NULL) {
9323 if ((rc = posix_memalign(&p, env->me_os_psize, MDB_WBUF*2)) != 0)
9329 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
9330 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
9331 my.mc_next_pgno = NUM_METAS;
9334 rc = THREAD_CREATE(thr, mdb_env_copythr, &my);
9338 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9342 mp = (MDB_page *)my.mc_wbuf[0];
9343 memset(mp, 0, NUM_METAS * env->me_psize);
9345 mp->mp_flags = P_META;
9346 mm = (MDB_meta *)METADATA(mp);
9347 mdb_env_init_meta0(env, mm);
9348 mm->mm_address = env->me_metas[0]->mm_address;
9350 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
9352 mp->mp_flags = P_META;
9353 *(MDB_meta *)METADATA(mp) = *mm;
9354 mm = (MDB_meta *)METADATA(mp);
9356 /* Set metapage 1 with current main DB */
9357 root = new_root = txn->mt_dbs[MAIN_DBI].md_root;
9358 if (root != P_INVALID) {
9359 /* Count free pages + freeDB pages. Subtract from last_pg
9360 * to find the new last_pg, which also becomes the new root.
9362 MDB_ID freecount = 0;
9365 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
9366 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
9367 freecount += *(MDB_ID *)data.mv_data;
9368 if (rc != MDB_NOTFOUND)
9370 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
9371 txn->mt_dbs[FREE_DBI].md_leaf_pages +
9372 txn->mt_dbs[FREE_DBI].md_overflow_pages;
9374 new_root = txn->mt_next_pgno - 1 - freecount;
9375 mm->mm_last_pg = new_root;
9376 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
9377 mm->mm_dbs[MAIN_DBI].md_root = new_root;
9379 /* When the DB is empty, handle it specially to
9380 * fix any breakage like page leaks from ITS#8174.
9382 mm->mm_dbs[MAIN_DBI].md_flags = txn->mt_dbs[MAIN_DBI].md_flags;
9384 if (root != P_INVALID || mm->mm_dbs[MAIN_DBI].md_flags) {
9385 mm->mm_txnid = 1; /* use metapage 1 */
9388 my.mc_wlen[0] = env->me_psize * NUM_METAS;
9390 rc = mdb_env_cwalk(&my, &root, 0);
9391 if (rc == MDB_SUCCESS && root != new_root) {
9392 rc = MDB_INCOMPATIBLE; /* page leak or corrupt DB */
9398 mdb_env_cthr_toggle(&my, 1 | MDB_EOF);
9399 rc = THREAD_FINISH(thr);
9404 if (my.mc_wbuf[0]) _aligned_free(my.mc_wbuf[0]);
9405 if (my.mc_cond) CloseHandle(my.mc_cond);
9406 if (my.mc_mutex) CloseHandle(my.mc_mutex);
9408 free(my.mc_wbuf[0]);
9409 pthread_cond_destroy(&my.mc_cond);
9411 pthread_mutex_destroy(&my.mc_mutex);
9413 return rc ? rc : my.mc_error;
9416 /** Copy environment as-is. */
9418 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
9420 MDB_txn *txn = NULL;
9421 mdb_mutexref_t wmutex = NULL;
9427 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9431 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9434 /* Do the lock/unlock of the reader mutex before starting the
9435 * write txn. Otherwise other read txns could block writers.
9437 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9442 /* We must start the actual read txn after blocking writers */
9443 mdb_txn_end(txn, MDB_END_RESET_TMP);
9445 /* Temporarily block writers until we snapshot the meta pages */
9446 wmutex = env->me_wmutex;
9447 if (LOCK_MUTEX(rc, env, wmutex))
9450 rc = mdb_txn_renew0(txn);
9452 UNLOCK_MUTEX(wmutex);
9457 wsize = env->me_psize * NUM_METAS;
9461 DO_WRITE(rc, fd, ptr, w2, len);
9465 } else if (len > 0) {
9471 /* Non-blocking or async handles are not supported */
9477 UNLOCK_MUTEX(wmutex);
9482 w3 = txn->mt_next_pgno * env->me_psize;
9485 if ((rc = mdb_fsize(env->me_fd, &fsize)))
9492 if (wsize > MAX_WRITE)
9496 DO_WRITE(rc, fd, ptr, w2, len);
9500 } else if (len > 0) {
9517 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
9519 if (flags & MDB_CP_COMPACT)
9520 return mdb_env_copyfd1(env, fd);
9522 return mdb_env_copyfd0(env, fd);
9526 mdb_env_copyfd(MDB_env *env, HANDLE fd)
9528 return mdb_env_copyfd2(env, fd, 0);
9532 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
9536 HANDLE newfd = INVALID_HANDLE_VALUE;
9538 rc = mdb_fname_init(path, env->me_flags | MDB_NOLOCK, &fname);
9539 if (rc == MDB_SUCCESS) {
9540 rc = mdb_fopen(env, &fname, MDB_O_COPY, 0666, &newfd);
9541 mdb_fname_destroy(fname);
9543 if (rc == MDB_SUCCESS) {
9544 rc = mdb_env_copyfd2(env, newfd, flags);
9545 if (close(newfd) < 0 && rc == MDB_SUCCESS)
9552 mdb_env_copy(MDB_env *env, const char *path)
9554 return mdb_env_copy2(env, path, 0);
9558 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
9560 if (flag & ~CHANGEABLE)
9563 env->me_flags |= flag;
9565 env->me_flags &= ~flag;
9570 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
9575 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
9580 mdb_env_set_userctx(MDB_env *env, void *ctx)
9584 env->me_userctx = ctx;
9589 mdb_env_get_userctx(MDB_env *env)
9591 return env ? env->me_userctx : NULL;
9595 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
9600 env->me_assert_func = func;
9606 mdb_env_get_path(MDB_env *env, const char **arg)
9611 *arg = env->me_path;
9616 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
9625 /** Common code for #mdb_stat() and #mdb_env_stat().
9626 * @param[in] env the environment to operate in.
9627 * @param[in] db the #MDB_db record containing the stats to return.
9628 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
9629 * @return 0, this function always succeeds.
9632 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
9634 arg->ms_psize = env->me_psize;
9635 arg->ms_depth = db->md_depth;
9636 arg->ms_branch_pages = db->md_branch_pages;
9637 arg->ms_leaf_pages = db->md_leaf_pages;
9638 arg->ms_overflow_pages = db->md_overflow_pages;
9639 arg->ms_entries = db->md_entries;
9645 mdb_env_stat(MDB_env *env, MDB_stat *arg)
9649 if (env == NULL || arg == NULL)
9652 meta = mdb_env_pick_meta(env);
9654 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
9658 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
9662 if (env == NULL || arg == NULL)
9665 meta = mdb_env_pick_meta(env);
9666 arg->me_mapaddr = meta->mm_address;
9667 arg->me_last_pgno = meta->mm_last_pg;
9668 arg->me_last_txnid = meta->mm_txnid;
9670 arg->me_mapsize = env->me_mapsize;
9671 arg->me_maxreaders = env->me_maxreaders;
9672 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
9676 /** Set the default comparison functions for a database.
9677 * Called immediately after a database is opened to set the defaults.
9678 * The user can then override them with #mdb_set_compare() or
9679 * #mdb_set_dupsort().
9680 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
9681 * @param[in] dbi A database handle returned by #mdb_dbi_open()
9684 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
9686 uint16_t f = txn->mt_dbs[dbi].md_flags;
9688 txn->mt_dbxs[dbi].md_cmp =
9689 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
9690 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
9692 txn->mt_dbxs[dbi].md_dcmp =
9693 !(f & MDB_DUPSORT) ? 0 :
9694 ((f & MDB_INTEGERDUP)
9695 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
9696 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
9699 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
9705 int rc, dbflag, exact;
9706 unsigned int unused = 0, seq;
9710 if (flags & ~VALID_FLAGS)
9712 if (txn->mt_flags & MDB_TXN_BLOCKED)
9718 if (flags & PERSISTENT_FLAGS) {
9719 uint16_t f2 = flags & PERSISTENT_FLAGS;
9720 /* make sure flag changes get committed */
9721 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
9722 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
9723 txn->mt_flags |= MDB_TXN_DIRTY;
9726 mdb_default_cmp(txn, MAIN_DBI);
9730 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
9731 mdb_default_cmp(txn, MAIN_DBI);
9734 /* Is the DB already open? */
9736 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
9737 if (!txn->mt_dbxs[i].md_name.mv_size) {
9738 /* Remember this free slot */
9739 if (!unused) unused = i;
9742 if (len == txn->mt_dbxs[i].md_name.mv_size &&
9743 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
9749 /* If no free slot and max hit, fail */
9750 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
9751 return MDB_DBS_FULL;
9753 /* Cannot mix named databases with some mainDB flags */
9754 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
9755 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
9757 /* Find the DB info */
9758 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
9761 key.mv_data = (void *)name;
9762 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
9763 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
9764 if (rc == MDB_SUCCESS) {
9765 /* make sure this is actually a DB */
9766 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
9767 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
9768 return MDB_INCOMPATIBLE;
9770 if (rc != MDB_NOTFOUND || !(flags & MDB_CREATE))
9772 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9776 /* Done here so we cannot fail after creating a new DB */
9777 if ((namedup = strdup(name)) == NULL)
9781 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
9782 data.mv_size = sizeof(MDB_db);
9783 data.mv_data = &dummy;
9784 memset(&dummy, 0, sizeof(dummy));
9785 dummy.md_root = P_INVALID;
9786 dummy.md_flags = flags & PERSISTENT_FLAGS;
9787 WITH_CURSOR_TRACKING(mc,
9788 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA));
9795 /* Got info, register DBI in this txn */
9796 unsigned int slot = unused ? unused : txn->mt_numdbs;
9797 txn->mt_dbxs[slot].md_name.mv_data = namedup;
9798 txn->mt_dbxs[slot].md_name.mv_size = len;
9799 txn->mt_dbxs[slot].md_rel = NULL;
9800 txn->mt_dbflags[slot] = dbflag;
9801 /* txn-> and env-> are the same in read txns, use
9802 * tmp variable to avoid undefined assignment
9804 seq = ++txn->mt_env->me_dbiseqs[slot];
9805 txn->mt_dbiseqs[slot] = seq;
9807 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
9809 mdb_default_cmp(txn, slot);
9819 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9821 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
9824 if (txn->mt_flags & MDB_TXN_BLOCKED)
9827 if (txn->mt_dbflags[dbi] & DB_STALE) {
9830 /* Stale, must read the DB's root. cursor_init does it for us. */
9831 mdb_cursor_init(&mc, txn, dbi, &mx);
9833 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9836 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9839 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
9841 ptr = env->me_dbxs[dbi].md_name.mv_data;
9842 /* If there was no name, this was already closed */
9844 env->me_dbxs[dbi].md_name.mv_data = NULL;
9845 env->me_dbxs[dbi].md_name.mv_size = 0;
9846 env->me_dbflags[dbi] = 0;
9847 env->me_dbiseqs[dbi]++;
9852 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9854 /* We could return the flags for the FREE_DBI too but what's the point? */
9855 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9857 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9861 /** Add all the DB's pages to the free list.
9862 * @param[in] mc Cursor on the DB to free.
9863 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9864 * @return 0 on success, non-zero on failure.
9867 mdb_drop0(MDB_cursor *mc, int subs)
9871 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9872 if (rc == MDB_SUCCESS) {
9873 MDB_txn *txn = mc->mc_txn;
9878 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
9879 * This also avoids any P_LEAF2 pages, which have no nodes.
9880 * Also if the DB doesn't have sub-DBs and has no overflow
9881 * pages, omit scanning leaves.
9883 if ((mc->mc_flags & C_SUB) ||
9884 (!subs && !mc->mc_db->md_overflow_pages))
9887 mdb_cursor_copy(mc, &mx);
9888 while (mc->mc_snum > 0) {
9889 MDB_page *mp = mc->mc_pg[mc->mc_top];
9890 unsigned n = NUMKEYS(mp);
9892 for (i=0; i<n; i++) {
9893 ni = NODEPTR(mp, i);
9894 if (ni->mn_flags & F_BIGDATA) {
9897 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9898 rc = mdb_page_get(mc, pg, &omp, NULL);
9901 mdb_cassert(mc, IS_OVERFLOW(omp));
9902 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9906 mc->mc_db->md_overflow_pages -= omp->mp_pages;
9907 if (!mc->mc_db->md_overflow_pages && !subs)
9909 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9910 mdb_xcursor_init1(mc, ni);
9911 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9916 if (!subs && !mc->mc_db->md_overflow_pages)
9919 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9921 for (i=0; i<n; i++) {
9923 ni = NODEPTR(mp, i);
9926 mdb_midl_xappend(txn->mt_free_pgs, pg);
9931 mc->mc_ki[mc->mc_top] = i;
9932 rc = mdb_cursor_sibling(mc, 1);
9934 if (rc != MDB_NOTFOUND)
9936 /* no more siblings, go back to beginning
9937 * of previous level.
9942 for (i=1; i<mc->mc_snum; i++) {
9944 mc->mc_pg[i] = mx.mc_pg[i];
9949 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9952 txn->mt_flags |= MDB_TXN_ERROR;
9953 } else if (rc == MDB_NOTFOUND) {
9956 mc->mc_flags &= ~C_INITIALIZED;
9960 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9962 MDB_cursor *mc, *m2;
9965 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9968 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9971 if (TXN_DBI_CHANGED(txn, dbi))
9974 rc = mdb_cursor_open(txn, dbi, &mc);
9978 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9979 /* Invalidate the dropped DB's cursors */
9980 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9981 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9985 /* Can't delete the main DB */
9986 if (del && dbi >= CORE_DBS) {
9987 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
9989 txn->mt_dbflags[dbi] = DB_STALE;
9990 mdb_dbi_close(txn->mt_env, dbi);
9992 txn->mt_flags |= MDB_TXN_ERROR;
9995 /* reset the DB record, mark it dirty */
9996 txn->mt_dbflags[dbi] |= DB_DIRTY;
9997 txn->mt_dbs[dbi].md_depth = 0;
9998 txn->mt_dbs[dbi].md_branch_pages = 0;
9999 txn->mt_dbs[dbi].md_leaf_pages = 0;
10000 txn->mt_dbs[dbi].md_overflow_pages = 0;
10001 txn->mt_dbs[dbi].md_entries = 0;
10002 txn->mt_dbs[dbi].md_root = P_INVALID;
10004 txn->mt_flags |= MDB_TXN_DIRTY;
10007 mdb_cursor_close(mc);
10011 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10013 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10016 txn->mt_dbxs[dbi].md_cmp = cmp;
10017 return MDB_SUCCESS;
10020 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10022 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10025 txn->mt_dbxs[dbi].md_dcmp = cmp;
10026 return MDB_SUCCESS;
10029 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
10031 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10034 txn->mt_dbxs[dbi].md_rel = rel;
10035 return MDB_SUCCESS;
10038 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
10040 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10043 txn->mt_dbxs[dbi].md_relctx = ctx;
10044 return MDB_SUCCESS;
10048 mdb_env_get_maxkeysize(MDB_env *env)
10050 return ENV_MAXKEY(env);
10054 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
10056 unsigned int i, rdrs;
10059 int rc = 0, first = 1;
10063 if (!env->me_txns) {
10064 return func("(no reader locks)\n", ctx);
10066 rdrs = env->me_txns->mti_numreaders;
10067 mr = env->me_txns->mti_readers;
10068 for (i=0; i<rdrs; i++) {
10069 if (mr[i].mr_pid) {
10070 txnid_t txnid = mr[i].mr_txnid;
10071 sprintf(buf, txnid == (txnid_t)-1 ?
10072 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
10073 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
10076 rc = func(" pid thread txnid\n", ctx);
10080 rc = func(buf, ctx);
10086 rc = func("(no active readers)\n", ctx);
10091 /** Insert pid into list if not already present.
10092 * return -1 if already present.
10095 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
10097 /* binary search of pid in list */
10099 unsigned cursor = 1;
10101 unsigned n = ids[0];
10104 unsigned pivot = n >> 1;
10105 cursor = base + pivot + 1;
10106 val = pid - ids[cursor];
10111 } else if ( val > 0 ) {
10116 /* found, so it's a duplicate */
10125 for (n = ids[0]; n > cursor; n--)
10132 mdb_reader_check(MDB_env *env, int *dead)
10138 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
10141 /** As #mdb_reader_check(). \b rlocked is set if caller locked #me_rmutex. */
10143 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
10145 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
10146 unsigned int i, j, rdrs;
10148 MDB_PID_T *pids, pid;
10149 int rc = MDB_SUCCESS, count = 0;
10151 rdrs = env->me_txns->mti_numreaders;
10152 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
10156 mr = env->me_txns->mti_readers;
10157 for (i=0; i<rdrs; i++) {
10158 pid = mr[i].mr_pid;
10159 if (pid && pid != env->me_pid) {
10160 if (mdb_pid_insert(pids, pid) == 0) {
10161 if (!mdb_reader_pid(env, Pidcheck, pid)) {
10162 /* Stale reader found */
10165 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
10166 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
10168 rdrs = 0; /* the above checked all readers */
10170 /* Recheck, a new process may have reused pid */
10171 if (mdb_reader_pid(env, Pidcheck, pid))
10175 for (; j<rdrs; j++)
10176 if (mr[j].mr_pid == pid) {
10177 DPRINTF(("clear stale reader pid %u txn %"Z"d",
10178 (unsigned) pid, mr[j].mr_txnid));
10183 UNLOCK_MUTEX(rmutex);
10194 #ifdef MDB_ROBUST_SUPPORTED
10195 /** Handle #LOCK_MUTEX0() failure.
10196 * Try to repair the lock file if the mutex owner died.
10197 * @param[in] env the environment handle
10198 * @param[in] mutex LOCK_MUTEX0() mutex
10199 * @param[in] rc LOCK_MUTEX0() error (nonzero)
10200 * @return 0 on success with the mutex locked, or an error code on failure.
10203 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10208 if (rc == MDB_OWNERDEAD) {
10209 /* We own the mutex. Clean up after dead previous owner. */
10211 rlocked = (mutex == env->me_rmutex);
10213 /* Keep mti_txnid updated, otherwise next writer can
10214 * overwrite data which latest meta page refers to.
10216 meta = mdb_env_pick_meta(env);
10217 env->me_txns->mti_txnid = meta->mm_txnid;
10218 /* env is hosed if the dead thread was ours */
10220 env->me_flags |= MDB_FATAL_ERROR;
10221 env->me_txn = NULL;
10225 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
10226 (rc ? "this process' env is hosed" : "recovering")));
10227 rc2 = mdb_reader_check0(env, rlocked, NULL);
10229 rc2 = mdb_mutex_consistent(mutex);
10230 if (rc || (rc = rc2)) {
10231 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
10232 UNLOCK_MUTEX(mutex);
10238 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
10243 #endif /* MDB_ROBUST_SUPPORTED */
10245 #if defined(_WIN32)
10246 /** Convert \b src to new wchar_t[] string with room for \b xtra extra chars */
10248 utf8_to_utf16(const char *src, MDB_name *dst, int xtra)
10251 wchar_t *result = NULL;
10252 for (;;) { /* malloc result, then fill it in */
10253 need = MultiByteToWideChar(CP_UTF8, 0, src, -1, result, need);
10260 result = malloc(sizeof(wchar_t) * (need + xtra));
10265 dst->mn_alloced = 1;
10266 dst->mn_len = need - 1;
10267 dst->mn_val = result;
10268 return MDB_SUCCESS;
10271 #endif /* defined(_WIN32) */