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 */
1230 #define XCURSOR_INITED(mc) \
1231 ((mc)->mc_xcursor && ((mc)->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
1233 /** Update the xcursor's sub-page pointer, if any, in \b mc. Needed
1234 * when the node which contains the sub-page may have moved. Called
1235 * with leaf page \b mp = mc->mc_pg[\b top].
1237 #define XCURSOR_REFRESH(mc, top, mp) do { \
1238 MDB_page *xr_pg = (mp); \
1239 MDB_node *xr_node; \
1240 if (!XCURSOR_INITED(mc) || (mc)->mc_ki[top] >= NUMKEYS(xr_pg)) break; \
1241 xr_node = NODEPTR(xr_pg, (mc)->mc_ki[top]); \
1242 if ((xr_node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) \
1243 (mc)->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(xr_node); \
1246 /** State of FreeDB old pages, stored in the MDB_env */
1247 typedef struct MDB_pgstate {
1248 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1249 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1252 /** The database environment. */
1254 HANDLE me_fd; /**< The main data file */
1255 HANDLE me_lfd; /**< The lock file */
1256 HANDLE me_mfd; /**< For writing and syncing the meta pages */
1257 /** Failed to update the meta page. Probably an I/O error. */
1258 #define MDB_FATAL_ERROR 0x80000000U
1259 /** Some fields are initialized. */
1260 #define MDB_ENV_ACTIVE 0x20000000U
1261 /** me_txkey is set */
1262 #define MDB_ENV_TXKEY 0x10000000U
1263 /** fdatasync is unreliable */
1264 #define MDB_FSYNCONLY 0x08000000U
1265 uint32_t me_flags; /**< @ref mdb_env */
1266 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1267 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1268 unsigned int me_maxreaders; /**< size of the reader table */
1269 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1270 volatile int me_close_readers;
1271 MDB_dbi me_numdbs; /**< number of DBs opened */
1272 MDB_dbi me_maxdbs; /**< size of the DB table */
1273 MDB_PID_T me_pid; /**< process ID of this env */
1274 char *me_path; /**< path to the DB files */
1275 char *me_map; /**< the memory map of the data file */
1276 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1277 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1278 void *me_pbuf; /**< scratch area for DUPSORT put() */
1279 MDB_txn *me_txn; /**< current write transaction */
1280 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1281 size_t me_mapsize; /**< size of the data memory map */
1282 off_t me_size; /**< current file size */
1283 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1284 MDB_dbx *me_dbxs; /**< array of static DB info */
1285 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1286 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1287 pthread_key_t me_txkey; /**< thread-key for readers */
1288 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1289 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1290 # define me_pglast me_pgstate.mf_pglast
1291 # define me_pghead me_pgstate.mf_pghead
1292 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1293 /** IDL of pages that became unused in a write txn */
1294 MDB_IDL me_free_pgs;
1295 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1296 MDB_ID2L me_dirty_list;
1297 /** Max number of freelist items that can fit in a single overflow page */
1299 /** Max size of a node on a page */
1300 unsigned int me_nodemax;
1301 #if !(MDB_MAXKEYSIZE)
1302 unsigned int me_maxkey; /**< max size of a key */
1304 int me_live_reader; /**< have liveness lock in reader table */
1306 int me_pidquery; /**< Used in OpenProcess */
1308 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1309 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1310 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1312 mdb_mutex_t me_rmutex;
1313 mdb_mutex_t me_wmutex;
1315 void *me_userctx; /**< User-settable context */
1316 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1319 /** Nested transaction */
1320 typedef struct MDB_ntxn {
1321 MDB_txn mnt_txn; /**< the transaction */
1322 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1325 /** max number of pages to commit in one writev() call */
1326 #define MDB_COMMIT_PAGES 64
1327 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1328 #undef MDB_COMMIT_PAGES
1329 #define MDB_COMMIT_PAGES IOV_MAX
1332 /** max bytes to write in one call */
1333 #define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
1335 /** Check \b txn and \b dbi arguments to a function */
1336 #define TXN_DBI_EXIST(txn, dbi, validity) \
1337 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1339 /** Check for misused \b dbi handles */
1340 #define TXN_DBI_CHANGED(txn, dbi) \
1341 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1343 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1344 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1345 static int mdb_page_touch(MDB_cursor *mc);
1347 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1348 "reset-tmp", "fail-begin", "fail-beginchild"}
1350 /* mdb_txn_end operation number, for logging */
1351 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1352 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1354 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1355 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1356 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1357 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1358 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1360 static int mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
1361 static int mdb_page_search_root(MDB_cursor *mc,
1362 MDB_val *key, int modify);
1363 #define MDB_PS_MODIFY 1
1364 #define MDB_PS_ROOTONLY 2
1365 #define MDB_PS_FIRST 4
1366 #define MDB_PS_LAST 8
1367 static int mdb_page_search(MDB_cursor *mc,
1368 MDB_val *key, int flags);
1369 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1371 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1372 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1373 pgno_t newpgno, unsigned int nflags);
1375 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1376 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1377 static int mdb_env_write_meta(MDB_txn *txn);
1378 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1379 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1381 static void mdb_env_close0(MDB_env *env, int excl);
1383 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1384 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1385 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1386 static void mdb_node_del(MDB_cursor *mc, int ksize);
1387 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1388 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1389 static int mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
1390 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1391 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1393 static int mdb_rebalance(MDB_cursor *mc);
1394 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1396 static void mdb_cursor_pop(MDB_cursor *mc);
1397 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1399 static int mdb_cursor_del0(MDB_cursor *mc);
1400 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1401 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1402 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1403 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1404 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1406 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1407 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1409 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1410 static void mdb_xcursor_init0(MDB_cursor *mc);
1411 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1412 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1414 static int mdb_drop0(MDB_cursor *mc, int subs);
1415 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1416 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1419 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1422 /** Compare two items pointing at size_t's of unknown alignment. */
1423 #ifdef MISALIGNED_OK
1424 # define mdb_cmp_clong mdb_cmp_long
1426 # define mdb_cmp_clong mdb_cmp_cint
1430 static SECURITY_DESCRIPTOR mdb_null_sd;
1431 static SECURITY_ATTRIBUTES mdb_all_sa;
1432 static int mdb_sec_inited;
1435 static int utf8_to_utf16(const char *src, struct MDB_name *dst, int xtra);
1438 /** Return the library version info. */
1440 mdb_version(int *major, int *minor, int *patch)
1442 if (major) *major = MDB_VERSION_MAJOR;
1443 if (minor) *minor = MDB_VERSION_MINOR;
1444 if (patch) *patch = MDB_VERSION_PATCH;
1445 return MDB_VERSION_STRING;
1448 /** Table of descriptions for LMDB @ref errors */
1449 static char *const mdb_errstr[] = {
1450 "MDB_KEYEXIST: Key/data pair already exists",
1451 "MDB_NOTFOUND: No matching key/data pair found",
1452 "MDB_PAGE_NOTFOUND: Requested page not found",
1453 "MDB_CORRUPTED: Located page was wrong type",
1454 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1455 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1456 "MDB_INVALID: File is not an LMDB file",
1457 "MDB_MAP_FULL: Environment mapsize limit reached",
1458 "MDB_DBS_FULL: Environment maxdbs limit reached",
1459 "MDB_READERS_FULL: Environment maxreaders limit reached",
1460 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1461 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1462 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1463 "MDB_PAGE_FULL: Internal error - page has no more space",
1464 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1465 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1466 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1467 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1468 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1469 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1473 mdb_strerror(int err)
1476 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1477 * This works as long as no function between the call to mdb_strerror
1478 * and the actual use of the message uses more than 4K of stack.
1480 #define MSGSIZE 1024
1481 #define PADSIZE 4096
1482 char buf[MSGSIZE+PADSIZE], *ptr = buf;
1486 return ("Successful return: 0");
1488 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1489 i = err - MDB_KEYEXIST;
1490 return mdb_errstr[i];
1494 /* These are the C-runtime error codes we use. The comment indicates
1495 * their numeric value, and the Win32 error they would correspond to
1496 * if the error actually came from a Win32 API. A major mess, we should
1497 * have used LMDB-specific error codes for everything.
1500 case ENOENT: /* 2, FILE_NOT_FOUND */
1501 case EIO: /* 5, ACCESS_DENIED */
1502 case ENOMEM: /* 12, INVALID_ACCESS */
1503 case EACCES: /* 13, INVALID_DATA */
1504 case EBUSY: /* 16, CURRENT_DIRECTORY */
1505 case EINVAL: /* 22, BAD_COMMAND */
1506 case ENOSPC: /* 28, OUT_OF_PAPER */
1507 return strerror(err);
1512 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1513 FORMAT_MESSAGE_IGNORE_INSERTS,
1514 NULL, err, 0, ptr, MSGSIZE, (va_list *)buf+MSGSIZE);
1517 return strerror(err);
1521 /** assert(3) variant in cursor context */
1522 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1523 /** assert(3) variant in transaction context */
1524 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1525 /** assert(3) variant in environment context */
1526 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1529 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1530 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1533 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1534 const char *func, const char *file, int line)
1537 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1538 file, line, expr_txt, func);
1539 if (env->me_assert_func)
1540 env->me_assert_func(env, buf);
1541 fprintf(stderr, "%s\n", buf);
1545 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1549 /** Return the page number of \b mp which may be sub-page, for debug output */
1551 mdb_dbg_pgno(MDB_page *mp)
1554 COPY_PGNO(ret, mp->mp_pgno);
1558 /** Display a key in hexadecimal and return the address of the result.
1559 * @param[in] key the key to display
1560 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1561 * @return The key in hexadecimal form.
1564 mdb_dkey(MDB_val *key, char *buf)
1567 unsigned char *c = key->mv_data;
1573 if (key->mv_size > DKBUF_MAXKEYSIZE)
1574 return "MDB_MAXKEYSIZE";
1575 /* may want to make this a dynamic check: if the key is mostly
1576 * printable characters, print it as-is instead of converting to hex.
1580 for (i=0; i<key->mv_size; i++)
1581 ptr += sprintf(ptr, "%02x", *c++);
1583 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1589 mdb_leafnode_type(MDB_node *n)
1591 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1592 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1593 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1596 /** Display all the keys in the page. */
1598 mdb_page_list(MDB_page *mp)
1600 pgno_t pgno = mdb_dbg_pgno(mp);
1601 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1603 unsigned int i, nkeys, nsize, total = 0;
1607 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1608 case P_BRANCH: type = "Branch page"; break;
1609 case P_LEAF: type = "Leaf page"; break;
1610 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1611 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1612 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1614 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1615 pgno, mp->mp_pages, state);
1618 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1619 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1622 fprintf(stderr, "Bad page %"Z"u flags 0x%X\n", pgno, mp->mp_flags);
1626 nkeys = NUMKEYS(mp);
1627 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1629 for (i=0; i<nkeys; i++) {
1630 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1631 key.mv_size = nsize = mp->mp_pad;
1632 key.mv_data = LEAF2KEY(mp, i, nsize);
1634 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1637 node = NODEPTR(mp, i);
1638 key.mv_size = node->mn_ksize;
1639 key.mv_data = node->mn_data;
1640 nsize = NODESIZE + key.mv_size;
1641 if (IS_BRANCH(mp)) {
1642 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1646 if (F_ISSET(node->mn_flags, F_BIGDATA))
1647 nsize += sizeof(pgno_t);
1649 nsize += NODEDSZ(node);
1651 nsize += sizeof(indx_t);
1652 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1653 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1655 total = EVEN(total);
1657 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1658 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1662 mdb_cursor_chk(MDB_cursor *mc)
1668 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1669 for (i=0; i<mc->mc_top; i++) {
1671 node = NODEPTR(mp, mc->mc_ki[i]);
1672 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1675 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1677 if (XCURSOR_INITED(mc)) {
1678 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1679 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1680 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1688 /** Count all the pages in each DB and in the freelist
1689 * and make sure it matches the actual number of pages
1691 * All named DBs must be open for a correct count.
1693 static void mdb_audit(MDB_txn *txn)
1697 MDB_ID freecount, count;
1702 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1703 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1704 freecount += *(MDB_ID *)data.mv_data;
1705 mdb_tassert(txn, rc == MDB_NOTFOUND);
1708 for (i = 0; i<txn->mt_numdbs; i++) {
1710 if (!(txn->mt_dbflags[i] & DB_VALID))
1712 mdb_cursor_init(&mc, txn, i, &mx);
1713 if (txn->mt_dbs[i].md_root == P_INVALID)
1715 count += txn->mt_dbs[i].md_branch_pages +
1716 txn->mt_dbs[i].md_leaf_pages +
1717 txn->mt_dbs[i].md_overflow_pages;
1718 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1719 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1720 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1723 mp = mc.mc_pg[mc.mc_top];
1724 for (j=0; j<NUMKEYS(mp); j++) {
1725 MDB_node *leaf = NODEPTR(mp, j);
1726 if (leaf->mn_flags & F_SUBDATA) {
1728 memcpy(&db, NODEDATA(leaf), sizeof(db));
1729 count += db.md_branch_pages + db.md_leaf_pages +
1730 db.md_overflow_pages;
1734 mdb_tassert(txn, rc == MDB_NOTFOUND);
1737 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1738 fprintf(stderr, "audit: %"Z"u freecount: %"Z"u count: %"Z"u total: %"Z"u next_pgno: %"Z"u\n",
1739 txn->mt_txnid, freecount, count+NUM_METAS,
1740 freecount+count+NUM_METAS, txn->mt_next_pgno);
1746 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1748 return txn->mt_dbxs[dbi].md_cmp(a, b);
1752 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1754 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1755 #if UINT_MAX < SIZE_MAX
1756 if (dcmp == mdb_cmp_int && a->mv_size == sizeof(size_t))
1757 dcmp = mdb_cmp_clong;
1762 /** Allocate memory for a page.
1763 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1764 * Set #MDB_TXN_ERROR on failure.
1767 mdb_page_malloc(MDB_txn *txn, unsigned num)
1769 MDB_env *env = txn->mt_env;
1770 MDB_page *ret = env->me_dpages;
1771 size_t psize = env->me_psize, sz = psize, off;
1772 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1773 * For a single page alloc, we init everything after the page header.
1774 * For multi-page, we init the final page; if the caller needed that
1775 * many pages they will be filling in at least up to the last page.
1779 VGMEMP_ALLOC(env, ret, sz);
1780 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1781 env->me_dpages = ret->mp_next;
1784 psize -= off = PAGEHDRSZ;
1789 if ((ret = malloc(sz)) != NULL) {
1790 VGMEMP_ALLOC(env, ret, sz);
1791 if (!(env->me_flags & MDB_NOMEMINIT)) {
1792 memset((char *)ret + off, 0, psize);
1796 txn->mt_flags |= MDB_TXN_ERROR;
1800 /** Free a single page.
1801 * Saves single pages to a list, for future reuse.
1802 * (This is not used for multi-page overflow pages.)
1805 mdb_page_free(MDB_env *env, MDB_page *mp)
1807 mp->mp_next = env->me_dpages;
1808 VGMEMP_FREE(env, mp);
1809 env->me_dpages = mp;
1812 /** Free a dirty page */
1814 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1816 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1817 mdb_page_free(env, dp);
1819 /* large pages just get freed directly */
1820 VGMEMP_FREE(env, dp);
1825 /** Return all dirty pages to dpage list */
1827 mdb_dlist_free(MDB_txn *txn)
1829 MDB_env *env = txn->mt_env;
1830 MDB_ID2L dl = txn->mt_u.dirty_list;
1831 unsigned i, n = dl[0].mid;
1833 for (i = 1; i <= n; i++) {
1834 mdb_dpage_free(env, dl[i].mptr);
1839 /** Loosen or free a single page.
1840 * Saves single pages to a list for future reuse
1841 * in this same txn. It has been pulled from the freeDB
1842 * and already resides on the dirty list, but has been
1843 * deleted. Use these pages first before pulling again
1846 * If the page wasn't dirtied in this txn, just add it
1847 * to this txn's free list.
1850 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1853 pgno_t pgno = mp->mp_pgno;
1854 MDB_txn *txn = mc->mc_txn;
1856 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1857 if (txn->mt_parent) {
1858 MDB_ID2 *dl = txn->mt_u.dirty_list;
1859 /* If txn has a parent, make sure the page is in our
1863 unsigned x = mdb_mid2l_search(dl, pgno);
1864 if (x <= dl[0].mid && dl[x].mid == pgno) {
1865 if (mp != dl[x].mptr) { /* bad cursor? */
1866 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1867 txn->mt_flags |= MDB_TXN_ERROR;
1868 return MDB_CORRUPTED;
1875 /* no parent txn, so it's just ours */
1880 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1882 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1883 txn->mt_loose_pgs = mp;
1884 txn->mt_loose_count++;
1885 mp->mp_flags |= P_LOOSE;
1887 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1895 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1896 * @param[in] mc A cursor handle for the current operation.
1897 * @param[in] pflags Flags of the pages to update:
1898 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1899 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1900 * @return 0 on success, non-zero on failure.
1903 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1905 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1906 MDB_txn *txn = mc->mc_txn;
1907 MDB_cursor *m3, *m0 = mc;
1912 int rc = MDB_SUCCESS, level;
1914 /* Mark pages seen by cursors */
1915 if (mc->mc_flags & C_UNTRACK)
1916 mc = NULL; /* will find mc in mt_cursors */
1917 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1918 for (; mc; mc=mc->mc_next) {
1919 if (!(mc->mc_flags & C_INITIALIZED))
1921 for (m3 = mc;; m3 = &mx->mx_cursor) {
1923 for (j=0; j<m3->mc_snum; j++) {
1925 if ((mp->mp_flags & Mask) == pflags)
1926 mp->mp_flags ^= P_KEEP;
1928 mx = m3->mc_xcursor;
1929 /* Proceed to mx if it is at a sub-database */
1930 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1932 if (! (mp && (mp->mp_flags & P_LEAF)))
1934 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1935 if (!(leaf->mn_flags & F_SUBDATA))
1944 /* Mark dirty root pages */
1945 for (i=0; i<txn->mt_numdbs; i++) {
1946 if (txn->mt_dbflags[i] & DB_DIRTY) {
1947 pgno_t pgno = txn->mt_dbs[i].md_root;
1948 if (pgno == P_INVALID)
1950 if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
1952 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1953 dp->mp_flags ^= P_KEEP;
1961 static int mdb_page_flush(MDB_txn *txn, int keep);
1963 /** Spill pages from the dirty list back to disk.
1964 * This is intended to prevent running into #MDB_TXN_FULL situations,
1965 * but note that they may still occur in a few cases:
1966 * 1) our estimate of the txn size could be too small. Currently this
1967 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1968 * 2) child txns may run out of space if their parents dirtied a
1969 * lot of pages and never spilled them. TODO: we probably should do
1970 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1971 * the parent's dirty_room is below a given threshold.
1973 * Otherwise, if not using nested txns, it is expected that apps will
1974 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1975 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1976 * If the txn never references them again, they can be left alone.
1977 * If the txn only reads them, they can be used without any fuss.
1978 * If the txn writes them again, they can be dirtied immediately without
1979 * going thru all of the work of #mdb_page_touch(). Such references are
1980 * handled by #mdb_page_unspill().
1982 * Also note, we never spill DB root pages, nor pages of active cursors,
1983 * because we'll need these back again soon anyway. And in nested txns,
1984 * we can't spill a page in a child txn if it was already spilled in a
1985 * parent txn. That would alter the parent txns' data even though
1986 * the child hasn't committed yet, and we'd have no way to undo it if
1987 * the child aborted.
1989 * @param[in] m0 cursor A cursor handle identifying the transaction and
1990 * database for which we are checking space.
1991 * @param[in] key For a put operation, the key being stored.
1992 * @param[in] data For a put operation, the data being stored.
1993 * @return 0 on success, non-zero on failure.
1996 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1998 MDB_txn *txn = m0->mc_txn;
2000 MDB_ID2L dl = txn->mt_u.dirty_list;
2001 unsigned int i, j, need;
2004 if (m0->mc_flags & C_SUB)
2007 /* Estimate how much space this op will take */
2008 i = m0->mc_db->md_depth;
2009 /* Named DBs also dirty the main DB */
2010 if (m0->mc_dbi >= CORE_DBS)
2011 i += txn->mt_dbs[MAIN_DBI].md_depth;
2012 /* For puts, roughly factor in the key+data size */
2014 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
2015 i += i; /* double it for good measure */
2018 if (txn->mt_dirty_room > i)
2021 if (!txn->mt_spill_pgs) {
2022 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
2023 if (!txn->mt_spill_pgs)
2026 /* purge deleted slots */
2027 MDB_IDL sl = txn->mt_spill_pgs;
2028 unsigned int num = sl[0];
2030 for (i=1; i<=num; i++) {
2037 /* Preserve pages which may soon be dirtied again */
2038 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2041 /* Less aggressive spill - we originally spilled the entire dirty list,
2042 * with a few exceptions for cursor pages and DB root pages. But this
2043 * turns out to be a lot of wasted effort because in a large txn many
2044 * of those pages will need to be used again. So now we spill only 1/8th
2045 * of the dirty pages. Testing revealed this to be a good tradeoff,
2046 * better than 1/2, 1/4, or 1/10.
2048 if (need < MDB_IDL_UM_MAX / 8)
2049 need = MDB_IDL_UM_MAX / 8;
2051 /* Save the page IDs of all the pages we're flushing */
2052 /* flush from the tail forward, this saves a lot of shifting later on. */
2053 for (i=dl[0].mid; i && need; i--) {
2054 MDB_ID pn = dl[i].mid << 1;
2056 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2058 /* Can't spill twice, make sure it's not already in a parent's
2061 if (txn->mt_parent) {
2063 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2064 if (tx2->mt_spill_pgs) {
2065 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2066 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2067 dp->mp_flags |= P_KEEP;
2075 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2079 mdb_midl_sort(txn->mt_spill_pgs);
2081 /* Flush the spilled part of dirty list */
2082 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2085 /* Reset any dirty pages we kept that page_flush didn't see */
2086 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2089 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2093 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2095 mdb_find_oldest(MDB_txn *txn)
2098 txnid_t mr, oldest = txn->mt_txnid - 1;
2099 if (txn->mt_env->me_txns) {
2100 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2101 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2112 /** Add a page to the txn's dirty list */
2114 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2117 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2119 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2120 insert = mdb_mid2l_append;
2122 insert = mdb_mid2l_insert;
2124 mid.mid = mp->mp_pgno;
2126 rc = insert(txn->mt_u.dirty_list, &mid);
2127 mdb_tassert(txn, rc == 0);
2128 txn->mt_dirty_room--;
2131 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2132 * me_pghead and mt_next_pgno. Set #MDB_TXN_ERROR on failure.
2134 * If there are free pages available from older transactions, they
2135 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2136 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2137 * and move me_pglast to say which records were consumed. Only this
2138 * function can create me_pghead and move me_pglast/mt_next_pgno.
2139 * @param[in] mc cursor A cursor handle identifying the transaction and
2140 * database for which we are allocating.
2141 * @param[in] num the number of pages to allocate.
2142 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2143 * will always be satisfied by a single contiguous chunk of memory.
2144 * @return 0 on success, non-zero on failure.
2147 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2149 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2150 /* Get at most <Max_retries> more freeDB records once me_pghead
2151 * has enough pages. If not enough, use new pages from the map.
2152 * If <Paranoid> and mc is updating the freeDB, only get new
2153 * records if me_pghead is empty. Then the freelist cannot play
2154 * catch-up with itself by growing while trying to save it.
2156 enum { Paranoid = 1, Max_retries = 500 };
2158 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2160 int rc, retry = num * 60;
2161 MDB_txn *txn = mc->mc_txn;
2162 MDB_env *env = txn->mt_env;
2163 pgno_t pgno, *mop = env->me_pghead;
2164 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2166 txnid_t oldest = 0, last;
2171 /* If there are any loose pages, just use them */
2172 if (num == 1 && txn->mt_loose_pgs) {
2173 np = txn->mt_loose_pgs;
2174 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2175 txn->mt_loose_count--;
2176 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
2184 /* If our dirty list is already full, we can't do anything */
2185 if (txn->mt_dirty_room == 0) {
2190 for (op = MDB_FIRST;; op = MDB_NEXT) {
2195 /* Seek a big enough contiguous page range. Prefer
2196 * pages at the tail, just truncating the list.
2202 if (mop[i-n2] == pgno+n2)
2209 if (op == MDB_FIRST) { /* 1st iteration */
2210 /* Prepare to fetch more and coalesce */
2211 last = env->me_pglast;
2212 oldest = env->me_pgoldest;
2213 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2216 key.mv_data = &last; /* will look up last+1 */
2217 key.mv_size = sizeof(last);
2219 if (Paranoid && mc->mc_dbi == FREE_DBI)
2222 if (Paranoid && retry < 0 && mop_len)
2226 /* Do not fetch more if the record will be too recent */
2227 if (oldest <= last) {
2229 oldest = mdb_find_oldest(txn);
2230 env->me_pgoldest = oldest;
2236 rc = mdb_cursor_get(&m2, &key, NULL, op);
2238 if (rc == MDB_NOTFOUND)
2242 last = *(txnid_t*)key.mv_data;
2243 if (oldest <= last) {
2245 oldest = mdb_find_oldest(txn);
2246 env->me_pgoldest = oldest;
2252 np = m2.mc_pg[m2.mc_top];
2253 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2254 if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
2257 idl = (MDB_ID *) data.mv_data;
2260 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2265 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2267 mop = env->me_pghead;
2269 env->me_pglast = last;
2271 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2272 last, txn->mt_dbs[FREE_DBI].md_root, i));
2274 DPRINTF(("IDL %"Z"u", idl[j]));
2276 /* Merge in descending sorted order */
2277 mdb_midl_xmerge(mop, idl);
2281 /* Use new pages from the map when nothing suitable in the freeDB */
2283 pgno = txn->mt_next_pgno;
2284 if (pgno + num >= env->me_maxpg) {
2285 DPUTS("DB size maxed out");
2291 if (env->me_flags & MDB_WRITEMAP) {
2292 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2294 if (!(np = mdb_page_malloc(txn, num))) {
2300 mop[0] = mop_len -= num;
2301 /* Move any stragglers down */
2302 for (j = i-num; j < mop_len; )
2303 mop[++j] = mop[++i];
2305 txn->mt_next_pgno = pgno + num;
2308 mdb_page_dirty(txn, np);
2314 txn->mt_flags |= MDB_TXN_ERROR;
2318 /** Copy the used portions of a non-overflow page.
2319 * @param[in] dst page to copy into
2320 * @param[in] src page to copy from
2321 * @param[in] psize size of a page
2324 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2326 enum { Align = sizeof(pgno_t) };
2327 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2329 /* If page isn't full, just copy the used portion. Adjust
2330 * alignment so memcpy may copy words instead of bytes.
2332 if ((unused &= -Align) && !IS_LEAF2(src)) {
2333 upper = (upper + PAGEBASE) & -Align;
2334 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2335 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2338 memcpy(dst, src, psize - unused);
2342 /** Pull a page off the txn's spill list, if present.
2343 * If a page being referenced was spilled to disk in this txn, bring
2344 * it back and make it dirty/writable again.
2345 * @param[in] txn the transaction handle.
2346 * @param[in] mp the page being referenced. It must not be dirty.
2347 * @param[out] ret the writable page, if any. ret is unchanged if
2348 * mp wasn't spilled.
2351 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2353 MDB_env *env = txn->mt_env;
2356 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2358 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2359 if (!tx2->mt_spill_pgs)
2361 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2362 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2365 if (txn->mt_dirty_room == 0)
2366 return MDB_TXN_FULL;
2367 if (IS_OVERFLOW(mp))
2371 if (env->me_flags & MDB_WRITEMAP) {
2374 np = mdb_page_malloc(txn, num);
2378 memcpy(np, mp, num * env->me_psize);
2380 mdb_page_copy(np, mp, env->me_psize);
2383 /* If in current txn, this page is no longer spilled.
2384 * If it happens to be the last page, truncate the spill list.
2385 * Otherwise mark it as deleted by setting the LSB.
2387 if (x == txn->mt_spill_pgs[0])
2388 txn->mt_spill_pgs[0]--;
2390 txn->mt_spill_pgs[x] |= 1;
2391 } /* otherwise, if belonging to a parent txn, the
2392 * page remains spilled until child commits
2395 mdb_page_dirty(txn, np);
2396 np->mp_flags |= P_DIRTY;
2404 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2405 * Set #MDB_TXN_ERROR on failure.
2406 * @param[in] mc cursor pointing to the page to be touched
2407 * @return 0 on success, non-zero on failure.
2410 mdb_page_touch(MDB_cursor *mc)
2412 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2413 MDB_txn *txn = mc->mc_txn;
2414 MDB_cursor *m2, *m3;
2418 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2419 if (txn->mt_flags & MDB_TXN_SPILLS) {
2421 rc = mdb_page_unspill(txn, mp, &np);
2427 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2428 (rc = mdb_page_alloc(mc, 1, &np)))
2431 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2432 mp->mp_pgno, pgno));
2433 mdb_cassert(mc, mp->mp_pgno != pgno);
2434 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2435 /* Update the parent page, if any, to point to the new page */
2437 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2438 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2439 SETPGNO(node, pgno);
2441 mc->mc_db->md_root = pgno;
2443 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2444 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2446 /* If txn has a parent, make sure the page is in our
2450 unsigned x = mdb_mid2l_search(dl, pgno);
2451 if (x <= dl[0].mid && dl[x].mid == pgno) {
2452 if (mp != dl[x].mptr) { /* bad cursor? */
2453 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2454 txn->mt_flags |= MDB_TXN_ERROR;
2455 return MDB_CORRUPTED;
2460 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2462 np = mdb_page_malloc(txn, 1);
2467 rc = mdb_mid2l_insert(dl, &mid);
2468 mdb_cassert(mc, rc == 0);
2473 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2475 np->mp_flags |= P_DIRTY;
2478 /* Adjust cursors pointing to mp */
2479 mc->mc_pg[mc->mc_top] = np;
2480 m2 = txn->mt_cursors[mc->mc_dbi];
2481 if (mc->mc_flags & C_SUB) {
2482 for (; m2; m2=m2->mc_next) {
2483 m3 = &m2->mc_xcursor->mx_cursor;
2484 if (m3->mc_snum < mc->mc_snum) continue;
2485 if (m3->mc_pg[mc->mc_top] == mp)
2486 m3->mc_pg[mc->mc_top] = np;
2489 for (; m2; m2=m2->mc_next) {
2490 if (m2->mc_snum < mc->mc_snum) continue;
2491 if (m2 == mc) continue;
2492 if (m2->mc_pg[mc->mc_top] == mp) {
2493 m2->mc_pg[mc->mc_top] = np;
2495 XCURSOR_REFRESH(m2, mc->mc_top, np);
2502 txn->mt_flags |= MDB_TXN_ERROR;
2507 mdb_env_sync(MDB_env *env, int force)
2510 if (env->me_flags & MDB_RDONLY)
2512 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2513 if (env->me_flags & MDB_WRITEMAP) {
2514 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2515 ? MS_ASYNC : MS_SYNC;
2516 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2519 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2523 #ifdef BROKEN_FDATASYNC
2524 if (env->me_flags & MDB_FSYNCONLY) {
2525 if (fsync(env->me_fd))
2529 if (MDB_FDATASYNC(env->me_fd))
2536 /** Back up parent txn's cursors, then grab the originals for tracking */
2538 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2540 MDB_cursor *mc, *bk;
2545 for (i = src->mt_numdbs; --i >= 0; ) {
2546 if ((mc = src->mt_cursors[i]) != NULL) {
2547 size = sizeof(MDB_cursor);
2549 size += sizeof(MDB_xcursor);
2550 for (; mc; mc = bk->mc_next) {
2556 mc->mc_db = &dst->mt_dbs[i];
2557 /* Kill pointers into src to reduce abuse: The
2558 * user may not use mc until dst ends. But we need a valid
2559 * txn pointer here for cursor fixups to keep working.
2562 mc->mc_dbflag = &dst->mt_dbflags[i];
2563 if ((mx = mc->mc_xcursor) != NULL) {
2564 *(MDB_xcursor *)(bk+1) = *mx;
2565 mx->mx_cursor.mc_txn = dst;
2567 mc->mc_next = dst->mt_cursors[i];
2568 dst->mt_cursors[i] = mc;
2575 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2576 * @param[in] txn the transaction handle.
2577 * @param[in] merge true to keep changes to parent cursors, false to revert.
2578 * @return 0 on success, non-zero on failure.
2581 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2583 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2587 for (i = txn->mt_numdbs; --i >= 0; ) {
2588 for (mc = cursors[i]; mc; mc = next) {
2590 if ((bk = mc->mc_backup) != NULL) {
2592 /* Commit changes to parent txn */
2593 mc->mc_next = bk->mc_next;
2594 mc->mc_backup = bk->mc_backup;
2595 mc->mc_txn = bk->mc_txn;
2596 mc->mc_db = bk->mc_db;
2597 mc->mc_dbflag = bk->mc_dbflag;
2598 if ((mx = mc->mc_xcursor) != NULL)
2599 mx->mx_cursor.mc_txn = bk->mc_txn;
2601 /* Abort nested txn */
2603 if ((mx = mc->mc_xcursor) != NULL)
2604 *mx = *(MDB_xcursor *)(bk+1);
2608 /* Only malloced cursors are permanently tracked. */
2615 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2621 Pidset = F_SETLK, Pidcheck = F_GETLK
2625 /** Set or check a pid lock. Set returns 0 on success.
2626 * Check returns 0 if the process is certainly dead, nonzero if it may
2627 * be alive (the lock exists or an error happened so we do not know).
2629 * On Windows Pidset is a no-op, we merely check for the existence
2630 * of the process with the given pid. On POSIX we use a single byte
2631 * lock on the lockfile, set at an offset equal to the pid.
2634 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2636 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2639 if (op == Pidcheck) {
2640 h = OpenProcess(env->me_pidquery, FALSE, pid);
2641 /* No documented "no such process" code, but other program use this: */
2643 return ErrCode() != ERROR_INVALID_PARAMETER;
2644 /* A process exists until all handles to it close. Has it exited? */
2645 ret = WaitForSingleObject(h, 0) != 0;
2652 struct flock lock_info;
2653 memset(&lock_info, 0, sizeof(lock_info));
2654 lock_info.l_type = F_WRLCK;
2655 lock_info.l_whence = SEEK_SET;
2656 lock_info.l_start = pid;
2657 lock_info.l_len = 1;
2658 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2659 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2661 } else if ((rc = ErrCode()) == EINTR) {
2669 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2670 * @param[in] txn the transaction handle to initialize
2671 * @return 0 on success, non-zero on failure.
2674 mdb_txn_renew0(MDB_txn *txn)
2676 MDB_env *env = txn->mt_env;
2677 MDB_txninfo *ti = env->me_txns;
2679 unsigned int i, nr, flags = txn->mt_flags;
2681 int rc, new_notls = 0;
2683 if ((flags &= MDB_TXN_RDONLY) != 0) {
2685 meta = mdb_env_pick_meta(env);
2686 txn->mt_txnid = meta->mm_txnid;
2687 txn->mt_u.reader = NULL;
2689 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2690 pthread_getspecific(env->me_txkey);
2692 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2693 return MDB_BAD_RSLOT;
2695 MDB_PID_T pid = env->me_pid;
2696 MDB_THR_T tid = pthread_self();
2697 mdb_mutexref_t rmutex = env->me_rmutex;
2699 if (!env->me_live_reader) {
2700 rc = mdb_reader_pid(env, Pidset, pid);
2703 env->me_live_reader = 1;
2706 if (LOCK_MUTEX(rc, env, rmutex))
2708 nr = ti->mti_numreaders;
2709 for (i=0; i<nr; i++)
2710 if (ti->mti_readers[i].mr_pid == 0)
2712 if (i == env->me_maxreaders) {
2713 UNLOCK_MUTEX(rmutex);
2714 return MDB_READERS_FULL;
2716 r = &ti->mti_readers[i];
2717 /* Claim the reader slot, carefully since other code
2718 * uses the reader table un-mutexed: First reset the
2719 * slot, next publish it in mti_numreaders. After
2720 * that, it is safe for mdb_env_close() to touch it.
2721 * When it will be closed, we can finally claim it.
2724 r->mr_txnid = (txnid_t)-1;
2727 ti->mti_numreaders = ++nr;
2728 env->me_close_readers = nr;
2730 UNLOCK_MUTEX(rmutex);
2732 new_notls = (env->me_flags & MDB_NOTLS);
2733 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2738 do /* LY: Retry on a race, ITS#7970. */
2739 r->mr_txnid = ti->mti_txnid;
2740 while(r->mr_txnid != ti->mti_txnid);
2741 txn->mt_txnid = r->mr_txnid;
2742 txn->mt_u.reader = r;
2743 meta = env->me_metas[txn->mt_txnid & 1];
2747 /* Not yet touching txn == env->me_txn0, it may be active */
2749 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2751 txn->mt_txnid = ti->mti_txnid;
2752 meta = env->me_metas[txn->mt_txnid & 1];
2754 meta = mdb_env_pick_meta(env);
2755 txn->mt_txnid = meta->mm_txnid;
2759 if (txn->mt_txnid == mdb_debug_start)
2762 txn->mt_child = NULL;
2763 txn->mt_loose_pgs = NULL;
2764 txn->mt_loose_count = 0;
2765 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2766 txn->mt_u.dirty_list = env->me_dirty_list;
2767 txn->mt_u.dirty_list[0].mid = 0;
2768 txn->mt_free_pgs = env->me_free_pgs;
2769 txn->mt_free_pgs[0] = 0;
2770 txn->mt_spill_pgs = NULL;
2772 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2775 /* Copy the DB info and flags */
2776 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
2778 /* Moved to here to avoid a data race in read TXNs */
2779 txn->mt_next_pgno = meta->mm_last_pg+1;
2781 txn->mt_flags = flags;
2784 txn->mt_numdbs = env->me_numdbs;
2785 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
2786 x = env->me_dbflags[i];
2787 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2788 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
2790 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
2791 txn->mt_dbflags[FREE_DBI] = DB_VALID;
2793 if (env->me_flags & MDB_FATAL_ERROR) {
2794 DPUTS("environment had fatal error, must shutdown!");
2796 } else if (env->me_maxpg < txn->mt_next_pgno) {
2797 rc = MDB_MAP_RESIZED;
2801 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
2806 mdb_txn_renew(MDB_txn *txn)
2810 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
2813 rc = mdb_txn_renew0(txn);
2814 if (rc == MDB_SUCCESS) {
2815 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2816 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2817 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2823 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2827 int rc, size, tsize;
2829 flags &= MDB_TXN_BEGIN_FLAGS;
2830 flags |= env->me_flags & MDB_WRITEMAP;
2832 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
2836 /* Nested transactions: Max 1 child, write txns only, no writemap */
2837 flags |= parent->mt_flags;
2838 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
2839 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2841 /* Child txns save MDB_pgstate and use own copy of cursors */
2842 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
2843 size += tsize = sizeof(MDB_ntxn);
2844 } else if (flags & MDB_RDONLY) {
2845 size = env->me_maxdbs * (sizeof(MDB_db)+1);
2846 size += tsize = sizeof(MDB_txn);
2848 /* Reuse preallocated write txn. However, do not touch it until
2849 * mdb_txn_renew0() succeeds, since it currently may be active.
2854 if ((txn = calloc(1, size)) == NULL) {
2855 DPRINTF(("calloc: %s", strerror(errno)));
2858 txn->mt_dbxs = env->me_dbxs; /* static */
2859 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2860 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
2861 txn->mt_flags = flags;
2866 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2867 txn->mt_dbiseqs = parent->mt_dbiseqs;
2868 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2869 if (!txn->mt_u.dirty_list ||
2870 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2872 free(txn->mt_u.dirty_list);
2876 txn->mt_txnid = parent->mt_txnid;
2877 txn->mt_dirty_room = parent->mt_dirty_room;
2878 txn->mt_u.dirty_list[0].mid = 0;
2879 txn->mt_spill_pgs = NULL;
2880 txn->mt_next_pgno = parent->mt_next_pgno;
2881 parent->mt_flags |= MDB_TXN_HAS_CHILD;
2882 parent->mt_child = txn;
2883 txn->mt_parent = parent;
2884 txn->mt_numdbs = parent->mt_numdbs;
2885 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2886 /* Copy parent's mt_dbflags, but clear DB_NEW */
2887 for (i=0; i<txn->mt_numdbs; i++)
2888 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2890 ntxn = (MDB_ntxn *)txn;
2891 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2892 if (env->me_pghead) {
2893 size = MDB_IDL_SIZEOF(env->me_pghead);
2894 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2896 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2901 rc = mdb_cursor_shadow(parent, txn);
2903 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
2904 } else { /* MDB_RDONLY */
2905 txn->mt_dbiseqs = env->me_dbiseqs;
2907 rc = mdb_txn_renew0(txn);
2910 if (txn != env->me_txn0)
2913 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
2915 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2916 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
2917 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2924 mdb_txn_env(MDB_txn *txn)
2926 if(!txn) return NULL;
2931 mdb_txn_id(MDB_txn *txn)
2934 return txn->mt_txnid;
2937 /** Export or close DBI handles opened in this txn. */
2939 mdb_dbis_update(MDB_txn *txn, int keep)
2942 MDB_dbi n = txn->mt_numdbs;
2943 MDB_env *env = txn->mt_env;
2944 unsigned char *tdbflags = txn->mt_dbflags;
2946 for (i = n; --i >= CORE_DBS;) {
2947 if (tdbflags[i] & DB_NEW) {
2949 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2951 char *ptr = env->me_dbxs[i].md_name.mv_data;
2953 env->me_dbxs[i].md_name.mv_data = NULL;
2954 env->me_dbxs[i].md_name.mv_size = 0;
2955 env->me_dbflags[i] = 0;
2956 env->me_dbiseqs[i]++;
2962 if (keep && env->me_numdbs < n)
2966 /** End a transaction, except successful commit of a nested transaction.
2967 * May be called twice for readonly txns: First reset it, then abort.
2968 * @param[in] txn the transaction handle to end
2969 * @param[in] mode why and how to end the transaction
2972 mdb_txn_end(MDB_txn *txn, unsigned mode)
2974 MDB_env *env = txn->mt_env;
2976 static const char *const names[] = MDB_END_NAMES;
2979 /* Export or close DBI handles opened in this txn */
2980 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
2982 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2983 names[mode & MDB_END_OPMASK],
2984 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2985 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2987 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2988 if (txn->mt_u.reader) {
2989 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2990 if (!(env->me_flags & MDB_NOTLS)) {
2991 txn->mt_u.reader = NULL; /* txn does not own reader */
2992 } else if (mode & MDB_END_SLOT) {
2993 txn->mt_u.reader->mr_pid = 0;
2994 txn->mt_u.reader = NULL;
2995 } /* else txn owns the slot until it does MDB_END_SLOT */
2997 txn->mt_numdbs = 0; /* prevent further DBI activity */
2998 txn->mt_flags |= MDB_TXN_FINISHED;
3000 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
3001 pgno_t *pghead = env->me_pghead;
3003 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
3004 mdb_cursors_close(txn, 0);
3005 if (!(env->me_flags & MDB_WRITEMAP)) {
3006 mdb_dlist_free(txn);
3010 txn->mt_flags = MDB_TXN_FINISHED;
3012 if (!txn->mt_parent) {
3013 mdb_midl_shrink(&txn->mt_free_pgs);
3014 env->me_free_pgs = txn->mt_free_pgs;
3016 env->me_pghead = NULL;
3020 mode = 0; /* txn == env->me_txn0, do not free() it */
3022 /* The writer mutex was locked in mdb_txn_begin. */
3024 UNLOCK_MUTEX(env->me_wmutex);
3026 txn->mt_parent->mt_child = NULL;
3027 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
3028 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
3029 mdb_midl_free(txn->mt_free_pgs);
3030 mdb_midl_free(txn->mt_spill_pgs);
3031 free(txn->mt_u.dirty_list);
3034 mdb_midl_free(pghead);
3037 if (mode & MDB_END_FREE)
3042 mdb_txn_reset(MDB_txn *txn)
3047 /* This call is only valid for read-only txns */
3048 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3051 mdb_txn_end(txn, MDB_END_RESET);
3055 mdb_txn_abort(MDB_txn *txn)
3061 mdb_txn_abort(txn->mt_child);
3063 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3066 /** Save the freelist as of this transaction to the freeDB.
3067 * This changes the freelist. Keep trying until it stabilizes.
3070 mdb_freelist_save(MDB_txn *txn)
3072 /* env->me_pghead[] can grow and shrink during this call.
3073 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3074 * Page numbers cannot disappear from txn->mt_free_pgs[].
3077 MDB_env *env = txn->mt_env;
3078 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3079 txnid_t pglast = 0, head_id = 0;
3080 pgno_t freecnt = 0, *free_pgs, *mop;
3081 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3083 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3085 if (env->me_pghead) {
3086 /* Make sure first page of freeDB is touched and on freelist */
3087 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3088 if (rc && rc != MDB_NOTFOUND)
3092 if (!env->me_pghead && txn->mt_loose_pgs) {
3093 /* Put loose page numbers in mt_free_pgs, since
3094 * we may be unable to return them to me_pghead.
3096 MDB_page *mp = txn->mt_loose_pgs;
3097 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3099 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3100 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3101 txn->mt_loose_pgs = NULL;
3102 txn->mt_loose_count = 0;
3105 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3106 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3107 ? SSIZE_MAX : maxfree_1pg;
3110 /* Come back here after each Put() in case freelist changed */
3115 /* If using records from freeDB which we have not yet
3116 * deleted, delete them and any we reserved for me_pghead.
3118 while (pglast < env->me_pglast) {
3119 rc = mdb_cursor_first(&mc, &key, NULL);
3122 pglast = head_id = *(txnid_t *)key.mv_data;
3123 total_room = head_room = 0;
3124 mdb_tassert(txn, pglast <= env->me_pglast);
3125 rc = mdb_cursor_del(&mc, 0);
3130 /* Save the IDL of pages freed by this txn, to a single record */
3131 if (freecnt < txn->mt_free_pgs[0]) {
3133 /* Make sure last page of freeDB is touched and on freelist */
3134 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3135 if (rc && rc != MDB_NOTFOUND)
3138 free_pgs = txn->mt_free_pgs;
3139 /* Write to last page of freeDB */
3140 key.mv_size = sizeof(txn->mt_txnid);
3141 key.mv_data = &txn->mt_txnid;
3143 freecnt = free_pgs[0];
3144 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3145 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3148 /* Retry if mt_free_pgs[] grew during the Put() */
3149 free_pgs = txn->mt_free_pgs;
3150 } while (freecnt < free_pgs[0]);
3151 mdb_midl_sort(free_pgs);
3152 memcpy(data.mv_data, free_pgs, data.mv_size);
3155 unsigned int i = free_pgs[0];
3156 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
3157 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3159 DPRINTF(("IDL %"Z"u", free_pgs[i]));
3165 mop = env->me_pghead;
3166 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3168 /* Reserve records for me_pghead[]. Split it if multi-page,
3169 * to avoid searching freeDB for a page range. Use keys in
3170 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3172 if (total_room >= mop_len) {
3173 if (total_room == mop_len || --more < 0)
3175 } else if (head_room >= maxfree_1pg && head_id > 1) {
3176 /* Keep current record (overflow page), add a new one */
3180 /* (Re)write {key = head_id, IDL length = head_room} */
3181 total_room -= head_room;
3182 head_room = mop_len - total_room;
3183 if (head_room > maxfree_1pg && head_id > 1) {
3184 /* Overflow multi-page for part of me_pghead */
3185 head_room /= head_id; /* amortize page sizes */
3186 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3187 } else if (head_room < 0) {
3188 /* Rare case, not bothering to delete this record */
3191 key.mv_size = sizeof(head_id);
3192 key.mv_data = &head_id;
3193 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3194 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3197 /* IDL is initially empty, zero out at least the length */
3198 pgs = (pgno_t *)data.mv_data;
3199 j = head_room > clean_limit ? head_room : 0;
3203 total_room += head_room;
3206 /* Return loose page numbers to me_pghead, though usually none are
3207 * left at this point. The pages themselves remain in dirty_list.
3209 if (txn->mt_loose_pgs) {
3210 MDB_page *mp = txn->mt_loose_pgs;
3211 unsigned count = txn->mt_loose_count;
3213 /* Room for loose pages + temp IDL with same */
3214 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3216 mop = env->me_pghead;
3217 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3218 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3219 loose[ ++count ] = mp->mp_pgno;
3221 mdb_midl_sort(loose);
3222 mdb_midl_xmerge(mop, loose);
3223 txn->mt_loose_pgs = NULL;
3224 txn->mt_loose_count = 0;
3228 /* Fill in the reserved me_pghead records */
3234 rc = mdb_cursor_first(&mc, &key, &data);
3235 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3236 txnid_t id = *(txnid_t *)key.mv_data;
3237 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3240 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3242 if (len > mop_len) {
3244 data.mv_size = (len + 1) * sizeof(MDB_ID);
3246 data.mv_data = mop -= len;
3249 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3251 if (rc || !(mop_len -= len))
3258 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3259 * @param[in] txn the transaction that's being committed
3260 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3261 * @return 0 on success, non-zero on failure.
3264 mdb_page_flush(MDB_txn *txn, int keep)
3266 MDB_env *env = txn->mt_env;
3267 MDB_ID2L dl = txn->mt_u.dirty_list;
3268 unsigned psize = env->me_psize, j;
3269 int i, pagecount = dl[0].mid, rc;
3270 size_t size = 0, pos = 0;
3272 MDB_page *dp = NULL;
3276 struct iovec iov[MDB_COMMIT_PAGES];
3277 ssize_t wpos = 0, wsize = 0, wres;
3278 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3284 if (env->me_flags & MDB_WRITEMAP) {
3285 /* Clear dirty flags */
3286 while (++i <= pagecount) {
3288 /* Don't flush this page yet */
3289 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3290 dp->mp_flags &= ~P_KEEP;
3294 dp->mp_flags &= ~P_DIRTY;
3299 /* Write the pages */
3301 if (++i <= pagecount) {
3303 /* Don't flush this page yet */
3304 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3305 dp->mp_flags &= ~P_KEEP;
3310 /* clear dirty flag */
3311 dp->mp_flags &= ~P_DIRTY;
3314 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3319 /* Windows actually supports scatter/gather I/O, but only on
3320 * unbuffered file handles. Since we're relying on the OS page
3321 * cache for all our data, that's self-defeating. So we just
3322 * write pages one at a time. We use the ov structure to set
3323 * the write offset, to at least save the overhead of a Seek
3326 DPRINTF(("committing page %"Z"u", pgno));
3327 memset(&ov, 0, sizeof(ov));
3328 ov.Offset = pos & 0xffffffff;
3329 ov.OffsetHigh = pos >> 16 >> 16;
3330 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3332 DPRINTF(("WriteFile: %d", rc));
3336 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3337 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3340 /* Write previous page(s) */
3341 #ifdef MDB_USE_PWRITEV
3342 wres = pwritev(env->me_fd, iov, n, wpos);
3345 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3348 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3352 DPRINTF(("lseek: %s", strerror(rc)));
3355 wres = writev(env->me_fd, iov, n);
3358 if (wres != wsize) {
3363 DPRINTF(("Write error: %s", strerror(rc)));
3365 rc = EIO; /* TODO: Use which error code? */
3366 DPUTS("short write, filesystem full?");
3377 DPRINTF(("committing page %"Z"u", pgno));
3378 next_pos = pos + size;
3379 iov[n].iov_len = size;
3380 iov[n].iov_base = (char *)dp;
3386 /* MIPS has cache coherency issues, this is a no-op everywhere else
3387 * Note: for any size >= on-chip cache size, entire on-chip cache is
3390 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3392 for (i = keep; ++i <= pagecount; ) {
3394 /* This is a page we skipped above */
3397 dl[j].mid = dp->mp_pgno;
3400 mdb_dpage_free(env, dp);
3405 txn->mt_dirty_room += i - j;
3411 mdb_txn_commit(MDB_txn *txn)
3414 unsigned int i, end_mode;
3420 /* mdb_txn_end() mode for a commit which writes nothing */
3421 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3423 if (txn->mt_child) {
3424 rc = mdb_txn_commit(txn->mt_child);
3431 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3435 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3436 DPUTS("txn has failed/finished, can't commit");
3438 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3443 if (txn->mt_parent) {
3444 MDB_txn *parent = txn->mt_parent;
3448 unsigned x, y, len, ps_len;
3450 /* Append our free list to parent's */
3451 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3454 mdb_midl_free(txn->mt_free_pgs);
3455 /* Failures after this must either undo the changes
3456 * to the parent or set MDB_TXN_ERROR in the parent.
3459 parent->mt_next_pgno = txn->mt_next_pgno;
3460 parent->mt_flags = txn->mt_flags;
3462 /* Merge our cursors into parent's and close them */
3463 mdb_cursors_close(txn, 1);
3465 /* Update parent's DB table. */
3466 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3467 parent->mt_numdbs = txn->mt_numdbs;
3468 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3469 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3470 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3471 /* preserve parent's DB_NEW status */
3472 x = parent->mt_dbflags[i] & DB_NEW;
3473 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3476 dst = parent->mt_u.dirty_list;
3477 src = txn->mt_u.dirty_list;
3478 /* Remove anything in our dirty list from parent's spill list */
3479 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3481 pspill[0] = (pgno_t)-1;
3482 /* Mark our dirty pages as deleted in parent spill list */
3483 for (i=0, len=src[0].mid; ++i <= len; ) {
3484 MDB_ID pn = src[i].mid << 1;
3485 while (pn > pspill[x])
3487 if (pn == pspill[x]) {
3492 /* Squash deleted pagenums if we deleted any */
3493 for (x=y; ++x <= ps_len; )
3494 if (!(pspill[x] & 1))
3495 pspill[++y] = pspill[x];
3499 /* Remove anything in our spill list from parent's dirty list */
3500 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3501 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3502 MDB_ID pn = txn->mt_spill_pgs[i];
3504 continue; /* deleted spillpg */
3506 y = mdb_mid2l_search(dst, pn);
3507 if (y <= dst[0].mid && dst[y].mid == pn) {
3509 while (y < dst[0].mid) {
3518 /* Find len = length of merging our dirty list with parent's */
3520 dst[0].mid = 0; /* simplify loops */
3521 if (parent->mt_parent) {
3522 len = x + src[0].mid;
3523 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3524 for (i = x; y && i; y--) {
3525 pgno_t yp = src[y].mid;
3526 while (yp < dst[i].mid)
3528 if (yp == dst[i].mid) {
3533 } else { /* Simplify the above for single-ancestor case */
3534 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3536 /* Merge our dirty list with parent's */
3538 for (i = len; y; dst[i--] = src[y--]) {
3539 pgno_t yp = src[y].mid;
3540 while (yp < dst[x].mid)
3541 dst[i--] = dst[x--];
3542 if (yp == dst[x].mid)
3543 free(dst[x--].mptr);
3545 mdb_tassert(txn, i == x);
3547 free(txn->mt_u.dirty_list);
3548 parent->mt_dirty_room = txn->mt_dirty_room;
3549 if (txn->mt_spill_pgs) {
3550 if (parent->mt_spill_pgs) {
3551 /* TODO: Prevent failure here, so parent does not fail */
3552 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3554 parent->mt_flags |= MDB_TXN_ERROR;
3555 mdb_midl_free(txn->mt_spill_pgs);
3556 mdb_midl_sort(parent->mt_spill_pgs);
3558 parent->mt_spill_pgs = txn->mt_spill_pgs;
3562 /* Append our loose page list to parent's */
3563 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3565 *lp = txn->mt_loose_pgs;
3566 parent->mt_loose_count += txn->mt_loose_count;
3568 parent->mt_child = NULL;
3569 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3574 if (txn != env->me_txn) {
3575 DPUTS("attempt to commit unknown transaction");
3580 mdb_cursors_close(txn, 0);
3582 if (!txn->mt_u.dirty_list[0].mid &&
3583 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3586 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3587 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3589 /* Update DB root pointers */
3590 if (txn->mt_numdbs > CORE_DBS) {
3594 data.mv_size = sizeof(MDB_db);
3596 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3597 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3598 if (txn->mt_dbflags[i] & DB_DIRTY) {
3599 if (TXN_DBI_CHANGED(txn, i)) {
3603 data.mv_data = &txn->mt_dbs[i];
3604 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3612 rc = mdb_freelist_save(txn);
3616 mdb_midl_free(env->me_pghead);
3617 env->me_pghead = NULL;
3618 mdb_midl_shrink(&txn->mt_free_pgs);
3624 if ((rc = mdb_page_flush(txn, 0)) ||
3625 (rc = mdb_env_sync(env, 0)) ||
3626 (rc = mdb_env_write_meta(txn)))
3628 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3631 mdb_txn_end(txn, end_mode);
3639 /** Read the environment parameters of a DB environment before
3640 * mapping it into memory.
3641 * @param[in] env the environment handle
3642 * @param[out] meta address of where to store the meta information
3643 * @return 0 on success, non-zero on failure.
3646 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3652 enum { Size = sizeof(pbuf) };
3654 /* We don't know the page size yet, so use a minimum value.
3655 * Read both meta pages so we can use the latest one.
3658 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3662 memset(&ov, 0, sizeof(ov));
3664 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3665 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3668 rc = pread(env->me_fd, &pbuf, Size, off);
3671 if (rc == 0 && off == 0)
3673 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3674 DPRINTF(("read: %s", mdb_strerror(rc)));
3678 p = (MDB_page *)&pbuf;
3680 if (!F_ISSET(p->mp_flags, P_META)) {
3681 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3686 if (m->mm_magic != MDB_MAGIC) {
3687 DPUTS("meta has invalid magic");
3691 if (m->mm_version != MDB_DATA_VERSION) {
3692 DPRINTF(("database is version %u, expected version %u",
3693 m->mm_version, MDB_DATA_VERSION));
3694 return MDB_VERSION_MISMATCH;
3697 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3703 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3705 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3707 meta->mm_magic = MDB_MAGIC;
3708 meta->mm_version = MDB_DATA_VERSION;
3709 meta->mm_mapsize = env->me_mapsize;
3710 meta->mm_psize = env->me_psize;
3711 meta->mm_last_pg = NUM_METAS-1;
3712 meta->mm_flags = env->me_flags & 0xffff;
3713 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3714 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3715 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3718 /** Write the environment parameters of a freshly created DB environment.
3719 * @param[in] env the environment handle
3720 * @param[in] meta the #MDB_meta to write
3721 * @return 0 on success, non-zero on failure.
3724 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3732 memset(&ov, 0, sizeof(ov));
3733 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3735 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3738 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3739 len = pwrite(fd, ptr, size, pos); \
3740 if (len == -1 && ErrCode() == EINTR) continue; \
3741 rc = (len >= 0); break; } while(1)
3744 DPUTS("writing new meta page");
3746 psize = env->me_psize;
3748 p = calloc(NUM_METAS, psize);
3753 p->mp_flags = P_META;
3754 *(MDB_meta *)METADATA(p) = *meta;
3756 q = (MDB_page *)((char *)p + psize);
3758 q->mp_flags = P_META;
3759 *(MDB_meta *)METADATA(q) = *meta;
3761 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
3764 else if ((unsigned) len == psize * NUM_METAS)
3772 /** Update the environment info to commit a transaction.
3773 * @param[in] txn the transaction that's being committed
3774 * @return 0 on success, non-zero on failure.
3777 mdb_env_write_meta(MDB_txn *txn)
3780 MDB_meta meta, metab, *mp;
3784 int rc, len, toggle;
3793 toggle = txn->mt_txnid & 1;
3794 DPRINTF(("writing meta page %d for root page %"Z"u",
3795 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3798 flags = env->me_flags;
3799 mp = env->me_metas[toggle];
3800 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3801 /* Persist any increases of mapsize config */
3802 if (mapsize < env->me_mapsize)
3803 mapsize = env->me_mapsize;
3805 if (flags & MDB_WRITEMAP) {
3806 mp->mm_mapsize = mapsize;
3807 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3808 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3809 mp->mm_last_pg = txn->mt_next_pgno - 1;
3810 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
3811 !(defined(__i386__) || defined(__x86_64__))
3812 /* LY: issue a memory barrier, if not x86. ITS#7969 */
3813 __sync_synchronize();
3815 mp->mm_txnid = txn->mt_txnid;
3816 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3817 unsigned meta_size = env->me_psize;
3818 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3819 ptr = (char *)mp - PAGEHDRSZ;
3820 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3821 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
3825 if (MDB_MSYNC(ptr, meta_size, rc)) {
3832 metab.mm_txnid = mp->mm_txnid;
3833 metab.mm_last_pg = mp->mm_last_pg;
3835 meta.mm_mapsize = mapsize;
3836 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3837 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3838 meta.mm_last_pg = txn->mt_next_pgno - 1;
3839 meta.mm_txnid = txn->mt_txnid;
3841 off = offsetof(MDB_meta, mm_mapsize);
3842 ptr = (char *)&meta + off;
3843 len = sizeof(MDB_meta) - off;
3844 off += (char *)mp - env->me_map;
3846 /* Write to the SYNC fd unless MDB_NOSYNC/MDB_NOMETASYNC.
3847 * (me_mfd goes to the same file as me_fd, but writing to it
3848 * also syncs to disk. Avoids a separate fdatasync() call.)
3850 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
3853 memset(&ov, 0, sizeof(ov));
3855 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3860 rc = pwrite(mfd, ptr, len, off);
3863 rc = rc < 0 ? ErrCode() : EIO;
3868 DPUTS("write failed, disk error?");
3869 /* On a failure, the pagecache still contains the new data.
3870 * Write some old data back, to prevent it from being used.
3871 * Use the non-SYNC fd; we know it will fail anyway.
3873 meta.mm_last_pg = metab.mm_last_pg;
3874 meta.mm_txnid = metab.mm_txnid;
3876 memset(&ov, 0, sizeof(ov));
3878 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3880 r2 = pwrite(env->me_fd, ptr, len, off);
3881 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3884 env->me_flags |= MDB_FATAL_ERROR;
3887 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3888 CACHEFLUSH(env->me_map + off, len, DCACHE);
3890 /* Memory ordering issues are irrelevant; since the entire writer
3891 * is wrapped by wmutex, all of these changes will become visible
3892 * after the wmutex is unlocked. Since the DB is multi-version,
3893 * readers will get consistent data regardless of how fresh or
3894 * how stale their view of these values is.
3897 env->me_txns->mti_txnid = txn->mt_txnid;
3902 /** Check both meta pages to see which one is newer.
3903 * @param[in] env the environment handle
3904 * @return newest #MDB_meta.
3907 mdb_env_pick_meta(const MDB_env *env)
3909 MDB_meta *const *metas = env->me_metas;
3910 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
3914 mdb_env_create(MDB_env **env)
3918 e = calloc(1, sizeof(MDB_env));
3922 e->me_maxreaders = DEFAULT_READERS;
3923 e->me_maxdbs = e->me_numdbs = CORE_DBS;
3924 e->me_fd = INVALID_HANDLE_VALUE;
3925 e->me_lfd = INVALID_HANDLE_VALUE;
3926 e->me_mfd = INVALID_HANDLE_VALUE;
3927 #ifdef MDB_USE_POSIX_SEM
3928 e->me_rmutex = SEM_FAILED;
3929 e->me_wmutex = SEM_FAILED;
3931 e->me_pid = getpid();
3932 GET_PAGESIZE(e->me_os_psize);
3933 VGMEMP_CREATE(e,0,0);
3939 mdb_env_map(MDB_env *env, void *addr)
3942 unsigned int flags = env->me_flags;
3946 LONG sizelo, sizehi;
3949 if (flags & MDB_RDONLY) {
3950 /* Don't set explicit map size, use whatever exists */
3955 msize = env->me_mapsize;
3956 sizelo = msize & 0xffffffff;
3957 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3959 /* Windows won't create mappings for zero length files.
3960 * and won't map more than the file size.
3961 * Just set the maxsize right now.
3963 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3964 || !SetEndOfFile(env->me_fd)
3965 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3969 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3970 PAGE_READWRITE : PAGE_READONLY,
3971 sizehi, sizelo, NULL);
3974 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3975 FILE_MAP_WRITE : FILE_MAP_READ,
3977 rc = env->me_map ? 0 : ErrCode();
3982 int prot = PROT_READ;
3983 if (flags & MDB_WRITEMAP) {
3985 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3988 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3990 if (env->me_map == MAP_FAILED) {
3995 if (flags & MDB_NORDAHEAD) {
3996 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3998 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
4000 #ifdef POSIX_MADV_RANDOM
4001 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
4002 #endif /* POSIX_MADV_RANDOM */
4003 #endif /* MADV_RANDOM */
4007 /* Can happen because the address argument to mmap() is just a
4008 * hint. mmap() can pick another, e.g. if the range is in use.
4009 * The MAP_FIXED flag would prevent that, but then mmap could
4010 * instead unmap existing pages to make room for the new map.
4012 if (addr && env->me_map != addr)
4013 return EBUSY; /* TODO: Make a new MDB_* error code? */
4015 p = (MDB_page *)env->me_map;
4016 env->me_metas[0] = METADATA(p);
4017 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
4023 mdb_env_set_mapsize(MDB_env *env, size_t size)
4025 /* If env is already open, caller is responsible for making
4026 * sure there are no active txns.
4034 meta = mdb_env_pick_meta(env);
4036 size = meta->mm_mapsize;
4038 /* Silently round up to minimum if the size is too small */
4039 size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
4043 munmap(env->me_map, env->me_mapsize);
4044 env->me_mapsize = size;
4045 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4046 rc = mdb_env_map(env, old);
4050 env->me_mapsize = size;
4052 env->me_maxpg = env->me_mapsize / env->me_psize;
4057 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4061 env->me_maxdbs = dbs + CORE_DBS;
4066 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4068 if (env->me_map || readers < 1)
4070 env->me_maxreaders = readers;
4075 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4077 if (!env || !readers)
4079 *readers = env->me_maxreaders;
4084 mdb_fsize(HANDLE fd, size_t *size)
4087 LARGE_INTEGER fsize;
4089 if (!GetFileSizeEx(fd, &fsize))
4092 *size = fsize.QuadPart;
4106 typedef wchar_t mdb_nchar_t;
4107 # define MDB_NAME(str) L##str
4108 # define mdb_name_cpy wcscpy
4110 /** Character type for file names: char on Unix, wchar_t on Windows */
4111 typedef char mdb_nchar_t;
4112 # define MDB_NAME(str) str /**< #mdb_nchar_t[] string literal */
4113 # define mdb_name_cpy strcpy /**< Copy name (#mdb_nchar_t string) */
4116 /** Filename - string of #mdb_nchar_t[] */
4117 typedef struct MDB_name {
4118 int mn_len; /**< Length */
4119 int mn_alloced; /**< True if #mn_val was malloced */
4120 mdb_nchar_t *mn_val; /**< Contents */
4123 /** Filename suffixes [datafile,lockfile][without,with MDB_NOSUBDIR] */
4124 static const mdb_nchar_t *const mdb_suffixes[2][2] = {
4125 { MDB_NAME("/data.mdb"), MDB_NAME("") },
4126 { MDB_NAME("/lock.mdb"), MDB_NAME("-lock") }
4129 #define MDB_SUFFLEN 9 /**< Max string length in #mdb_suffixes[] */
4131 /** Set up filename + scratch area for filename suffix, for opening files.
4132 * It should be freed with #mdb_fname_destroy().
4133 * On Windows, paths are converted from char *UTF-8 to wchar_t *UTF-16.
4135 * @param[in] path Pathname for #mdb_env_open().
4136 * @param[in] envflags Whether a subdir and/or lockfile will be used.
4137 * @param[out] fname Resulting filename, with room for a suffix if necessary.
4140 mdb_fname_init(const char *path, unsigned envflags, MDB_name *fname)
4142 int no_suffix = F_ISSET(envflags, MDB_NOSUBDIR|MDB_NOLOCK);
4143 fname->mn_alloced = 0;
4145 return utf8_to_utf16(path, fname, no_suffix ? 0 : MDB_SUFFLEN);
4147 fname->mn_len = strlen(path);
4149 fname->mn_val = (char *) path;
4150 else if ((fname->mn_val = malloc(fname->mn_len + MDB_SUFFLEN+1)) != NULL) {
4151 fname->mn_alloced = 1;
4152 strcpy(fname->mn_val, path);
4160 /** Destroy \b fname from #mdb_fname_init() */
4161 #define mdb_fname_destroy(fname) \
4162 do { if ((fname).mn_alloced) free((fname).mn_val); } while (0)
4164 #ifdef O_CLOEXEC /* POSIX.1-2008: Set FD_CLOEXEC atomically at open() */
4165 # define MDB_CLOEXEC O_CLOEXEC
4167 # define MDB_CLOEXEC 0
4170 /** File type, access mode etc. for #mdb_fopen() */
4171 enum mdb_fopen_type {
4173 MDB_O_RDONLY, MDB_O_RDWR, MDB_O_META, MDB_O_COPY, MDB_O_LOCKS
4175 /* A comment in mdb_fopen() explains some O_* flag choices. */
4176 MDB_O_RDONLY= O_RDONLY, /**< for RDONLY me_fd */
4177 MDB_O_RDWR = O_RDWR |O_CREAT, /**< for me_fd */
4178 MDB_O_META = O_WRONLY|MDB_DSYNC |MDB_CLOEXEC, /**< for me_mfd */
4179 MDB_O_COPY = O_WRONLY|O_CREAT|O_EXCL|MDB_CLOEXEC, /**< for #mdb_env_copy() */
4180 /** Bitmask for open() flags in enum #mdb_fopen_type. The other bits
4181 * distinguish otherwise-equal MDB_O_* constants from each other.
4183 MDB_O_MASK = MDB_O_RDWR|MDB_CLOEXEC | MDB_O_RDONLY|MDB_O_META|MDB_O_COPY,
4184 MDB_O_LOCKS = MDB_O_RDWR|MDB_CLOEXEC | ((MDB_O_MASK+1) & ~MDB_O_MASK) /**< for me_lfd */
4188 /** Open an LMDB file.
4189 * @param[in] env The LMDB environment.
4190 * @param[in,out] fname Path from from #mdb_fname_init(). A suffix is
4191 * appended if necessary to create the filename, without changing mn_len.
4192 * @param[in] which Determines file type, access mode, etc.
4193 * @param[in] mode The Unix permissions for the file, if we create it.
4194 * @param[out] res Resulting file handle.
4195 * @return 0 on success, non-zero on failure.
4198 mdb_fopen(const MDB_env *env, MDB_name *fname,
4199 enum mdb_fopen_type which, mdb_mode_t mode,
4202 int rc = MDB_SUCCESS;
4205 DWORD acc, share, disp, attrs;
4210 if (fname->mn_alloced) /* modifiable copy */
4211 mdb_name_cpy(fname->mn_val + fname->mn_len,
4212 mdb_suffixes[which==MDB_O_LOCKS][F_ISSET(env->me_flags, MDB_NOSUBDIR)]);
4214 /* The directory must already exist. Usually the file need not.
4215 * MDB_O_META requires the file because we already created it using
4216 * MDB_O_RDWR. MDB_O_COPY must not overwrite an existing file.
4218 * With MDB_O_COPY we do not want the OS to cache the writes, since
4219 * the source data is already in the OS cache.
4221 * The lockfile needs FD_CLOEXEC (close file descriptor on exec*())
4222 * to avoid the flock() issues noted under Caveats in lmdb.h.
4223 * Also set it for other filehandles which the user cannot get at
4224 * and close himself, which he may need after fork(). I.e. all but
4225 * me_fd, which programs do use via mdb_env_get_fd().
4229 acc = GENERIC_READ|GENERIC_WRITE;
4230 share = FILE_SHARE_READ|FILE_SHARE_WRITE;
4232 attrs = FILE_ATTRIBUTE_NORMAL;
4234 case MDB_O_RDONLY: /* read-only datafile */
4236 disp = OPEN_EXISTING;
4238 case MDB_O_META: /* for writing metapages */
4239 acc = GENERIC_WRITE;
4240 disp = OPEN_EXISTING;
4241 attrs = FILE_ATTRIBUTE_NORMAL|FILE_FLAG_WRITE_THROUGH;
4243 case MDB_O_COPY: /* mdb_env_copy() & co */
4244 acc = GENERIC_WRITE;
4247 attrs = FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH;
4249 default: break; /* silence gcc -Wswitch (not all enum values handled) */
4251 fd = CreateFileW(fname->mn_val, acc, share, NULL, disp, attrs, NULL);
4253 fd = open(fname->mn_val, which & MDB_O_MASK, mode);
4256 if (fd == INVALID_HANDLE_VALUE)
4260 if (which != MDB_O_RDONLY && which != MDB_O_RDWR) {
4261 /* Set CLOEXEC if we could not pass it to open() */
4262 if (!MDB_CLOEXEC && (flags = fcntl(fd, F_GETFD)) != -1)
4263 (void) fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
4265 if (which == MDB_O_COPY && env->me_psize >= env->me_os_psize) {
4266 /* This may require buffer alignment. There is no portable
4267 * way to ask how much, so we require OS pagesize alignment.
4269 # ifdef F_NOCACHE /* __APPLE__ */
4270 (void) fcntl(fd, F_NOCACHE, 1);
4271 # elif defined O_DIRECT
4272 /* open(...O_DIRECT...) would break on filesystems without
4273 * O_DIRECT support (ITS#7682). Try to set it here instead.
4275 if ((flags = fcntl(fd, F_GETFL)) != -1)
4276 (void) fcntl(fd, F_SETFL, flags | O_DIRECT);
4280 #endif /* !_WIN32 */
4287 #ifdef BROKEN_FDATASYNC
4288 #include <sys/utsname.h>
4289 #include <sys/vfs.h>
4292 /** Further setup required for opening an LMDB environment
4295 mdb_env_open2(MDB_env *env)
4297 unsigned int flags = env->me_flags;
4298 int i, newenv = 0, rc;
4302 /* See if we should use QueryLimited */
4304 if ((rc & 0xff) > 5)
4305 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4307 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4310 #ifdef BROKEN_FDATASYNC
4311 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4312 * https://lkml.org/lkml/2012/9/3/83
4313 * Kernels after 3.6-rc6 are known good.
4314 * https://lkml.org/lkml/2012/9/10/556
4315 * See if the DB is on ext3/ext4, then check for new enough kernel
4316 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4321 fstatfs(env->me_fd, &st);
4322 while (st.f_type == 0xEF53) {
4326 if (uts.release[0] < '3') {
4327 if (!strncmp(uts.release, "2.6.32.", 7)) {
4328 i = atoi(uts.release+7);
4330 break; /* 2.6.32.60 and newer is OK */
4331 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4332 i = atoi(uts.release+7);
4334 break; /* 2.6.34.15 and newer is OK */
4336 } else if (uts.release[0] == '3') {
4337 i = atoi(uts.release+2);
4339 break; /* 3.6 and newer is OK */
4341 i = atoi(uts.release+4);
4343 break; /* 3.5.4 and newer is OK */
4344 } else if (i == 2) {
4345 i = atoi(uts.release+4);
4347 break; /* 3.2.30 and newer is OK */
4349 } else { /* 4.x and newer is OK */
4352 env->me_flags |= MDB_FSYNCONLY;
4358 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4361 DPUTS("new mdbenv");
4363 env->me_psize = env->me_os_psize;
4364 if (env->me_psize > MAX_PAGESIZE)
4365 env->me_psize = MAX_PAGESIZE;
4366 memset(&meta, 0, sizeof(meta));
4367 mdb_env_init_meta0(env, &meta);
4368 meta.mm_mapsize = DEFAULT_MAPSIZE;
4370 env->me_psize = meta.mm_psize;
4373 /* Was a mapsize configured? */
4374 if (!env->me_mapsize) {
4375 env->me_mapsize = meta.mm_mapsize;
4378 /* Make sure mapsize >= committed data size. Even when using
4379 * mm_mapsize, which could be broken in old files (ITS#7789).
4381 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4382 if (env->me_mapsize < minsize)
4383 env->me_mapsize = minsize;
4385 meta.mm_mapsize = env->me_mapsize;
4387 if (newenv && !(flags & MDB_FIXEDMAP)) {
4388 /* mdb_env_map() may grow the datafile. Write the metapages
4389 * first, so the file will be valid if initialization fails.
4390 * Except with FIXEDMAP, since we do not yet know mm_address.
4391 * We could fill in mm_address later, but then a different
4392 * program might end up doing that - one with a memory layout
4393 * and map address which does not suit the main program.
4395 rc = mdb_env_init_meta(env, &meta);
4401 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4406 if (flags & MDB_FIXEDMAP)
4407 meta.mm_address = env->me_map;
4408 i = mdb_env_init_meta(env, &meta);
4409 if (i != MDB_SUCCESS) {
4414 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4415 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4417 #if !(MDB_MAXKEYSIZE)
4418 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4420 env->me_maxpg = env->me_mapsize / env->me_psize;
4424 MDB_meta *meta = mdb_env_pick_meta(env);
4425 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4427 DPRINTF(("opened database version %u, pagesize %u",
4428 meta->mm_version, env->me_psize));
4429 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4430 DPRINTF(("depth: %u", db->md_depth));
4431 DPRINTF(("entries: %"Z"u", db->md_entries));
4432 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
4433 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
4434 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
4435 DPRINTF(("root: %"Z"u", db->md_root));
4443 /** Release a reader thread's slot in the reader lock table.
4444 * This function is called automatically when a thread exits.
4445 * @param[in] ptr This points to the slot in the reader lock table.
4448 mdb_env_reader_dest(void *ptr)
4450 MDB_reader *reader = ptr;
4453 if (reader->mr_pid == getpid()) /* catch pthread_exit() in child process */
4455 /* We omit the mutex, so do this atomically (i.e. skip mr_txnid) */
4460 /** Junk for arranging thread-specific callbacks on Windows. This is
4461 * necessarily platform and compiler-specific. Windows supports up
4462 * to 1088 keys. Let's assume nobody opens more than 64 environments
4463 * in a single process, for now. They can override this if needed.
4465 #ifndef MAX_TLS_KEYS
4466 #define MAX_TLS_KEYS 64
4468 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4469 static int mdb_tls_nkeys;
4471 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4475 case DLL_PROCESS_ATTACH: break;
4476 case DLL_THREAD_ATTACH: break;
4477 case DLL_THREAD_DETACH:
4478 for (i=0; i<mdb_tls_nkeys; i++) {
4479 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4481 mdb_env_reader_dest(r);
4485 case DLL_PROCESS_DETACH: break;
4490 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4492 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4496 /* Force some symbol references.
4497 * _tls_used forces the linker to create the TLS directory if not already done
4498 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4500 #pragma comment(linker, "/INCLUDE:_tls_used")
4501 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4502 #pragma const_seg(".CRT$XLB")
4503 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4504 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4507 #pragma comment(linker, "/INCLUDE:__tls_used")
4508 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4509 #pragma data_seg(".CRT$XLB")
4510 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4512 #endif /* WIN 32/64 */
4513 #endif /* !__GNUC__ */
4516 /** Downgrade the exclusive lock on the region back to shared */
4518 mdb_env_share_locks(MDB_env *env, int *excl)
4521 MDB_meta *meta = mdb_env_pick_meta(env);
4523 env->me_txns->mti_txnid = meta->mm_txnid;
4528 /* First acquire a shared lock. The Unlock will
4529 * then release the existing exclusive lock.
4531 memset(&ov, 0, sizeof(ov));
4532 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4535 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4541 struct flock lock_info;
4542 /* The shared lock replaces the existing lock */
4543 memset((void *)&lock_info, 0, sizeof(lock_info));
4544 lock_info.l_type = F_RDLCK;
4545 lock_info.l_whence = SEEK_SET;
4546 lock_info.l_start = 0;
4547 lock_info.l_len = 1;
4548 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4549 (rc = ErrCode()) == EINTR) ;
4550 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4557 /** Try to get exclusive lock, otherwise shared.
4558 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4561 mdb_env_excl_lock(MDB_env *env, int *excl)
4565 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4569 memset(&ov, 0, sizeof(ov));
4570 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4577 struct flock lock_info;
4578 memset((void *)&lock_info, 0, sizeof(lock_info));
4579 lock_info.l_type = F_WRLCK;
4580 lock_info.l_whence = SEEK_SET;
4581 lock_info.l_start = 0;
4582 lock_info.l_len = 1;
4583 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4584 (rc = ErrCode()) == EINTR) ;
4588 # ifndef MDB_USE_POSIX_MUTEX
4589 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4592 lock_info.l_type = F_RDLCK;
4593 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4594 (rc = ErrCode()) == EINTR) ;
4604 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4606 * @(#) $Revision: 5.1 $
4607 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4608 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4610 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4614 * Please do not copyright this code. This code is in the public domain.
4616 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4617 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4618 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4619 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4620 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4621 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4622 * PERFORMANCE OF THIS SOFTWARE.
4625 * chongo <Landon Curt Noll> /\oo/\
4626 * http://www.isthe.com/chongo/
4628 * Share and Enjoy! :-)
4631 typedef unsigned long long mdb_hash_t;
4632 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4634 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4635 * @param[in] val value to hash
4636 * @param[in] hval initial value for hash
4637 * @return 64 bit hash
4639 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4640 * hval arg on the first call.
4643 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4645 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4646 unsigned char *end = s + val->mv_size;
4648 * FNV-1a hash each octet of the string
4651 /* xor the bottom with the current octet */
4652 hval ^= (mdb_hash_t)*s++;
4654 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4655 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4656 (hval << 7) + (hval << 8) + (hval << 40);
4658 /* return our new hash value */
4662 /** Hash the string and output the encoded hash.
4663 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4664 * very short name limits. We don't care about the encoding being reversible,
4665 * we just want to preserve as many bits of the input as possible in a
4666 * small printable string.
4667 * @param[in] str string to hash
4668 * @param[out] encbuf an array of 11 chars to hold the hash
4670 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4673 mdb_pack85(unsigned long l, char *out)
4677 for (i=0; i<5; i++) {
4678 *out++ = mdb_a85[l % 85];
4684 mdb_hash_enc(MDB_val *val, char *encbuf)
4686 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4688 mdb_pack85(h, encbuf);
4689 mdb_pack85(h>>32, encbuf+5);
4694 /** Open and/or initialize the lock region for the environment.
4695 * @param[in] env The LMDB environment.
4696 * @param[in] fname Filename + scratch area, from #mdb_fname_init().
4697 * @param[in] mode The Unix permissions for the file, if we create it.
4698 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4699 * @return 0 on success, non-zero on failure.
4702 mdb_env_setup_locks(MDB_env *env, MDB_name *fname, int mode, int *excl)
4705 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4707 # define MDB_ERRCODE_ROFS EROFS
4712 rc = mdb_fopen(env, fname, MDB_O_LOCKS, mode, &env->me_lfd);
4714 /* Omit lockfile if read-only env on read-only filesystem */
4715 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4721 if (!(env->me_flags & MDB_NOTLS)) {
4722 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4725 env->me_flags |= MDB_ENV_TXKEY;
4727 /* Windows TLS callbacks need help finding their TLS info. */
4728 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4732 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4736 /* Try to get exclusive lock. If we succeed, then
4737 * nobody is using the lock region and we should initialize it.
4739 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4742 size = GetFileSize(env->me_lfd, NULL);
4744 size = lseek(env->me_lfd, 0, SEEK_END);
4745 if (size == -1) goto fail_errno;
4747 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4748 if (size < rsize && *excl > 0) {
4750 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4751 || !SetEndOfFile(env->me_lfd))
4754 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4758 size = rsize - sizeof(MDB_txninfo);
4759 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4764 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4766 if (!mh) goto fail_errno;
4767 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4769 if (!env->me_txns) goto fail_errno;
4771 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4773 if (m == MAP_FAILED) goto fail_errno;
4779 BY_HANDLE_FILE_INFORMATION stbuf;
4788 if (!mdb_sec_inited) {
4789 InitializeSecurityDescriptor(&mdb_null_sd,
4790 SECURITY_DESCRIPTOR_REVISION);
4791 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4792 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4793 mdb_all_sa.bInheritHandle = FALSE;
4794 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4797 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4798 idbuf.volume = stbuf.dwVolumeSerialNumber;
4799 idbuf.nhigh = stbuf.nFileIndexHigh;
4800 idbuf.nlow = stbuf.nFileIndexLow;
4801 val.mv_data = &idbuf;
4802 val.mv_size = sizeof(idbuf);
4803 mdb_hash_enc(&val, encbuf);
4804 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4805 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4806 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4807 if (!env->me_rmutex) goto fail_errno;
4808 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4809 if (!env->me_wmutex) goto fail_errno;
4810 #elif defined(MDB_USE_POSIX_SEM)
4819 #if defined(__NetBSD__)
4820 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4822 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4823 idbuf.dev = stbuf.st_dev;
4824 idbuf.ino = stbuf.st_ino;
4825 val.mv_data = &idbuf;
4826 val.mv_size = sizeof(idbuf);
4827 mdb_hash_enc(&val, encbuf);
4828 #ifdef MDB_SHORT_SEMNAMES
4829 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4831 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4832 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4833 /* Clean up after a previous run, if needed: Try to
4834 * remove both semaphores before doing anything else.
4836 sem_unlink(env->me_txns->mti_rmname);
4837 sem_unlink(env->me_txns->mti_wmname);
4838 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4839 O_CREAT|O_EXCL, mode, 1);
4840 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4841 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4842 O_CREAT|O_EXCL, mode, 1);
4843 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4844 #else /* MDB_USE_POSIX_MUTEX: */
4845 pthread_mutexattr_t mattr;
4847 /* Solaris needs this before initing a robust mutex. Otherwise
4848 * it may skip the init and return EBUSY "seems someone already
4849 * inited" or EINVAL "it was inited differently".
4851 memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
4852 memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
4854 if ((rc = pthread_mutexattr_init(&mattr)))
4857 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
4858 #ifdef MDB_ROBUST_SUPPORTED
4859 if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
4861 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
4862 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
4863 pthread_mutexattr_destroy(&mattr);
4866 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4868 env->me_txns->mti_magic = MDB_MAGIC;
4869 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4870 env->me_txns->mti_txnid = 0;
4871 env->me_txns->mti_numreaders = 0;
4874 if (env->me_txns->mti_magic != MDB_MAGIC) {
4875 DPUTS("lock region has invalid magic");
4879 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4880 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4881 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4882 rc = MDB_VERSION_MISMATCH;
4886 if (rc && rc != EACCES && rc != EAGAIN) {
4890 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4891 if (!env->me_rmutex) goto fail_errno;
4892 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4893 if (!env->me_wmutex) goto fail_errno;
4894 #elif defined(MDB_USE_POSIX_SEM)
4895 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4896 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4897 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4898 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4909 /** Only a subset of the @ref mdb_env flags can be changed
4910 * at runtime. Changing other flags requires closing the
4911 * environment and re-opening it with the new flags.
4913 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4914 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
4915 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4917 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4918 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4922 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4927 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4930 flags |= env->me_flags;
4932 rc = mdb_fname_init(path, flags, &fname);
4936 if (flags & MDB_RDONLY) {
4937 /* silently ignore WRITEMAP when we're only getting read access */
4938 flags &= ~MDB_WRITEMAP;
4940 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4941 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4944 env->me_flags = flags |= MDB_ENV_ACTIVE;
4948 env->me_path = strdup(path);
4949 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4950 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4951 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4952 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4956 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
4958 /* For RDONLY, get lockfile after we know datafile exists */
4959 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4960 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
4965 rc = mdb_fopen(env, &fname,
4966 (flags & MDB_RDONLY) ? MDB_O_RDONLY : MDB_O_RDWR,
4971 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4972 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
4977 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4978 if (!(flags & (MDB_RDONLY|MDB_WRITEMAP))) {
4979 /* Synchronous fd for meta writes. Needed even with
4980 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4982 rc = mdb_fopen(env, &fname, MDB_O_META, mode, &env->me_mfd);
4986 DPRINTF(("opened dbenv %p", (void *) env));
4988 rc = mdb_env_share_locks(env, &excl);
4992 if (!(flags & MDB_RDONLY)) {
4994 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
4995 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
4996 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
4997 (txn = calloc(1, size)))
4999 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
5000 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
5001 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
5002 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
5004 txn->mt_dbxs = env->me_dbxs;
5005 txn->mt_flags = MDB_TXN_FINISHED;
5015 mdb_env_close0(env, excl);
5017 mdb_fname_destroy(fname);
5021 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
5023 mdb_env_close0(MDB_env *env, int excl)
5027 if (!(env->me_flags & MDB_ENV_ACTIVE))
5030 /* Doing this here since me_dbxs may not exist during mdb_env_close */
5032 for (i = env->me_maxdbs; --i >= CORE_DBS; )
5033 free(env->me_dbxs[i].md_name.mv_data);
5038 free(env->me_dbiseqs);
5039 free(env->me_dbflags);
5041 free(env->me_dirty_list);
5043 mdb_midl_free(env->me_free_pgs);
5045 if (env->me_flags & MDB_ENV_TXKEY) {
5046 pthread_key_delete(env->me_txkey);
5048 /* Delete our key from the global list */
5049 for (i=0; i<mdb_tls_nkeys; i++)
5050 if (mdb_tls_keys[i] == env->me_txkey) {
5051 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
5059 munmap(env->me_map, env->me_mapsize);
5061 if (env->me_mfd != INVALID_HANDLE_VALUE)
5062 (void) close(env->me_mfd);
5063 if (env->me_fd != INVALID_HANDLE_VALUE)
5064 (void) close(env->me_fd);
5066 MDB_PID_T pid = env->me_pid;
5067 /* Clearing readers is done in this function because
5068 * me_txkey with its destructor must be disabled first.
5070 * We skip the the reader mutex, so we touch only
5071 * data owned by this process (me_close_readers and
5072 * our readers), and clear each reader atomically.
5074 for (i = env->me_close_readers; --i >= 0; )
5075 if (env->me_txns->mti_readers[i].mr_pid == pid)
5076 env->me_txns->mti_readers[i].mr_pid = 0;
5078 if (env->me_rmutex) {
5079 CloseHandle(env->me_rmutex);
5080 if (env->me_wmutex) CloseHandle(env->me_wmutex);
5082 /* Windows automatically destroys the mutexes when
5083 * the last handle closes.
5085 #elif defined(MDB_USE_POSIX_SEM)
5086 if (env->me_rmutex != SEM_FAILED) {
5087 sem_close(env->me_rmutex);
5088 if (env->me_wmutex != SEM_FAILED)
5089 sem_close(env->me_wmutex);
5090 /* If we have the filelock: If we are the
5091 * only remaining user, clean up semaphores.
5094 mdb_env_excl_lock(env, &excl);
5096 sem_unlink(env->me_txns->mti_rmname);
5097 sem_unlink(env->me_txns->mti_wmname);
5101 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
5103 if (env->me_lfd != INVALID_HANDLE_VALUE) {
5106 /* Unlock the lockfile. Windows would have unlocked it
5107 * after closing anyway, but not necessarily at once.
5109 UnlockFile(env->me_lfd, 0, 0, 1, 0);
5112 (void) close(env->me_lfd);
5115 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
5119 mdb_env_close(MDB_env *env)
5126 VGMEMP_DESTROY(env);
5127 while ((dp = env->me_dpages) != NULL) {
5128 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5129 env->me_dpages = dp->mp_next;
5133 mdb_env_close0(env, 0);
5137 /** Compare two items pointing at aligned size_t's */
5139 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5141 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
5142 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
5145 /** Compare two items pointing at aligned unsigned int's.
5147 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5148 * but #mdb_cmp_clong() is called instead if the data type is size_t.
5151 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5153 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5154 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5157 /** Compare two items pointing at unsigned ints of unknown alignment.
5158 * Nodes and keys are guaranteed to be 2-byte aligned.
5161 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5163 #if BYTE_ORDER == LITTLE_ENDIAN
5164 unsigned short *u, *c;
5167 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5168 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5171 } while(!x && u > (unsigned short *)a->mv_data);
5174 unsigned short *u, *c, *end;
5177 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5178 u = (unsigned short *)a->mv_data;
5179 c = (unsigned short *)b->mv_data;
5182 } while(!x && u < end);
5187 /** Compare two items lexically */
5189 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5196 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5202 diff = memcmp(a->mv_data, b->mv_data, len);
5203 return diff ? diff : len_diff<0 ? -1 : len_diff;
5206 /** Compare two items in reverse byte order */
5208 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5210 const unsigned char *p1, *p2, *p1_lim;
5214 p1_lim = (const unsigned char *)a->mv_data;
5215 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5216 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5218 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5224 while (p1 > p1_lim) {
5225 diff = *--p1 - *--p2;
5229 return len_diff<0 ? -1 : len_diff;
5232 /** Search for key within a page, using binary search.
5233 * Returns the smallest entry larger or equal to the key.
5234 * If exactp is non-null, stores whether the found entry was an exact match
5235 * in *exactp (1 or 0).
5236 * Updates the cursor index with the index of the found entry.
5237 * If no entry larger or equal to the key is found, returns NULL.
5240 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5242 unsigned int i = 0, nkeys;
5245 MDB_page *mp = mc->mc_pg[mc->mc_top];
5246 MDB_node *node = NULL;
5251 nkeys = NUMKEYS(mp);
5253 DPRINTF(("searching %u keys in %s %spage %"Z"u",
5254 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5257 low = IS_LEAF(mp) ? 0 : 1;
5259 cmp = mc->mc_dbx->md_cmp;
5261 /* Branch pages have no data, so if using integer keys,
5262 * alignment is guaranteed. Use faster mdb_cmp_int.
5264 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5265 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
5272 nodekey.mv_size = mc->mc_db->md_pad;
5273 node = NODEPTR(mp, 0); /* fake */
5274 while (low <= high) {
5275 i = (low + high) >> 1;
5276 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5277 rc = cmp(key, &nodekey);
5278 DPRINTF(("found leaf index %u [%s], rc = %i",
5279 i, DKEY(&nodekey), rc));
5288 while (low <= high) {
5289 i = (low + high) >> 1;
5291 node = NODEPTR(mp, i);
5292 nodekey.mv_size = NODEKSZ(node);
5293 nodekey.mv_data = NODEKEY(node);
5295 rc = cmp(key, &nodekey);
5298 DPRINTF(("found leaf index %u [%s], rc = %i",
5299 i, DKEY(&nodekey), rc));
5301 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
5302 i, DKEY(&nodekey), NODEPGNO(node), rc));
5313 if (rc > 0) { /* Found entry is less than the key. */
5314 i++; /* Skip to get the smallest entry larger than key. */
5316 node = NODEPTR(mp, i);
5319 *exactp = (rc == 0 && nkeys > 0);
5320 /* store the key index */
5321 mc->mc_ki[mc->mc_top] = i;
5323 /* There is no entry larger or equal to the key. */
5326 /* nodeptr is fake for LEAF2 */
5332 mdb_cursor_adjust(MDB_cursor *mc, func)
5336 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5337 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5344 /** Pop a page off the top of the cursor's stack. */
5346 mdb_cursor_pop(MDB_cursor *mc)
5349 DPRINTF(("popping page %"Z"u off db %d cursor %p",
5350 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5356 mc->mc_flags &= ~C_INITIALIZED;
5361 /** Push a page onto the top of the cursor's stack.
5362 * Set #MDB_TXN_ERROR on failure.
5365 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5367 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
5368 DDBI(mc), (void *) mc));
5370 if (mc->mc_snum >= CURSOR_STACK) {
5371 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5372 return MDB_CURSOR_FULL;
5375 mc->mc_top = mc->mc_snum++;
5376 mc->mc_pg[mc->mc_top] = mp;
5377 mc->mc_ki[mc->mc_top] = 0;
5382 /** Find the address of the page corresponding to a given page number.
5383 * Set #MDB_TXN_ERROR on failure.
5384 * @param[in] mc the cursor accessing the page.
5385 * @param[in] pgno the page number for the page to retrieve.
5386 * @param[out] ret address of a pointer where the page's address will be stored.
5387 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5388 * @return 0 on success, non-zero on failure.
5391 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
5393 MDB_txn *txn = mc->mc_txn;
5394 MDB_env *env = txn->mt_env;
5398 if (! (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_WRITEMAP))) {
5402 MDB_ID2L dl = tx2->mt_u.dirty_list;
5404 /* Spilled pages were dirtied in this txn and flushed
5405 * because the dirty list got full. Bring this page
5406 * back in from the map (but don't unspill it here,
5407 * leave that unless page_touch happens again).
5409 if (tx2->mt_spill_pgs) {
5410 MDB_ID pn = pgno << 1;
5411 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5412 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5413 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5418 unsigned x = mdb_mid2l_search(dl, pgno);
5419 if (x <= dl[0].mid && dl[x].mid == pgno) {
5425 } while ((tx2 = tx2->mt_parent) != NULL);
5428 if (pgno < txn->mt_next_pgno) {
5430 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5432 DPRINTF(("page %"Z"u not found", pgno));
5433 txn->mt_flags |= MDB_TXN_ERROR;
5434 return MDB_PAGE_NOTFOUND;
5444 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
5445 * The cursor is at the root page, set up the rest of it.
5448 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
5450 MDB_page *mp = mc->mc_pg[mc->mc_top];
5454 while (IS_BRANCH(mp)) {
5458 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
5459 /* Don't assert on branch pages in the FreeDB. We can get here
5460 * while in the process of rebalancing a FreeDB branch page; we must
5461 * let that proceed. ITS#8336
5463 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
5464 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
5466 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
5468 if (flags & MDB_PS_LAST) {
5469 i = NUMKEYS(mp) - 1;
5470 /* if already init'd, see if we're already in right place */
5471 if (mc->mc_flags & C_INITIALIZED) {
5472 if (mc->mc_ki[mc->mc_top] == i) {
5473 mc->mc_top = mc->mc_snum++;
5474 mp = mc->mc_pg[mc->mc_top];
5481 node = mdb_node_search(mc, key, &exact);
5483 i = NUMKEYS(mp) - 1;
5485 i = mc->mc_ki[mc->mc_top];
5487 mdb_cassert(mc, i > 0);
5491 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
5494 mdb_cassert(mc, i < NUMKEYS(mp));
5495 node = NODEPTR(mp, i);
5497 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
5500 mc->mc_ki[mc->mc_top] = i;
5501 if ((rc = mdb_cursor_push(mc, mp)))
5505 if (flags & MDB_PS_MODIFY) {
5506 if ((rc = mdb_page_touch(mc)) != 0)
5508 mp = mc->mc_pg[mc->mc_top];
5513 DPRINTF(("internal error, index points to a %02X page!?",
5515 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5516 return MDB_CORRUPTED;
5519 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
5520 key ? DKEY(key) : "null"));
5521 mc->mc_flags |= C_INITIALIZED;
5522 mc->mc_flags &= ~C_EOF;
5527 /** Search for the lowest key under the current branch page.
5528 * This just bypasses a NUMKEYS check in the current page
5529 * before calling mdb_page_search_root(), because the callers
5530 * are all in situations where the current page is known to
5534 mdb_page_search_lowest(MDB_cursor *mc)
5536 MDB_page *mp = mc->mc_pg[mc->mc_top];
5537 MDB_node *node = NODEPTR(mp, 0);
5540 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
5543 mc->mc_ki[mc->mc_top] = 0;
5544 if ((rc = mdb_cursor_push(mc, mp)))
5546 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5549 /** Search for the page a given key should be in.
5550 * Push it and its parent pages on the cursor stack.
5551 * @param[in,out] mc the cursor for this operation.
5552 * @param[in] key the key to search for, or NULL for first/last page.
5553 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5554 * are touched (updated with new page numbers).
5555 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5556 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5557 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5558 * @return 0 on success, non-zero on failure.
5561 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5566 /* Make sure the txn is still viable, then find the root from
5567 * the txn's db table and set it as the root of the cursor's stack.
5569 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
5570 DPUTS("transaction may not be used now");
5573 /* Make sure we're using an up-to-date root */
5574 if (*mc->mc_dbflag & DB_STALE) {
5576 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5578 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5579 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5586 MDB_node *leaf = mdb_node_search(&mc2,
5587 &mc->mc_dbx->md_name, &exact);
5589 return MDB_NOTFOUND;
5590 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
5591 return MDB_INCOMPATIBLE; /* not a named DB */
5592 rc = mdb_node_read(&mc2, leaf, &data);
5595 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5597 /* The txn may not know this DBI, or another process may
5598 * have dropped and recreated the DB with other flags.
5600 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5601 return MDB_INCOMPATIBLE;
5602 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5604 *mc->mc_dbflag &= ~DB_STALE;
5606 root = mc->mc_db->md_root;
5608 if (root == P_INVALID) { /* Tree is empty. */
5609 DPUTS("tree is empty");
5610 return MDB_NOTFOUND;
5614 mdb_cassert(mc, root > 1);
5615 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5616 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
5622 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5623 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5625 if (flags & MDB_PS_MODIFY) {
5626 if ((rc = mdb_page_touch(mc)))
5630 if (flags & MDB_PS_ROOTONLY)
5633 return mdb_page_search_root(mc, key, flags);
5637 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5639 MDB_txn *txn = mc->mc_txn;
5640 pgno_t pg = mp->mp_pgno;
5641 unsigned x = 0, ovpages = mp->mp_pages;
5642 MDB_env *env = txn->mt_env;
5643 MDB_IDL sl = txn->mt_spill_pgs;
5644 MDB_ID pn = pg << 1;
5647 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5648 /* If the page is dirty or on the spill list we just acquired it,
5649 * so we should give it back to our current free list, if any.
5650 * Otherwise put it onto the list of pages we freed in this txn.
5652 * Won't create me_pghead: me_pglast must be inited along with it.
5653 * Unsupported in nested txns: They would need to hide the page
5654 * range in ancestor txns' dirty and spilled lists.
5656 if (env->me_pghead &&
5658 ((mp->mp_flags & P_DIRTY) ||
5659 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5663 MDB_ID2 *dl, ix, iy;
5664 rc = mdb_midl_need(&env->me_pghead, ovpages);
5667 if (!(mp->mp_flags & P_DIRTY)) {
5668 /* This page is no longer spilled */
5675 /* Remove from dirty list */
5676 dl = txn->mt_u.dirty_list;
5678 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5684 mdb_cassert(mc, x > 1);
5686 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5687 txn->mt_flags |= MDB_TXN_ERROR;
5688 return MDB_CORRUPTED;
5691 txn->mt_dirty_room++;
5692 if (!(env->me_flags & MDB_WRITEMAP))
5693 mdb_dpage_free(env, mp);
5695 /* Insert in me_pghead */
5696 mop = env->me_pghead;
5697 j = mop[0] + ovpages;
5698 for (i = mop[0]; i && mop[i] < pg; i--)
5704 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5708 mc->mc_db->md_overflow_pages -= ovpages;
5712 /** Return the data associated with a given node.
5713 * @param[in] mc The cursor for this operation.
5714 * @param[in] leaf The node being read.
5715 * @param[out] data Updated to point to the node's data.
5716 * @return 0 on success, non-zero on failure.
5719 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
5721 MDB_page *omp; /* overflow page */
5725 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5726 data->mv_size = NODEDSZ(leaf);
5727 data->mv_data = NODEDATA(leaf);
5731 /* Read overflow data.
5733 data->mv_size = NODEDSZ(leaf);
5734 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5735 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
5736 DPRINTF(("read overflow page %"Z"u failed", pgno));
5739 data->mv_data = METADATA(omp);
5745 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5746 MDB_val *key, MDB_val *data)
5753 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5755 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
5758 if (txn->mt_flags & MDB_TXN_BLOCKED)
5761 mdb_cursor_init(&mc, txn, dbi, &mx);
5762 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5765 /** Find a sibling for a page.
5766 * Replaces the page at the top of the cursor's stack with the
5767 * specified sibling, if one exists.
5768 * @param[in] mc The cursor for this operation.
5769 * @param[in] move_right Non-zero if the right sibling is requested,
5770 * otherwise the left sibling.
5771 * @return 0 on success, non-zero on failure.
5774 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5780 if (mc->mc_snum < 2) {
5781 return MDB_NOTFOUND; /* root has no siblings */
5785 DPRINTF(("parent page is page %"Z"u, index %u",
5786 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5788 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5789 : (mc->mc_ki[mc->mc_top] == 0)) {
5790 DPRINTF(("no more keys left, moving to %s sibling",
5791 move_right ? "right" : "left"));
5792 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5793 /* undo cursor_pop before returning */
5800 mc->mc_ki[mc->mc_top]++;
5802 mc->mc_ki[mc->mc_top]--;
5803 DPRINTF(("just moving to %s index key %u",
5804 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5806 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5808 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5809 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
5810 /* mc will be inconsistent if caller does mc_snum++ as above */
5811 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5815 mdb_cursor_push(mc, mp);
5817 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5822 /** Move the cursor to the next data item. */
5824 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5830 if ((mc->mc_flags & C_DEL && op == MDB_NEXT_DUP))
5831 return MDB_NOTFOUND;
5833 if (!(mc->mc_flags & C_INITIALIZED))
5834 return mdb_cursor_first(mc, key, data);
5836 mp = mc->mc_pg[mc->mc_top];
5838 if (mc->mc_flags & C_EOF) {
5839 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mp)-1)
5840 return MDB_NOTFOUND;
5841 mc->mc_flags ^= C_EOF;
5844 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5845 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5846 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5847 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5848 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5849 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5850 if (rc == MDB_SUCCESS)
5851 MDB_GET_KEY(leaf, key);
5856 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5857 if (op == MDB_NEXT_DUP)
5858 return MDB_NOTFOUND;
5862 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5863 mdb_dbg_pgno(mp), (void *) mc));
5864 if (mc->mc_flags & C_DEL) {
5865 mc->mc_flags ^= C_DEL;
5869 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5870 DPUTS("=====> move to next sibling page");
5871 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5872 mc->mc_flags |= C_EOF;
5875 mp = mc->mc_pg[mc->mc_top];
5876 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5878 mc->mc_ki[mc->mc_top]++;
5881 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5882 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5885 key->mv_size = mc->mc_db->md_pad;
5886 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5890 mdb_cassert(mc, IS_LEAF(mp));
5891 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5893 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5894 mdb_xcursor_init1(mc, leaf);
5897 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
5900 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5901 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5902 if (rc != MDB_SUCCESS)
5907 MDB_GET_KEY(leaf, key);
5911 /** Move the cursor to the previous data item. */
5913 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5919 if (!(mc->mc_flags & C_INITIALIZED)) {
5920 rc = mdb_cursor_last(mc, key, data);
5923 mc->mc_ki[mc->mc_top]++;
5926 mp = mc->mc_pg[mc->mc_top];
5928 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5929 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5930 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5931 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5932 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5933 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5934 if (rc == MDB_SUCCESS) {
5935 MDB_GET_KEY(leaf, key);
5936 mc->mc_flags &= ~C_EOF;
5942 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5943 if (op == MDB_PREV_DUP)
5944 return MDB_NOTFOUND;
5948 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5949 mdb_dbg_pgno(mp), (void *) mc));
5951 mc->mc_flags &= ~(C_EOF|C_DEL);
5953 if (mc->mc_ki[mc->mc_top] == 0) {
5954 DPUTS("=====> move to prev sibling page");
5955 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5958 mp = mc->mc_pg[mc->mc_top];
5959 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5960 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5962 mc->mc_ki[mc->mc_top]--;
5964 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5965 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5968 key->mv_size = mc->mc_db->md_pad;
5969 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5973 mdb_cassert(mc, IS_LEAF(mp));
5974 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5976 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5977 mdb_xcursor_init1(mc, leaf);
5980 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
5983 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5984 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5985 if (rc != MDB_SUCCESS)
5990 MDB_GET_KEY(leaf, key);
5994 /** Set the cursor on a specific data item. */
5996 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5997 MDB_cursor_op op, int *exactp)
6001 MDB_node *leaf = NULL;
6004 if (key->mv_size == 0)
6005 return MDB_BAD_VALSIZE;
6008 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6010 /* See if we're already on the right page */
6011 if (mc->mc_flags & C_INITIALIZED) {
6014 mp = mc->mc_pg[mc->mc_top];
6016 mc->mc_ki[mc->mc_top] = 0;
6017 return MDB_NOTFOUND;
6019 if (mp->mp_flags & P_LEAF2) {
6020 nodekey.mv_size = mc->mc_db->md_pad;
6021 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
6023 leaf = NODEPTR(mp, 0);
6024 MDB_GET_KEY2(leaf, nodekey);
6026 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6028 /* Probably happens rarely, but first node on the page
6029 * was the one we wanted.
6031 mc->mc_ki[mc->mc_top] = 0;
6038 unsigned int nkeys = NUMKEYS(mp);
6040 if (mp->mp_flags & P_LEAF2) {
6041 nodekey.mv_data = LEAF2KEY(mp,
6042 nkeys-1, nodekey.mv_size);
6044 leaf = NODEPTR(mp, nkeys-1);
6045 MDB_GET_KEY2(leaf, nodekey);
6047 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6049 /* last node was the one we wanted */
6050 mc->mc_ki[mc->mc_top] = nkeys-1;
6056 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
6057 /* This is definitely the right page, skip search_page */
6058 if (mp->mp_flags & P_LEAF2) {
6059 nodekey.mv_data = LEAF2KEY(mp,
6060 mc->mc_ki[mc->mc_top], nodekey.mv_size);
6062 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6063 MDB_GET_KEY2(leaf, nodekey);
6065 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6067 /* current node was the one we wanted */
6074 mc->mc_flags &= ~C_EOF;
6078 /* If any parents have right-sibs, search.
6079 * Otherwise, there's nothing further.
6081 for (i=0; i<mc->mc_top; i++)
6083 NUMKEYS(mc->mc_pg[i])-1)
6085 if (i == mc->mc_top) {
6086 /* There are no other pages */
6087 mc->mc_ki[mc->mc_top] = nkeys;
6088 return MDB_NOTFOUND;
6092 /* There are no other pages */
6093 mc->mc_ki[mc->mc_top] = 0;
6094 if (op == MDB_SET_RANGE && !exactp) {
6098 return MDB_NOTFOUND;
6104 rc = mdb_page_search(mc, key, 0);
6105 if (rc != MDB_SUCCESS)
6108 mp = mc->mc_pg[mc->mc_top];
6109 mdb_cassert(mc, IS_LEAF(mp));
6112 leaf = mdb_node_search(mc, key, exactp);
6113 if (exactp != NULL && !*exactp) {
6114 /* MDB_SET specified and not an exact match. */
6115 return MDB_NOTFOUND;
6119 DPUTS("===> inexact leaf not found, goto sibling");
6120 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6121 mc->mc_flags |= C_EOF;
6122 return rc; /* no entries matched */
6124 mp = mc->mc_pg[mc->mc_top];
6125 mdb_cassert(mc, IS_LEAF(mp));
6126 leaf = NODEPTR(mp, 0);
6130 mc->mc_flags |= C_INITIALIZED;
6131 mc->mc_flags &= ~C_EOF;
6134 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
6135 key->mv_size = mc->mc_db->md_pad;
6136 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6141 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6142 mdb_xcursor_init1(mc, leaf);
6145 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6146 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
6147 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6150 if (op == MDB_GET_BOTH) {
6156 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
6157 if (rc != MDB_SUCCESS)
6160 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
6163 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
6165 dcmp = mc->mc_dbx->md_dcmp;
6166 #if UINT_MAX < SIZE_MAX
6167 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6168 dcmp = mdb_cmp_clong;
6170 rc = dcmp(data, &olddata);
6172 if (op == MDB_GET_BOTH || rc > 0)
6173 return MDB_NOTFOUND;
6180 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6181 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6186 /* The key already matches in all other cases */
6187 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6188 MDB_GET_KEY(leaf, key);
6189 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6194 /** Move the cursor to the first item in the database. */
6196 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6202 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6204 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6205 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6206 if (rc != MDB_SUCCESS)
6209 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6211 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6212 mc->mc_flags |= C_INITIALIZED;
6213 mc->mc_flags &= ~C_EOF;
6215 mc->mc_ki[mc->mc_top] = 0;
6217 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6218 key->mv_size = mc->mc_db->md_pad;
6219 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
6224 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6225 mdb_xcursor_init1(mc, leaf);
6226 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6230 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6234 MDB_GET_KEY(leaf, key);
6238 /** Move the cursor to the last item in the database. */
6240 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6246 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6248 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6249 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
6250 if (rc != MDB_SUCCESS)
6253 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6255 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
6256 mc->mc_flags |= C_INITIALIZED|C_EOF;
6257 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6259 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6260 key->mv_size = mc->mc_db->md_pad;
6261 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
6266 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6267 mdb_xcursor_init1(mc, leaf);
6268 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6272 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6277 MDB_GET_KEY(leaf, key);
6282 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6287 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
6292 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
6296 case MDB_GET_CURRENT:
6297 if (!(mc->mc_flags & C_INITIALIZED)) {
6300 MDB_page *mp = mc->mc_pg[mc->mc_top];
6301 int nkeys = NUMKEYS(mp);
6302 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
6303 mc->mc_ki[mc->mc_top] = nkeys;
6309 key->mv_size = mc->mc_db->md_pad;
6310 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6312 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6313 MDB_GET_KEY(leaf, key);
6315 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6316 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
6318 rc = mdb_node_read(mc, leaf, data);
6325 case MDB_GET_BOTH_RANGE:
6330 if (mc->mc_xcursor == NULL) {
6331 rc = MDB_INCOMPATIBLE;
6341 rc = mdb_cursor_set(mc, key, data, op,
6342 op == MDB_SET_RANGE ? NULL : &exact);
6345 case MDB_GET_MULTIPLE:
6346 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6350 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6351 rc = MDB_INCOMPATIBLE;
6355 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6356 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6359 case MDB_NEXT_MULTIPLE:
6364 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6365 rc = MDB_INCOMPATIBLE;
6368 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6369 if (rc == MDB_SUCCESS) {
6370 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6373 mx = &mc->mc_xcursor->mx_cursor;
6374 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
6376 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
6377 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
6383 case MDB_PREV_MULTIPLE:
6388 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6389 rc = MDB_INCOMPATIBLE;
6392 if (!(mc->mc_flags & C_INITIALIZED))
6393 rc = mdb_cursor_last(mc, key, data);
6396 if (rc == MDB_SUCCESS) {
6397 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
6398 if (mx->mc_flags & C_INITIALIZED) {
6399 rc = mdb_cursor_sibling(mx, 0);
6400 if (rc == MDB_SUCCESS)
6409 case MDB_NEXT_NODUP:
6410 rc = mdb_cursor_next(mc, key, data, op);
6414 case MDB_PREV_NODUP:
6415 rc = mdb_cursor_prev(mc, key, data, op);
6418 rc = mdb_cursor_first(mc, key, data);
6421 mfunc = mdb_cursor_first;
6423 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6427 if (mc->mc_xcursor == NULL) {
6428 rc = MDB_INCOMPATIBLE;
6431 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top])) {
6432 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
6437 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6438 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6439 MDB_GET_KEY(leaf, key);
6440 rc = mdb_node_read(mc, leaf, data);
6444 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6448 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
6451 rc = mdb_cursor_last(mc, key, data);
6454 mfunc = mdb_cursor_last;
6457 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
6462 if (mc->mc_flags & C_DEL)
6463 mc->mc_flags ^= C_DEL;
6468 /** Touch all the pages in the cursor stack. Set mc_top.
6469 * Makes sure all the pages are writable, before attempting a write operation.
6470 * @param[in] mc The cursor to operate on.
6473 mdb_cursor_touch(MDB_cursor *mc)
6475 int rc = MDB_SUCCESS;
6477 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & (DB_DIRTY|DB_DUPDATA))) {
6478 /* Touch DB record of named DB */
6481 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6483 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
6484 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
6487 *mc->mc_dbflag |= DB_DIRTY;
6492 rc = mdb_page_touch(mc);
6493 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
6494 mc->mc_top = mc->mc_snum-1;
6499 /** Do not spill pages to disk if txn is getting full, may fail instead */
6500 #define MDB_NOSPILL 0x8000
6503 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6507 MDB_node *leaf = NULL;
6508 MDB_page *fp, *mp, *sub_root = NULL;
6510 MDB_val xdata, *rdata, dkey, olddata;
6512 int do_sub = 0, insert_key, insert_data;
6513 unsigned int mcount = 0, dcount = 0, nospill;
6516 unsigned int nflags;
6519 if (mc == NULL || key == NULL)
6522 env = mc->mc_txn->mt_env;
6524 /* Check this first so counter will always be zero on any
6527 if (flags & MDB_MULTIPLE) {
6528 dcount = data[1].mv_size;
6529 data[1].mv_size = 0;
6530 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
6531 return MDB_INCOMPATIBLE;
6534 nospill = flags & MDB_NOSPILL;
6535 flags &= ~MDB_NOSPILL;
6537 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6538 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6540 if (key->mv_size-1 >= ENV_MAXKEY(env))
6541 return MDB_BAD_VALSIZE;
6543 #if SIZE_MAX > MAXDATASIZE
6544 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
6545 return MDB_BAD_VALSIZE;
6547 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
6548 return MDB_BAD_VALSIZE;
6551 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
6552 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
6556 if (flags == MDB_CURRENT) {
6557 if (!(mc->mc_flags & C_INITIALIZED))
6560 } else if (mc->mc_db->md_root == P_INVALID) {
6561 /* new database, cursor has nothing to point to */
6564 mc->mc_flags &= ~C_INITIALIZED;
6569 if (flags & MDB_APPEND) {
6571 rc = mdb_cursor_last(mc, &k2, &d2);
6573 rc = mc->mc_dbx->md_cmp(key, &k2);
6576 mc->mc_ki[mc->mc_top]++;
6578 /* new key is <= last key */
6583 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6585 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6586 DPRINTF(("duplicate key [%s]", DKEY(key)));
6588 return MDB_KEYEXIST;
6590 if (rc && rc != MDB_NOTFOUND)
6594 if (mc->mc_flags & C_DEL)
6595 mc->mc_flags ^= C_DEL;
6597 /* Cursor is positioned, check for room in the dirty list */
6599 if (flags & MDB_MULTIPLE) {
6601 xdata.mv_size = data->mv_size * dcount;
6605 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6609 if (rc == MDB_NO_ROOT) {
6611 /* new database, write a root leaf page */
6612 DPUTS("allocating new root leaf page");
6613 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6616 mdb_cursor_push(mc, np);
6617 mc->mc_db->md_root = np->mp_pgno;
6618 mc->mc_db->md_depth++;
6619 *mc->mc_dbflag |= DB_DIRTY;
6620 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6622 np->mp_flags |= P_LEAF2;
6623 mc->mc_flags |= C_INITIALIZED;
6625 /* make sure all cursor pages are writable */
6626 rc2 = mdb_cursor_touch(mc);
6631 insert_key = insert_data = rc;
6633 /* The key does not exist */
6634 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6635 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6636 LEAFSIZE(key, data) > env->me_nodemax)
6638 /* Too big for a node, insert in sub-DB. Set up an empty
6639 * "old sub-page" for prep_subDB to expand to a full page.
6641 fp_flags = P_LEAF|P_DIRTY;
6643 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6644 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6645 olddata.mv_size = PAGEHDRSZ;
6649 /* there's only a key anyway, so this is a no-op */
6650 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6652 unsigned int ksize = mc->mc_db->md_pad;
6653 if (key->mv_size != ksize)
6654 return MDB_BAD_VALSIZE;
6655 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6656 memcpy(ptr, key->mv_data, ksize);
6658 /* if overwriting slot 0 of leaf, need to
6659 * update branch key if there is a parent page
6661 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6662 unsigned short dtop = 1;
6664 /* slot 0 is always an empty key, find real slot */
6665 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6669 if (mc->mc_ki[mc->mc_top])
6670 rc2 = mdb_update_key(mc, key);
6681 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6682 olddata.mv_size = NODEDSZ(leaf);
6683 olddata.mv_data = NODEDATA(leaf);
6686 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6687 /* Prepare (sub-)page/sub-DB to accept the new item,
6688 * if needed. fp: old sub-page or a header faking
6689 * it. mp: new (sub-)page. offset: growth in page
6690 * size. xdata: node data with new page or DB.
6692 unsigned i, offset = 0;
6693 mp = fp = xdata.mv_data = env->me_pbuf;
6694 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6696 /* Was a single item before, must convert now */
6697 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6699 /* Just overwrite the current item */
6700 if (flags == MDB_CURRENT)
6702 dcmp = mc->mc_dbx->md_dcmp;
6703 #if UINT_MAX < SIZE_MAX
6704 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6705 dcmp = mdb_cmp_clong;
6707 /* does data match? */
6708 if (!dcmp(data, &olddata)) {
6709 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
6710 return MDB_KEYEXIST;
6715 /* Back up original data item */
6716 dkey.mv_size = olddata.mv_size;
6717 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6719 /* Make sub-page header for the dup items, with dummy body */
6720 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6721 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6722 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6723 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6724 fp->mp_flags |= P_LEAF2;
6725 fp->mp_pad = data->mv_size;
6726 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6728 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6729 (dkey.mv_size & 1) + (data->mv_size & 1);
6731 fp->mp_upper = xdata.mv_size - PAGEBASE;
6732 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6733 } else if (leaf->mn_flags & F_SUBDATA) {
6734 /* Data is on sub-DB, just store it */
6735 flags |= F_DUPDATA|F_SUBDATA;
6738 /* Data is on sub-page */
6739 fp = olddata.mv_data;
6742 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6743 offset = EVEN(NODESIZE + sizeof(indx_t) +
6747 offset = fp->mp_pad;
6748 if (SIZELEFT(fp) < offset) {
6749 offset *= 4; /* space for 4 more */
6752 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6754 fp->mp_flags |= P_DIRTY;
6755 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6756 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6760 xdata.mv_size = olddata.mv_size + offset;
6763 fp_flags = fp->mp_flags;
6764 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6765 /* Too big for a sub-page, convert to sub-DB */
6766 fp_flags &= ~P_SUBP;
6768 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6769 fp_flags |= P_LEAF2;
6770 dummy.md_pad = fp->mp_pad;
6771 dummy.md_flags = MDB_DUPFIXED;
6772 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6773 dummy.md_flags |= MDB_INTEGERKEY;
6779 dummy.md_branch_pages = 0;
6780 dummy.md_leaf_pages = 1;
6781 dummy.md_overflow_pages = 0;
6782 dummy.md_entries = NUMKEYS(fp);
6783 xdata.mv_size = sizeof(MDB_db);
6784 xdata.mv_data = &dummy;
6785 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6787 offset = env->me_psize - olddata.mv_size;
6788 flags |= F_DUPDATA|F_SUBDATA;
6789 dummy.md_root = mp->mp_pgno;
6793 mp->mp_flags = fp_flags | P_DIRTY;
6794 mp->mp_pad = fp->mp_pad;
6795 mp->mp_lower = fp->mp_lower;
6796 mp->mp_upper = fp->mp_upper + offset;
6797 if (fp_flags & P_LEAF2) {
6798 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6800 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6801 olddata.mv_size - fp->mp_upper - PAGEBASE);
6802 for (i=0; i<NUMKEYS(fp); i++)
6803 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6811 mdb_node_del(mc, 0);
6815 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
6816 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
6817 return MDB_INCOMPATIBLE;
6818 /* overflow page overwrites need special handling */
6819 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6822 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6824 memcpy(&pg, olddata.mv_data, sizeof(pg));
6825 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
6827 ovpages = omp->mp_pages;
6829 /* Is the ov page large enough? */
6830 if (ovpages >= dpages) {
6831 if (!(omp->mp_flags & P_DIRTY) &&
6832 (level || (env->me_flags & MDB_WRITEMAP)))
6834 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6837 level = 0; /* dirty in this txn or clean */
6840 if (omp->mp_flags & P_DIRTY) {
6841 /* yes, overwrite it. Note in this case we don't
6842 * bother to try shrinking the page if the new data
6843 * is smaller than the overflow threshold.
6846 /* It is writable only in a parent txn */
6847 size_t sz = (size_t) env->me_psize * ovpages, off;
6848 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6854 /* Note - this page is already counted in parent's dirty_room */
6855 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6856 mdb_cassert(mc, rc2 == 0);
6857 /* Currently we make the page look as with put() in the
6858 * parent txn, in case the user peeks at MDB_RESERVEd
6859 * or unused parts. Some users treat ovpages specially.
6861 if (!(flags & MDB_RESERVE)) {
6862 /* Skip the part where LMDB will put *data.
6863 * Copy end of page, adjusting alignment so
6864 * compiler may copy words instead of bytes.
6866 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6867 memcpy((size_t *)((char *)np + off),
6868 (size_t *)((char *)omp + off), sz - off);
6871 memcpy(np, omp, sz); /* Copy beginning of page */
6874 SETDSZ(leaf, data->mv_size);
6875 if (F_ISSET(flags, MDB_RESERVE))
6876 data->mv_data = METADATA(omp);
6878 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6882 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6884 } else if (data->mv_size == olddata.mv_size) {
6885 /* same size, just replace it. Note that we could
6886 * also reuse this node if the new data is smaller,
6887 * but instead we opt to shrink the node in that case.
6889 if (F_ISSET(flags, MDB_RESERVE))
6890 data->mv_data = olddata.mv_data;
6891 else if (!(mc->mc_flags & C_SUB))
6892 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6894 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6899 mdb_node_del(mc, 0);
6905 nflags = flags & NODE_ADD_FLAGS;
6906 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6907 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6908 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6909 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6911 nflags |= MDB_SPLIT_REPLACE;
6912 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6914 /* There is room already in this leaf page. */
6915 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6917 /* Adjust other cursors pointing to mp */
6918 MDB_cursor *m2, *m3;
6919 MDB_dbi dbi = mc->mc_dbi;
6920 unsigned i = mc->mc_top;
6921 MDB_page *mp = mc->mc_pg[i];
6923 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6924 if (mc->mc_flags & C_SUB)
6925 m3 = &m2->mc_xcursor->mx_cursor;
6928 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
6929 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
6932 XCURSOR_REFRESH(m3, i, mp);
6937 if (rc == MDB_SUCCESS) {
6938 /* Now store the actual data in the child DB. Note that we're
6939 * storing the user data in the keys field, so there are strict
6940 * size limits on dupdata. The actual data fields of the child
6941 * DB are all zero size.
6944 int xflags, new_dupdata;
6949 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6950 if (flags & MDB_CURRENT) {
6951 xflags = MDB_CURRENT|MDB_NOSPILL;
6953 mdb_xcursor_init1(mc, leaf);
6954 xflags = (flags & MDB_NODUPDATA) ?
6955 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6958 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
6959 new_dupdata = (int)dkey.mv_size;
6960 /* converted, write the original data first */
6962 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6965 /* we've done our job */
6968 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
6969 /* Adjust other cursors pointing to mp */
6971 MDB_xcursor *mx = mc->mc_xcursor;
6972 unsigned i = mc->mc_top;
6973 MDB_page *mp = mc->mc_pg[i];
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) {
6982 XCURSOR_REFRESH(m2, i, mp);
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]++;
7940 XCURSOR_REFRESH(m3, csrc->mc_top, m3->mc_pg[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]--;
7962 XCURSOR_REFRESH(m3, csrc->mc_top, m3->mc_pg[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]) {
8164 XCURSOR_REFRESH(m3, top, m3->mc_pg[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 XCURSOR_REFRESH(m3, mc->mc_top, mp);
8430 rc = mdb_rebalance(mc);
8432 if (rc == MDB_SUCCESS) {
8433 /* DB is totally empty now, just bail out.
8434 * Other cursors adjustments were already done
8435 * by mdb_rebalance and aren't needed here.
8440 mp = mc->mc_pg[mc->mc_top];
8441 nkeys = NUMKEYS(mp);
8443 /* Adjust other cursors pointing to mp */
8444 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
8445 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8446 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8448 if (m3->mc_snum < mc->mc_snum)
8450 if (m3->mc_pg[mc->mc_top] == mp) {
8451 /* if m3 points past last node in page, find next sibling */
8452 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
8453 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8454 rc = mdb_cursor_sibling(m3, 1);
8455 if (rc == MDB_NOTFOUND) {
8456 m3->mc_flags |= C_EOF;
8461 if (mc->mc_db->md_flags & MDB_DUPSORT) {
8462 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
8463 /* If this node has dupdata, it may need to be reinited
8464 * because its data has moved.
8465 * If the xcursor was not initd it must be reinited.
8466 * Else if node points to a subDB, nothing is needed.
8467 * Else (xcursor was initd, not a subDB) needs mc_pg[0] reset.
8469 if (node->mn_flags & F_DUPDATA) {
8470 if (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
8471 if (!(node->mn_flags & F_SUBDATA))
8472 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8474 mdb_xcursor_init1(m3, node);
8475 m3->mc_xcursor->mx_cursor.mc_flags |= C_DEL;
8482 mc->mc_flags |= C_DEL;
8486 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8491 mdb_del(MDB_txn *txn, MDB_dbi dbi,
8492 MDB_val *key, MDB_val *data)
8494 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8497 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8498 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8500 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
8501 /* must ignore any data */
8505 return mdb_del0(txn, dbi, key, data, 0);
8509 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
8510 MDB_val *key, MDB_val *data, unsigned flags)
8515 MDB_val rdata, *xdata;
8519 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
8521 mdb_cursor_init(&mc, txn, dbi, &mx);
8530 flags |= MDB_NODUPDATA;
8532 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
8534 /* let mdb_page_split know about this cursor if needed:
8535 * delete will trigger a rebalance; if it needs to move
8536 * a node from one page to another, it will have to
8537 * update the parent's separator key(s). If the new sepkey
8538 * is larger than the current one, the parent page may
8539 * run out of space, triggering a split. We need this
8540 * cursor to be consistent until the end of the rebalance.
8542 mc.mc_flags |= C_UNTRACK;
8543 mc.mc_next = txn->mt_cursors[dbi];
8544 txn->mt_cursors[dbi] = &mc;
8545 rc = mdb_cursor_del(&mc, flags);
8546 txn->mt_cursors[dbi] = mc.mc_next;
8551 /** Split a page and insert a new node.
8552 * Set #MDB_TXN_ERROR on failure.
8553 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
8554 * The cursor will be updated to point to the actual page and index where
8555 * the node got inserted after the split.
8556 * @param[in] newkey The key for the newly inserted node.
8557 * @param[in] newdata The data for the newly inserted node.
8558 * @param[in] newpgno The page number, if the new node is a branch node.
8559 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
8560 * @return 0 on success, non-zero on failure.
8563 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
8564 unsigned int nflags)
8567 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
8570 int i, j, split_indx, nkeys, pmax;
8571 MDB_env *env = mc->mc_txn->mt_env;
8573 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
8574 MDB_page *copy = NULL;
8575 MDB_page *mp, *rp, *pp;
8580 mp = mc->mc_pg[mc->mc_top];
8581 newindx = mc->mc_ki[mc->mc_top];
8582 nkeys = NUMKEYS(mp);
8584 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
8585 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
8586 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
8588 /* Create a right sibling. */
8589 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
8591 rp->mp_pad = mp->mp_pad;
8592 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
8594 /* Usually when splitting the root page, the cursor
8595 * height is 1. But when called from mdb_update_key,
8596 * the cursor height may be greater because it walks
8597 * up the stack while finding the branch slot to update.
8599 if (mc->mc_top < 1) {
8600 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
8602 /* shift current top to make room for new parent */
8603 for (i=mc->mc_snum; i>0; i--) {
8604 mc->mc_pg[i] = mc->mc_pg[i-1];
8605 mc->mc_ki[i] = mc->mc_ki[i-1];
8609 mc->mc_db->md_root = pp->mp_pgno;
8610 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
8611 new_root = mc->mc_db->md_depth++;
8613 /* Add left (implicit) pointer. */
8614 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
8615 /* undo the pre-push */
8616 mc->mc_pg[0] = mc->mc_pg[1];
8617 mc->mc_ki[0] = mc->mc_ki[1];
8618 mc->mc_db->md_root = mp->mp_pgno;
8619 mc->mc_db->md_depth--;
8626 ptop = mc->mc_top-1;
8627 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
8630 mdb_cursor_copy(mc, &mn);
8631 mn.mc_xcursor = NULL;
8632 mn.mc_pg[mn.mc_top] = rp;
8633 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
8635 if (nflags & MDB_APPEND) {
8636 mn.mc_ki[mn.mc_top] = 0;
8638 split_indx = newindx;
8642 split_indx = (nkeys+1) / 2;
8647 unsigned int lsize, rsize, ksize;
8648 /* Move half of the keys to the right sibling */
8649 x = mc->mc_ki[mc->mc_top] - split_indx;
8650 ksize = mc->mc_db->md_pad;
8651 split = LEAF2KEY(mp, split_indx, ksize);
8652 rsize = (nkeys - split_indx) * ksize;
8653 lsize = (nkeys - split_indx) * sizeof(indx_t);
8654 mp->mp_lower -= lsize;
8655 rp->mp_lower += lsize;
8656 mp->mp_upper += rsize - lsize;
8657 rp->mp_upper -= rsize - lsize;
8658 sepkey.mv_size = ksize;
8659 if (newindx == split_indx) {
8660 sepkey.mv_data = newkey->mv_data;
8662 sepkey.mv_data = split;
8665 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
8666 memcpy(rp->mp_ptrs, split, rsize);
8667 sepkey.mv_data = rp->mp_ptrs;
8668 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
8669 memcpy(ins, newkey->mv_data, ksize);
8670 mp->mp_lower += sizeof(indx_t);
8671 mp->mp_upper -= ksize - sizeof(indx_t);
8674 memcpy(rp->mp_ptrs, split, x * ksize);
8675 ins = LEAF2KEY(rp, x, ksize);
8676 memcpy(ins, newkey->mv_data, ksize);
8677 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
8678 rp->mp_lower += sizeof(indx_t);
8679 rp->mp_upper -= ksize - sizeof(indx_t);
8680 mc->mc_ki[mc->mc_top] = x;
8683 int psize, nsize, k;
8684 /* Maximum free space in an empty page */
8685 pmax = env->me_psize - PAGEHDRSZ;
8687 nsize = mdb_leaf_size(env, newkey, newdata);
8689 nsize = mdb_branch_size(env, newkey);
8690 nsize = EVEN(nsize);
8692 /* grab a page to hold a temporary copy */
8693 copy = mdb_page_malloc(mc->mc_txn, 1);
8698 copy->mp_pgno = mp->mp_pgno;
8699 copy->mp_flags = mp->mp_flags;
8700 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
8701 copy->mp_upper = env->me_psize - PAGEBASE;
8703 /* prepare to insert */
8704 for (i=0, j=0; i<nkeys; i++) {
8706 copy->mp_ptrs[j++] = 0;
8708 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
8711 /* When items are relatively large the split point needs
8712 * to be checked, because being off-by-one will make the
8713 * difference between success or failure in mdb_node_add.
8715 * It's also relevant if a page happens to be laid out
8716 * such that one half of its nodes are all "small" and
8717 * the other half of its nodes are "large." If the new
8718 * item is also "large" and falls on the half with
8719 * "large" nodes, it also may not fit.
8721 * As a final tweak, if the new item goes on the last
8722 * spot on the page (and thus, onto the new page), bias
8723 * the split so the new page is emptier than the old page.
8724 * This yields better packing during sequential inserts.
8726 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
8727 /* Find split point */
8729 if (newindx <= split_indx || newindx >= nkeys) {
8731 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
8736 for (; i!=k; i+=j) {
8741 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8742 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
8744 if (F_ISSET(node->mn_flags, F_BIGDATA))
8745 psize += sizeof(pgno_t);
8747 psize += NODEDSZ(node);
8749 psize = EVEN(psize);
8751 if (psize > pmax || i == k-j) {
8752 split_indx = i + (j<0);
8757 if (split_indx == newindx) {
8758 sepkey.mv_size = newkey->mv_size;
8759 sepkey.mv_data = newkey->mv_data;
8761 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
8762 sepkey.mv_size = node->mn_ksize;
8763 sepkey.mv_data = NODEKEY(node);
8768 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
8770 /* Copy separator key to the parent.
8772 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
8773 int snum = mc->mc_snum;
8777 /* We want other splits to find mn when doing fixups */
8778 WITH_CURSOR_TRACKING(mn,
8779 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
8784 if (mc->mc_snum > snum) {
8787 /* Right page might now have changed parent.
8788 * Check if left page also changed parent.
8790 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8791 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8792 for (i=0; i<ptop; i++) {
8793 mc->mc_pg[i] = mn.mc_pg[i];
8794 mc->mc_ki[i] = mn.mc_ki[i];
8796 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8797 if (mn.mc_ki[ptop]) {
8798 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8800 /* find right page's left sibling */
8801 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8802 mdb_cursor_sibling(mc, 0);
8807 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8810 if (rc != MDB_SUCCESS) {
8813 if (nflags & MDB_APPEND) {
8814 mc->mc_pg[mc->mc_top] = rp;
8815 mc->mc_ki[mc->mc_top] = 0;
8816 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8819 for (i=0; i<mc->mc_top; i++)
8820 mc->mc_ki[i] = mn.mc_ki[i];
8821 } else if (!IS_LEAF2(mp)) {
8823 mc->mc_pg[mc->mc_top] = rp;
8828 rkey.mv_data = newkey->mv_data;
8829 rkey.mv_size = newkey->mv_size;
8835 /* Update index for the new key. */
8836 mc->mc_ki[mc->mc_top] = j;
8838 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8839 rkey.mv_data = NODEKEY(node);
8840 rkey.mv_size = node->mn_ksize;
8842 xdata.mv_data = NODEDATA(node);
8843 xdata.mv_size = NODEDSZ(node);
8846 pgno = NODEPGNO(node);
8847 flags = node->mn_flags;
8850 if (!IS_LEAF(mp) && j == 0) {
8851 /* First branch index doesn't need key data. */
8855 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8861 mc->mc_pg[mc->mc_top] = copy;
8866 } while (i != split_indx);
8868 nkeys = NUMKEYS(copy);
8869 for (i=0; i<nkeys; i++)
8870 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8871 mp->mp_lower = copy->mp_lower;
8872 mp->mp_upper = copy->mp_upper;
8873 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8874 env->me_psize - copy->mp_upper - PAGEBASE);
8876 /* reset back to original page */
8877 if (newindx < split_indx) {
8878 mc->mc_pg[mc->mc_top] = mp;
8880 mc->mc_pg[mc->mc_top] = rp;
8882 /* Make sure mc_ki is still valid.
8884 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8885 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8886 for (i=0; i<=ptop; i++) {
8887 mc->mc_pg[i] = mn.mc_pg[i];
8888 mc->mc_ki[i] = mn.mc_ki[i];
8892 if (nflags & MDB_RESERVE) {
8893 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8894 if (!(node->mn_flags & F_BIGDATA))
8895 newdata->mv_data = NODEDATA(node);
8898 if (newindx >= split_indx) {
8899 mc->mc_pg[mc->mc_top] = rp;
8901 /* Make sure mc_ki is still valid.
8903 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8904 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8905 for (i=0; i<=ptop; i++) {
8906 mc->mc_pg[i] = mn.mc_pg[i];
8907 mc->mc_ki[i] = mn.mc_ki[i];
8914 /* Adjust other cursors pointing to mp */
8915 MDB_cursor *m2, *m3;
8916 MDB_dbi dbi = mc->mc_dbi;
8917 nkeys = NUMKEYS(mp);
8919 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8920 if (mc->mc_flags & C_SUB)
8921 m3 = &m2->mc_xcursor->mx_cursor;
8926 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8930 /* sub cursors may be on different DB */
8931 if (m3->mc_pg[0] != mp)
8934 for (k=new_root; k>=0; k--) {
8935 m3->mc_ki[k+1] = m3->mc_ki[k];
8936 m3->mc_pg[k+1] = m3->mc_pg[k];
8938 if (m3->mc_ki[0] >= nkeys) {
8943 m3->mc_pg[0] = mc->mc_pg[0];
8947 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8948 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8949 m3->mc_ki[mc->mc_top]++;
8950 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8951 m3->mc_pg[mc->mc_top] = rp;
8952 m3->mc_ki[mc->mc_top] -= nkeys;
8953 for (i=0; i<mc->mc_top; i++) {
8954 m3->mc_ki[i] = mn.mc_ki[i];
8955 m3->mc_pg[i] = mn.mc_pg[i];
8958 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8959 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8963 XCURSOR_REFRESH(m3, mc->mc_top, m3->mc_pg[mc->mc_top]);
8966 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8969 if (copy) /* tmp page */
8970 mdb_page_free(env, copy);
8972 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8977 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8978 MDB_val *key, MDB_val *data, unsigned int flags)
8984 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8987 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
8990 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8991 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8993 mdb_cursor_init(&mc, txn, dbi, &mx);
8994 mc.mc_next = txn->mt_cursors[dbi];
8995 txn->mt_cursors[dbi] = &mc;
8996 rc = mdb_cursor_put(&mc, key, data, flags);
8997 txn->mt_cursors[dbi] = mc.mc_next;
9002 #define MDB_WBUF (1024*1024)
9004 #define MDB_EOF 0x10 /**< #mdb_env_copyfd1() is done reading */
9006 /** State needed for a double-buffering compacting copy. */
9007 typedef struct mdb_copy {
9010 pthread_mutex_t mc_mutex;
9011 pthread_cond_t mc_cond; /**< Condition variable for #mc_new */
9016 pgno_t mc_next_pgno;
9018 int mc_toggle; /**< Buffer number in provider */
9019 int mc_new; /**< (0-2 buffers to write) | (#MDB_EOF at end) */
9020 /** Error code. Never cleared if set. Both threads can set nonzero
9021 * to fail the copy. Not mutex-protected, LMDB expects atomic int.
9023 volatile int mc_error;
9026 /** Dedicated writer thread for compacting copy. */
9027 static THREAD_RET ESECT CALL_CONV
9028 mdb_env_copythr(void *arg)
9032 int toggle = 0, wsize, rc;
9035 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9038 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9042 sigaddset(&set, SIGPIPE);
9043 if ((rc = pthread_sigmask(SIG_BLOCK, &set, NULL)) != 0)
9048 pthread_mutex_lock(&my->mc_mutex);
9051 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9052 if (my->mc_new == 0 + MDB_EOF) /* 0 buffers, just EOF */
9054 wsize = my->mc_wlen[toggle];
9055 ptr = my->mc_wbuf[toggle];
9058 while (wsize > 0 && !my->mc_error) {
9059 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
9062 #if defined(SIGPIPE) && !defined(_WIN32)
9064 /* Collect the pending SIGPIPE, otherwise at least OS X
9065 * gives it to the process on thread-exit (ITS#8504).
9068 sigwait(&set, &tmp);
9072 } else if (len > 0) {
9085 /* If there's an overflow page tail, write it too */
9086 if (my->mc_olen[toggle]) {
9087 wsize = my->mc_olen[toggle];
9088 ptr = my->mc_over[toggle];
9089 my->mc_olen[toggle] = 0;
9092 my->mc_wlen[toggle] = 0;
9094 /* Return the empty buffer to provider */
9096 pthread_cond_signal(&my->mc_cond);
9098 pthread_mutex_unlock(&my->mc_mutex);
9099 return (THREAD_RET)0;
9103 /** Give buffer and/or #MDB_EOF to writer thread, await unused buffer.
9105 * @param[in] my control structure.
9106 * @param[in] adjust (1 to hand off 1 buffer) | (MDB_EOF when ending).
9109 mdb_env_cthr_toggle(mdb_copy *my, int adjust)
9111 pthread_mutex_lock(&my->mc_mutex);
9112 my->mc_new += adjust;
9113 pthread_cond_signal(&my->mc_cond);
9114 while (my->mc_new & 2) /* both buffers in use */
9115 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9116 pthread_mutex_unlock(&my->mc_mutex);
9118 my->mc_toggle ^= (adjust & 1);
9119 /* Both threads reset mc_wlen, to be safe from threading errors */
9120 my->mc_wlen[my->mc_toggle] = 0;
9121 return my->mc_error;
9124 /** Depth-first tree traversal for compacting copy.
9125 * @param[in] my control structure.
9126 * @param[in,out] pg database root.
9127 * @param[in] flags includes #F_DUPDATA if it is a sorted-duplicate sub-DB.
9130 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
9132 MDB_cursor mc = {0};
9134 MDB_page *mo, *mp, *leaf;
9139 /* Empty DB, nothing to do */
9140 if (*pg == P_INVALID)
9144 mc.mc_txn = my->mc_txn;
9146 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
9149 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
9153 /* Make cursor pages writable */
9154 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
9158 for (i=0; i<mc.mc_top; i++) {
9159 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
9160 mc.mc_pg[i] = (MDB_page *)ptr;
9161 ptr += my->mc_env->me_psize;
9164 /* This is writable space for a leaf page. Usually not needed. */
9165 leaf = (MDB_page *)ptr;
9167 toggle = my->mc_toggle;
9168 while (mc.mc_snum > 0) {
9170 mp = mc.mc_pg[mc.mc_top];
9174 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
9175 for (i=0; i<n; i++) {
9176 ni = NODEPTR(mp, i);
9177 if (ni->mn_flags & F_BIGDATA) {
9181 /* Need writable leaf */
9183 mc.mc_pg[mc.mc_top] = leaf;
9184 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9186 ni = NODEPTR(mp, i);
9189 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9190 memcpy(NODEDATA(ni), &my->mc_next_pgno, sizeof(pgno_t));
9191 rc = mdb_page_get(&mc, pg, &omp, NULL);
9194 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9195 rc = mdb_env_cthr_toggle(my, 1);
9198 toggle = my->mc_toggle;
9200 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9201 memcpy(mo, omp, my->mc_env->me_psize);
9202 mo->mp_pgno = my->mc_next_pgno;
9203 my->mc_next_pgno += omp->mp_pages;
9204 my->mc_wlen[toggle] += my->mc_env->me_psize;
9205 if (omp->mp_pages > 1) {
9206 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
9207 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
9208 rc = mdb_env_cthr_toggle(my, 1);
9211 toggle = my->mc_toggle;
9213 } else if (ni->mn_flags & F_SUBDATA) {
9216 /* Need writable leaf */
9218 mc.mc_pg[mc.mc_top] = leaf;
9219 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9221 ni = NODEPTR(mp, i);
9224 memcpy(&db, NODEDATA(ni), sizeof(db));
9225 my->mc_toggle = toggle;
9226 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
9229 toggle = my->mc_toggle;
9230 memcpy(NODEDATA(ni), &db, sizeof(db));
9235 mc.mc_ki[mc.mc_top]++;
9236 if (mc.mc_ki[mc.mc_top] < n) {
9239 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
9241 rc = mdb_page_get(&mc, pg, &mp, NULL);
9246 mc.mc_ki[mc.mc_top] = 0;
9247 if (IS_BRANCH(mp)) {
9248 /* Whenever we advance to a sibling branch page,
9249 * we must proceed all the way down to its first leaf.
9251 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
9254 mc.mc_pg[mc.mc_top] = mp;
9258 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9259 rc = mdb_env_cthr_toggle(my, 1);
9262 toggle = my->mc_toggle;
9264 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9265 mdb_page_copy(mo, mp, my->mc_env->me_psize);
9266 mo->mp_pgno = my->mc_next_pgno++;
9267 my->mc_wlen[toggle] += my->mc_env->me_psize;
9269 /* Update parent if there is one */
9270 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
9271 SETPGNO(ni, mo->mp_pgno);
9272 mdb_cursor_pop(&mc);
9274 /* Otherwise we're done */
9284 /** Copy environment with compaction. */
9286 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
9291 MDB_txn *txn = NULL;
9293 pgno_t root, new_root;
9294 int rc = MDB_SUCCESS;
9297 if (!(my.mc_mutex = CreateMutex(NULL, FALSE, NULL)) ||
9298 !(my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL))) {
9302 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
9303 if (my.mc_wbuf[0] == NULL) {
9304 /* _aligned_malloc() sets errno, but we use Windows error codes */
9305 rc = ERROR_NOT_ENOUGH_MEMORY;
9309 if ((rc = pthread_mutex_init(&my.mc_mutex, NULL)) != 0)
9311 if ((rc = pthread_cond_init(&my.mc_cond, NULL)) != 0)
9313 #ifdef HAVE_MEMALIGN
9314 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
9315 if (my.mc_wbuf[0] == NULL) {
9322 if ((rc = posix_memalign(&p, env->me_os_psize, MDB_WBUF*2)) != 0)
9328 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
9329 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
9330 my.mc_next_pgno = NUM_METAS;
9333 rc = THREAD_CREATE(thr, mdb_env_copythr, &my);
9337 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9341 mp = (MDB_page *)my.mc_wbuf[0];
9342 memset(mp, 0, NUM_METAS * env->me_psize);
9344 mp->mp_flags = P_META;
9345 mm = (MDB_meta *)METADATA(mp);
9346 mdb_env_init_meta0(env, mm);
9347 mm->mm_address = env->me_metas[0]->mm_address;
9349 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
9351 mp->mp_flags = P_META;
9352 *(MDB_meta *)METADATA(mp) = *mm;
9353 mm = (MDB_meta *)METADATA(mp);
9355 /* Set metapage 1 with current main DB */
9356 root = new_root = txn->mt_dbs[MAIN_DBI].md_root;
9357 if (root != P_INVALID) {
9358 /* Count free pages + freeDB pages. Subtract from last_pg
9359 * to find the new last_pg, which also becomes the new root.
9361 MDB_ID freecount = 0;
9364 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
9365 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
9366 freecount += *(MDB_ID *)data.mv_data;
9367 if (rc != MDB_NOTFOUND)
9369 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
9370 txn->mt_dbs[FREE_DBI].md_leaf_pages +
9371 txn->mt_dbs[FREE_DBI].md_overflow_pages;
9373 new_root = txn->mt_next_pgno - 1 - freecount;
9374 mm->mm_last_pg = new_root;
9375 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
9376 mm->mm_dbs[MAIN_DBI].md_root = new_root;
9378 /* When the DB is empty, handle it specially to
9379 * fix any breakage like page leaks from ITS#8174.
9381 mm->mm_dbs[MAIN_DBI].md_flags = txn->mt_dbs[MAIN_DBI].md_flags;
9383 if (root != P_INVALID || mm->mm_dbs[MAIN_DBI].md_flags) {
9384 mm->mm_txnid = 1; /* use metapage 1 */
9387 my.mc_wlen[0] = env->me_psize * NUM_METAS;
9389 rc = mdb_env_cwalk(&my, &root, 0);
9390 if (rc == MDB_SUCCESS && root != new_root) {
9391 rc = MDB_INCOMPATIBLE; /* page leak or corrupt DB */
9397 mdb_env_cthr_toggle(&my, 1 | MDB_EOF);
9398 rc = THREAD_FINISH(thr);
9403 if (my.mc_wbuf[0]) _aligned_free(my.mc_wbuf[0]);
9404 if (my.mc_cond) CloseHandle(my.mc_cond);
9405 if (my.mc_mutex) CloseHandle(my.mc_mutex);
9407 free(my.mc_wbuf[0]);
9408 pthread_cond_destroy(&my.mc_cond);
9410 pthread_mutex_destroy(&my.mc_mutex);
9412 return rc ? rc : my.mc_error;
9415 /** Copy environment as-is. */
9417 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
9419 MDB_txn *txn = NULL;
9420 mdb_mutexref_t wmutex = NULL;
9426 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9430 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9433 /* Do the lock/unlock of the reader mutex before starting the
9434 * write txn. Otherwise other read txns could block writers.
9436 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9441 /* We must start the actual read txn after blocking writers */
9442 mdb_txn_end(txn, MDB_END_RESET_TMP);
9444 /* Temporarily block writers until we snapshot the meta pages */
9445 wmutex = env->me_wmutex;
9446 if (LOCK_MUTEX(rc, env, wmutex))
9449 rc = mdb_txn_renew0(txn);
9451 UNLOCK_MUTEX(wmutex);
9456 wsize = env->me_psize * NUM_METAS;
9460 DO_WRITE(rc, fd, ptr, w2, len);
9464 } else if (len > 0) {
9470 /* Non-blocking or async handles are not supported */
9476 UNLOCK_MUTEX(wmutex);
9481 w3 = txn->mt_next_pgno * env->me_psize;
9484 if ((rc = mdb_fsize(env->me_fd, &fsize)))
9491 if (wsize > MAX_WRITE)
9495 DO_WRITE(rc, fd, ptr, w2, len);
9499 } else if (len > 0) {
9516 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
9518 if (flags & MDB_CP_COMPACT)
9519 return mdb_env_copyfd1(env, fd);
9521 return mdb_env_copyfd0(env, fd);
9525 mdb_env_copyfd(MDB_env *env, HANDLE fd)
9527 return mdb_env_copyfd2(env, fd, 0);
9531 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
9535 HANDLE newfd = INVALID_HANDLE_VALUE;
9537 rc = mdb_fname_init(path, env->me_flags | MDB_NOLOCK, &fname);
9538 if (rc == MDB_SUCCESS) {
9539 rc = mdb_fopen(env, &fname, MDB_O_COPY, 0666, &newfd);
9540 mdb_fname_destroy(fname);
9542 if (rc == MDB_SUCCESS) {
9543 rc = mdb_env_copyfd2(env, newfd, flags);
9544 if (close(newfd) < 0 && rc == MDB_SUCCESS)
9551 mdb_env_copy(MDB_env *env, const char *path)
9553 return mdb_env_copy2(env, path, 0);
9557 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
9559 if (flag & ~CHANGEABLE)
9562 env->me_flags |= flag;
9564 env->me_flags &= ~flag;
9569 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
9574 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
9579 mdb_env_set_userctx(MDB_env *env, void *ctx)
9583 env->me_userctx = ctx;
9588 mdb_env_get_userctx(MDB_env *env)
9590 return env ? env->me_userctx : NULL;
9594 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
9599 env->me_assert_func = func;
9605 mdb_env_get_path(MDB_env *env, const char **arg)
9610 *arg = env->me_path;
9615 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
9624 /** Common code for #mdb_stat() and #mdb_env_stat().
9625 * @param[in] env the environment to operate in.
9626 * @param[in] db the #MDB_db record containing the stats to return.
9627 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
9628 * @return 0, this function always succeeds.
9631 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
9633 arg->ms_psize = env->me_psize;
9634 arg->ms_depth = db->md_depth;
9635 arg->ms_branch_pages = db->md_branch_pages;
9636 arg->ms_leaf_pages = db->md_leaf_pages;
9637 arg->ms_overflow_pages = db->md_overflow_pages;
9638 arg->ms_entries = db->md_entries;
9644 mdb_env_stat(MDB_env *env, MDB_stat *arg)
9648 if (env == NULL || arg == NULL)
9651 meta = mdb_env_pick_meta(env);
9653 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
9657 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
9661 if (env == NULL || arg == NULL)
9664 meta = mdb_env_pick_meta(env);
9665 arg->me_mapaddr = meta->mm_address;
9666 arg->me_last_pgno = meta->mm_last_pg;
9667 arg->me_last_txnid = meta->mm_txnid;
9669 arg->me_mapsize = env->me_mapsize;
9670 arg->me_maxreaders = env->me_maxreaders;
9671 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
9675 /** Set the default comparison functions for a database.
9676 * Called immediately after a database is opened to set the defaults.
9677 * The user can then override them with #mdb_set_compare() or
9678 * #mdb_set_dupsort().
9679 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
9680 * @param[in] dbi A database handle returned by #mdb_dbi_open()
9683 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
9685 uint16_t f = txn->mt_dbs[dbi].md_flags;
9687 txn->mt_dbxs[dbi].md_cmp =
9688 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
9689 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
9691 txn->mt_dbxs[dbi].md_dcmp =
9692 !(f & MDB_DUPSORT) ? 0 :
9693 ((f & MDB_INTEGERDUP)
9694 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
9695 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
9698 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
9704 int rc, dbflag, exact;
9705 unsigned int unused = 0, seq;
9709 if (flags & ~VALID_FLAGS)
9711 if (txn->mt_flags & MDB_TXN_BLOCKED)
9717 if (flags & PERSISTENT_FLAGS) {
9718 uint16_t f2 = flags & PERSISTENT_FLAGS;
9719 /* make sure flag changes get committed */
9720 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
9721 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
9722 txn->mt_flags |= MDB_TXN_DIRTY;
9725 mdb_default_cmp(txn, MAIN_DBI);
9729 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
9730 mdb_default_cmp(txn, MAIN_DBI);
9733 /* Is the DB already open? */
9735 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
9736 if (!txn->mt_dbxs[i].md_name.mv_size) {
9737 /* Remember this free slot */
9738 if (!unused) unused = i;
9741 if (len == txn->mt_dbxs[i].md_name.mv_size &&
9742 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
9748 /* If no free slot and max hit, fail */
9749 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
9750 return MDB_DBS_FULL;
9752 /* Cannot mix named databases with some mainDB flags */
9753 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
9754 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
9756 /* Find the DB info */
9757 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
9760 key.mv_data = (void *)name;
9761 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
9762 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
9763 if (rc == MDB_SUCCESS) {
9764 /* make sure this is actually a DB */
9765 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
9766 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
9767 return MDB_INCOMPATIBLE;
9769 if (rc != MDB_NOTFOUND || !(flags & MDB_CREATE))
9771 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9775 /* Done here so we cannot fail after creating a new DB */
9776 if ((namedup = strdup(name)) == NULL)
9780 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
9781 data.mv_size = sizeof(MDB_db);
9782 data.mv_data = &dummy;
9783 memset(&dummy, 0, sizeof(dummy));
9784 dummy.md_root = P_INVALID;
9785 dummy.md_flags = flags & PERSISTENT_FLAGS;
9786 WITH_CURSOR_TRACKING(mc,
9787 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA));
9794 /* Got info, register DBI in this txn */
9795 unsigned int slot = unused ? unused : txn->mt_numdbs;
9796 txn->mt_dbxs[slot].md_name.mv_data = namedup;
9797 txn->mt_dbxs[slot].md_name.mv_size = len;
9798 txn->mt_dbxs[slot].md_rel = NULL;
9799 txn->mt_dbflags[slot] = dbflag;
9800 /* txn-> and env-> are the same in read txns, use
9801 * tmp variable to avoid undefined assignment
9803 seq = ++txn->mt_env->me_dbiseqs[slot];
9804 txn->mt_dbiseqs[slot] = seq;
9806 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
9808 mdb_default_cmp(txn, slot);
9818 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9820 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
9823 if (txn->mt_flags & MDB_TXN_BLOCKED)
9826 if (txn->mt_dbflags[dbi] & DB_STALE) {
9829 /* Stale, must read the DB's root. cursor_init does it for us. */
9830 mdb_cursor_init(&mc, txn, dbi, &mx);
9832 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9835 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9838 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
9840 ptr = env->me_dbxs[dbi].md_name.mv_data;
9841 /* If there was no name, this was already closed */
9843 env->me_dbxs[dbi].md_name.mv_data = NULL;
9844 env->me_dbxs[dbi].md_name.mv_size = 0;
9845 env->me_dbflags[dbi] = 0;
9846 env->me_dbiseqs[dbi]++;
9851 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9853 /* We could return the flags for the FREE_DBI too but what's the point? */
9854 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9856 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9860 /** Add all the DB's pages to the free list.
9861 * @param[in] mc Cursor on the DB to free.
9862 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9863 * @return 0 on success, non-zero on failure.
9866 mdb_drop0(MDB_cursor *mc, int subs)
9870 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9871 if (rc == MDB_SUCCESS) {
9872 MDB_txn *txn = mc->mc_txn;
9877 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
9878 * This also avoids any P_LEAF2 pages, which have no nodes.
9879 * Also if the DB doesn't have sub-DBs and has no overflow
9880 * pages, omit scanning leaves.
9882 if ((mc->mc_flags & C_SUB) ||
9883 (!subs && !mc->mc_db->md_overflow_pages))
9886 mdb_cursor_copy(mc, &mx);
9887 while (mc->mc_snum > 0) {
9888 MDB_page *mp = mc->mc_pg[mc->mc_top];
9889 unsigned n = NUMKEYS(mp);
9891 for (i=0; i<n; i++) {
9892 ni = NODEPTR(mp, i);
9893 if (ni->mn_flags & F_BIGDATA) {
9896 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9897 rc = mdb_page_get(mc, pg, &omp, NULL);
9900 mdb_cassert(mc, IS_OVERFLOW(omp));
9901 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9905 mc->mc_db->md_overflow_pages -= omp->mp_pages;
9906 if (!mc->mc_db->md_overflow_pages && !subs)
9908 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9909 mdb_xcursor_init1(mc, ni);
9910 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9915 if (!subs && !mc->mc_db->md_overflow_pages)
9918 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9920 for (i=0; i<n; i++) {
9922 ni = NODEPTR(mp, i);
9925 mdb_midl_xappend(txn->mt_free_pgs, pg);
9930 mc->mc_ki[mc->mc_top] = i;
9931 rc = mdb_cursor_sibling(mc, 1);
9933 if (rc != MDB_NOTFOUND)
9935 /* no more siblings, go back to beginning
9936 * of previous level.
9941 for (i=1; i<mc->mc_snum; i++) {
9943 mc->mc_pg[i] = mx.mc_pg[i];
9948 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9951 txn->mt_flags |= MDB_TXN_ERROR;
9952 } else if (rc == MDB_NOTFOUND) {
9955 mc->mc_flags &= ~C_INITIALIZED;
9959 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9961 MDB_cursor *mc, *m2;
9964 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9967 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9970 if (TXN_DBI_CHANGED(txn, dbi))
9973 rc = mdb_cursor_open(txn, dbi, &mc);
9977 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9978 /* Invalidate the dropped DB's cursors */
9979 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9980 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9984 /* Can't delete the main DB */
9985 if (del && dbi >= CORE_DBS) {
9986 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
9988 txn->mt_dbflags[dbi] = DB_STALE;
9989 mdb_dbi_close(txn->mt_env, dbi);
9991 txn->mt_flags |= MDB_TXN_ERROR;
9994 /* reset the DB record, mark it dirty */
9995 txn->mt_dbflags[dbi] |= DB_DIRTY;
9996 txn->mt_dbs[dbi].md_depth = 0;
9997 txn->mt_dbs[dbi].md_branch_pages = 0;
9998 txn->mt_dbs[dbi].md_leaf_pages = 0;
9999 txn->mt_dbs[dbi].md_overflow_pages = 0;
10000 txn->mt_dbs[dbi].md_entries = 0;
10001 txn->mt_dbs[dbi].md_root = P_INVALID;
10003 txn->mt_flags |= MDB_TXN_DIRTY;
10006 mdb_cursor_close(mc);
10010 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10012 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10015 txn->mt_dbxs[dbi].md_cmp = cmp;
10016 return MDB_SUCCESS;
10019 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10021 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10024 txn->mt_dbxs[dbi].md_dcmp = cmp;
10025 return MDB_SUCCESS;
10028 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
10030 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10033 txn->mt_dbxs[dbi].md_rel = rel;
10034 return MDB_SUCCESS;
10037 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
10039 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10042 txn->mt_dbxs[dbi].md_relctx = ctx;
10043 return MDB_SUCCESS;
10047 mdb_env_get_maxkeysize(MDB_env *env)
10049 return ENV_MAXKEY(env);
10053 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
10055 unsigned int i, rdrs;
10058 int rc = 0, first = 1;
10062 if (!env->me_txns) {
10063 return func("(no reader locks)\n", ctx);
10065 rdrs = env->me_txns->mti_numreaders;
10066 mr = env->me_txns->mti_readers;
10067 for (i=0; i<rdrs; i++) {
10068 if (mr[i].mr_pid) {
10069 txnid_t txnid = mr[i].mr_txnid;
10070 sprintf(buf, txnid == (txnid_t)-1 ?
10071 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
10072 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
10075 rc = func(" pid thread txnid\n", ctx);
10079 rc = func(buf, ctx);
10085 rc = func("(no active readers)\n", ctx);
10090 /** Insert pid into list if not already present.
10091 * return -1 if already present.
10094 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
10096 /* binary search of pid in list */
10098 unsigned cursor = 1;
10100 unsigned n = ids[0];
10103 unsigned pivot = n >> 1;
10104 cursor = base + pivot + 1;
10105 val = pid - ids[cursor];
10110 } else if ( val > 0 ) {
10115 /* found, so it's a duplicate */
10124 for (n = ids[0]; n > cursor; n--)
10131 mdb_reader_check(MDB_env *env, int *dead)
10137 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
10140 /** As #mdb_reader_check(). \b rlocked is set if caller locked #me_rmutex. */
10142 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
10144 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
10145 unsigned int i, j, rdrs;
10147 MDB_PID_T *pids, pid;
10148 int rc = MDB_SUCCESS, count = 0;
10150 rdrs = env->me_txns->mti_numreaders;
10151 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
10155 mr = env->me_txns->mti_readers;
10156 for (i=0; i<rdrs; i++) {
10157 pid = mr[i].mr_pid;
10158 if (pid && pid != env->me_pid) {
10159 if (mdb_pid_insert(pids, pid) == 0) {
10160 if (!mdb_reader_pid(env, Pidcheck, pid)) {
10161 /* Stale reader found */
10164 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
10165 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
10167 rdrs = 0; /* the above checked all readers */
10169 /* Recheck, a new process may have reused pid */
10170 if (mdb_reader_pid(env, Pidcheck, pid))
10174 for (; j<rdrs; j++)
10175 if (mr[j].mr_pid == pid) {
10176 DPRINTF(("clear stale reader pid %u txn %"Z"d",
10177 (unsigned) pid, mr[j].mr_txnid));
10182 UNLOCK_MUTEX(rmutex);
10193 #ifdef MDB_ROBUST_SUPPORTED
10194 /** Handle #LOCK_MUTEX0() failure.
10195 * Try to repair the lock file if the mutex owner died.
10196 * @param[in] env the environment handle
10197 * @param[in] mutex LOCK_MUTEX0() mutex
10198 * @param[in] rc LOCK_MUTEX0() error (nonzero)
10199 * @return 0 on success with the mutex locked, or an error code on failure.
10202 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10207 if (rc == MDB_OWNERDEAD) {
10208 /* We own the mutex. Clean up after dead previous owner. */
10210 rlocked = (mutex == env->me_rmutex);
10212 /* Keep mti_txnid updated, otherwise next writer can
10213 * overwrite data which latest meta page refers to.
10215 meta = mdb_env_pick_meta(env);
10216 env->me_txns->mti_txnid = meta->mm_txnid;
10217 /* env is hosed if the dead thread was ours */
10219 env->me_flags |= MDB_FATAL_ERROR;
10220 env->me_txn = NULL;
10224 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
10225 (rc ? "this process' env is hosed" : "recovering")));
10226 rc2 = mdb_reader_check0(env, rlocked, NULL);
10228 rc2 = mdb_mutex_consistent(mutex);
10229 if (rc || (rc = rc2)) {
10230 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
10231 UNLOCK_MUTEX(mutex);
10237 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
10242 #endif /* MDB_ROBUST_SUPPORTED */
10244 #if defined(_WIN32)
10245 /** Convert \b src to new wchar_t[] string with room for \b xtra extra chars */
10247 utf8_to_utf16(const char *src, MDB_name *dst, int xtra)
10250 wchar_t *result = NULL;
10251 for (;;) { /* malloc result, then fill it in */
10252 need = MultiByteToWideChar(CP_UTF8, 0, src, -1, result, need);
10259 result = malloc(sizeof(wchar_t) * (need + xtra));
10264 dst->mn_alloced = 1;
10265 dst->mn_len = need - 1;
10266 dst->mn_val = result;
10267 return MDB_SUCCESS;
10270 #endif /* defined(_WIN32) */