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-2015 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.
41 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
42 * as int64 which is wrong. MSVC doesn't define it at all, so just
46 #define MDB_THR_T DWORD
47 #include <sys/types.h>
50 # include <sys/param.h>
52 # define LITTLE_ENDIAN 1234
53 # define BIG_ENDIAN 4321
54 # define BYTE_ORDER LITTLE_ENDIAN
56 # define SSIZE_MAX INT_MAX
60 #include <sys/types.h>
62 #define MDB_PID_T pid_t
63 #define MDB_THR_T pthread_t
64 #include <sys/param.h>
67 #ifdef HAVE_SYS_FILE_H
73 #if defined(__mips) && defined(__linux)
74 /* MIPS has cache coherency issues, requires explicit cache control */
75 #include <asm/cachectl.h>
76 extern int cacheflush(char *addr, int nbytes, int cache);
77 #define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
79 #define CACHEFLUSH(addr, bytes, cache)
82 #if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
83 /** fdatasync is broken on ext3/ext4fs on older kernels, see
84 * description in #mdb_env_open2 comments. You can safely
85 * define MDB_FDATASYNC_WORKS if this code will only be run
86 * on kernels 3.6 and newer.
88 #define BROKEN_FDATASYNC
102 typedef SSIZE_T ssize_t;
107 #if defined(__sun) || defined(ANDROID)
108 /* Most platforms have posix_memalign, older may only have memalign */
109 #define HAVE_MEMALIGN 1
113 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
114 #include <netinet/in.h>
115 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
118 #if defined(__APPLE__) || defined (BSD)
119 # if !(defined(MDB_USE_POSIX_MUTEX) || defined(MDB_USE_POSIX_SEM))
120 # define MDB_USE_SYSV_SEM 1
122 # define MDB_FDATASYNC fsync
123 #elif defined(ANDROID)
124 # define MDB_FDATASYNC fsync
129 #ifdef MDB_USE_POSIX_SEM
130 # define MDB_USE_HASH 1
131 #include <semaphore.h>
132 #elif defined(MDB_USE_SYSV_SEM)
135 #ifdef _SEM_SEMUN_UNDEFINED
138 struct semid_ds *buf;
139 unsigned short *array;
141 #endif /* _SEM_SEMUN_UNDEFINED */
143 #define MDB_USE_POSIX_MUTEX 1
144 #endif /* MDB_USE_POSIX_SEM */
147 #if defined(_WIN32) + defined(MDB_USE_POSIX_SEM) + defined(MDB_USE_SYSV_SEM) \
148 + defined(MDB_USE_POSIX_MUTEX) != 1
149 # error "Ambiguous shared-lock implementation"
153 #include <valgrind/memcheck.h>
154 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
155 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
156 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
157 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
158 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
160 #define VGMEMP_CREATE(h,r,z)
161 #define VGMEMP_ALLOC(h,a,s)
162 #define VGMEMP_FREE(h,a)
163 #define VGMEMP_DESTROY(h)
164 #define VGMEMP_DEFINED(a,s)
168 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
169 /* Solaris just defines one or the other */
170 # define LITTLE_ENDIAN 1234
171 # define BIG_ENDIAN 4321
172 # ifdef _LITTLE_ENDIAN
173 # define BYTE_ORDER LITTLE_ENDIAN
175 # define BYTE_ORDER BIG_ENDIAN
178 # define BYTE_ORDER __BYTE_ORDER
182 #ifndef LITTLE_ENDIAN
183 #define LITTLE_ENDIAN __LITTLE_ENDIAN
186 #define BIG_ENDIAN __BIG_ENDIAN
189 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
190 #define MISALIGNED_OK 1
196 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
197 # error "Unknown or unsupported endianness (BYTE_ORDER)"
198 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
199 # error "Two's complement, reasonably sized integer types, please"
203 /** Put infrequently used env functions in separate section */
205 # define ESECT __attribute__ ((section("__TEXT,text_env")))
207 # define ESECT __attribute__ ((section("text_env")))
214 #define CALL_CONV WINAPI
219 /** @defgroup internal LMDB Internals
222 /** @defgroup compat Compatibility Macros
223 * A bunch of macros to minimize the amount of platform-specific ifdefs
224 * needed throughout the rest of the code. When the features this library
225 * needs are similar enough to POSIX to be hidden in a one-or-two line
226 * replacement, this macro approach is used.
230 /** Features under development */
235 /** Wrapper around __func__, which is a C99 feature */
236 #if __STDC_VERSION__ >= 199901L
237 # define mdb_func_ __func__
238 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
239 # define mdb_func_ __FUNCTION__
241 /* If a debug message says <mdb_unknown>(), update the #if statements above */
242 # define mdb_func_ "<mdb_unknown>"
245 /* Internal error codes, not exposed outside liblmdb */
246 #define MDB_NO_ROOT (MDB_LAST_ERRCODE + 10)
248 #define MDB_OWNERDEAD ((int) WAIT_ABANDONED)
249 #elif defined MDB_USE_SYSV_SEM
250 #define MDB_OWNERDEAD (MDB_LAST_ERRCODE + 11)
251 #elif defined(MDB_USE_POSIX_MUTEX) && defined(EOWNERDEAD)
252 #define MDB_OWNERDEAD EOWNERDEAD /**< #LOCK_MUTEX0() result if dead owner */
256 #define MDB_ROBUST_SUPPORTED 1
260 #define MDB_USE_HASH 1
261 #define MDB_PIDLOCK 0
262 #define THREAD_RET DWORD
263 #define pthread_t HANDLE
264 #define pthread_mutex_t HANDLE
265 #define pthread_cond_t HANDLE
266 typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
267 #define pthread_key_t DWORD
268 #define pthread_self() GetCurrentThreadId()
269 #define pthread_key_create(x,y) \
270 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
271 #define pthread_key_delete(x) TlsFree(x)
272 #define pthread_getspecific(x) TlsGetValue(x)
273 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
274 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
275 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
276 #define pthread_cond_signal(x) SetEvent(*x)
277 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
278 #define THREAD_CREATE(thr,start,arg) thr=CreateThread(NULL,0,start,arg,0,NULL)
279 #define THREAD_FINISH(thr) WaitForSingleObject(thr, INFINITE)
280 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
281 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
282 #define mdb_mutex_consistent(mutex) 0
283 #define getpid() GetCurrentProcessId()
284 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
285 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
286 #define ErrCode() GetLastError()
287 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
288 #define close(fd) (CloseHandle(fd) ? 0 : -1)
289 #define munmap(ptr,len) UnmapViewOfFile(ptr)
290 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
291 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
293 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
297 #define THREAD_RET void *
298 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
299 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
300 #define Z "z" /**< printf format modifier for size_t */
302 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
303 #define MDB_PIDLOCK 1
305 #ifdef MDB_USE_POSIX_SEM
307 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
308 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
309 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
312 mdb_sem_wait(sem_t *sem)
315 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
319 #elif defined MDB_USE_SYSV_SEM
321 typedef struct mdb_mutex {
325 } mdb_mutex_t[1], *mdb_mutexref_t;
327 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
328 #define UNLOCK_MUTEX(mutex) do { \
329 struct sembuf sb = { 0, 1, SEM_UNDO }; \
330 sb.sem_num = (mutex)->semnum; \
331 *(mutex)->locked = 0; \
332 semop((mutex)->semid, &sb, 1); \
336 mdb_sem_wait(mdb_mutexref_t sem)
338 int rc, *locked = sem->locked;
339 struct sembuf sb = { 0, -1, SEM_UNDO };
340 sb.sem_num = sem->semnum;
342 if (!semop(sem->semid, &sb, 1)) {
343 rc = *locked ? MDB_OWNERDEAD : MDB_SUCCESS;
347 } while ((rc = errno) == EINTR);
351 #define mdb_mutex_consistent(mutex) 0
353 #else /* MDB_USE_POSIX_MUTEX: */
354 /** Shared mutex/semaphore as it is stored (mdb_mutex_t), and as
355 * local variables keep it (mdb_mutexref_t).
357 * An mdb_mutex_t can be assigned to an mdb_mutexref_t. They can
358 * be the same, or an array[size 1] and a pointer.
361 typedef pthread_mutex_t mdb_mutex_t[1], *mdb_mutexref_t;
363 /** Lock the reader or writer mutex.
364 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
366 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
367 /** Unlock the reader or writer mutex.
369 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
370 /** Mark mutex-protected data as repaired, after death of previous owner.
372 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
373 #endif /* MDB_USE_POSIX_SEM || MDB_USE_SYSV_SEM */
375 /** Get the error code for the last failed system function.
377 #define ErrCode() errno
379 /** An abstraction for a file handle.
380 * On POSIX systems file handles are small integers. On Windows
381 * they're opaque pointers.
385 /** A value for an invalid file handle.
386 * Mainly used to initialize file variables and signify that they are
389 #define INVALID_HANDLE_VALUE (-1)
391 /** Get the size of a memory page for the system.
392 * This is the basic size that the platform's memory manager uses, and is
393 * fundamental to the use of memory-mapped files.
395 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
398 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
400 #elif defined(MDB_USE_SYSV_SEM)
401 #define MNAME_LEN (sizeof(int))
403 #define MNAME_LEN (sizeof(pthread_mutex_t))
406 #ifdef MDB_USE_SYSV_SEM
407 #define SYSV_SEM_FLAG 1 /**< SysV sems in lockfile format */
409 #define SYSV_SEM_FLAG 0
414 #ifdef MDB_ROBUST_SUPPORTED
415 /** Lock mutex, handle any error, set rc = result.
416 * Return 0 on success, nonzero (not rc) on error.
418 #define LOCK_MUTEX(rc, env, mutex) \
419 (((rc) = LOCK_MUTEX0(mutex)) && \
420 ((rc) = mdb_mutex_failed(env, mutex, rc)))
421 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
423 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
424 #define mdb_mutex_failed(env, mutex, rc) (rc)
428 /** A flag for opening a file and requesting synchronous data writes.
429 * This is only used when writing a meta page. It's not strictly needed;
430 * we could just do a normal write and then immediately perform a flush.
431 * But if this flag is available it saves us an extra system call.
433 * @note If O_DSYNC is undefined but exists in /usr/include,
434 * preferably set some compiler flag to get the definition.
435 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
438 # define MDB_DSYNC O_DSYNC
442 /** Function for flushing the data of a file. Define this to fsync
443 * if fdatasync() is not supported.
445 #ifndef MDB_FDATASYNC
446 # define MDB_FDATASYNC fdatasync
450 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
461 /** A page number in the database.
462 * Note that 64 bit page numbers are overkill, since pages themselves
463 * already represent 12-13 bits of addressable memory, and the OS will
464 * always limit applications to a maximum of 63 bits of address space.
466 * @note In the #MDB_node structure, we only store 48 bits of this value,
467 * which thus limits us to only 60 bits of addressable data.
469 typedef MDB_ID pgno_t;
471 /** A transaction ID.
472 * See struct MDB_txn.mt_txnid for details.
474 typedef MDB_ID txnid_t;
476 /** @defgroup debug Debug Macros
480 /** Enable debug output. Needs variable argument macros (a C99 feature).
481 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
482 * read from and written to the database (used for free space management).
488 static int mdb_debug;
489 static txnid_t mdb_debug_start;
491 /** Print a debug message with printf formatting.
492 * Requires double parenthesis around 2 or more args.
494 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
495 # define DPRINTF0(fmt, ...) \
496 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
498 # define DPRINTF(args) ((void) 0)
500 /** Print a debug string.
501 * The string is printed literally, with no format processing.
503 #define DPUTS(arg) DPRINTF(("%s", arg))
504 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
506 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
509 /** @brief The maximum size of a database page.
511 * It is 32k or 64k, since value-PAGEBASE must fit in
512 * #MDB_page.%mp_upper.
514 * LMDB will use database pages < OS pages if needed.
515 * That causes more I/O in write transactions: The OS must
516 * know (read) the whole page before writing a partial page.
518 * Note that we don't currently support Huge pages. On Linux,
519 * regular data files cannot use Huge pages, and in general
520 * Huge pages aren't actually pageable. We rely on the OS
521 * demand-pager to read our data and page it out when memory
522 * pressure from other processes is high. So until OSs have
523 * actual paging support for Huge pages, they're not viable.
525 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
527 /** The minimum number of keys required in a database page.
528 * Setting this to a larger value will place a smaller bound on the
529 * maximum size of a data item. Data items larger than this size will
530 * be pushed into overflow pages instead of being stored directly in
531 * the B-tree node. This value used to default to 4. With a page size
532 * of 4096 bytes that meant that any item larger than 1024 bytes would
533 * go into an overflow page. That also meant that on average 2-3KB of
534 * each overflow page was wasted space. The value cannot be lower than
535 * 2 because then there would no longer be a tree structure. With this
536 * value, items larger than 2KB will go into overflow pages, and on
537 * average only 1KB will be wasted.
539 #define MDB_MINKEYS 2
541 /** A stamp that identifies a file as an LMDB file.
542 * There's nothing special about this value other than that it is easily
543 * recognizable, and it will reflect any byte order mismatches.
545 #define MDB_MAGIC 0xBEEFC0DE
547 /** The version number for a database's datafile format. */
548 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
549 /** The version number for a database's lockfile format. */
550 #define MDB_LOCK_VERSION ((MDB_DEVEL) ? 999 : 1)
552 /** @brief The max size of a key we can write, or 0 for computed max.
554 * This macro should normally be left alone or set to 0.
555 * Note that a database with big keys or dupsort data cannot be
556 * reliably modified by a liblmdb which uses a smaller max.
557 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
559 * Other values are allowed, for backwards compat. However:
560 * A value bigger than the computed max can break if you do not
561 * know what you are doing, and liblmdb <= 0.9.10 can break when
562 * modifying a DB with keys/dupsort data bigger than its max.
564 * Data items in an #MDB_DUPSORT database are also limited to
565 * this size, since they're actually keys of a sub-DB. Keys and
566 * #MDB_DUPSORT data items must fit on a node in a regular page.
568 #ifndef MDB_MAXKEYSIZE
569 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
572 /** The maximum size of a key we can write to the environment. */
574 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
576 #define ENV_MAXKEY(env) ((env)->me_maxkey)
579 /** @brief The maximum size of a data item.
581 * We only store a 32 bit value for node sizes.
583 #define MAXDATASIZE 0xffffffffUL
586 /** Key size which fits in a #DKBUF.
589 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
592 * This is used for printing a hex dump of a key's contents.
594 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
595 /** Display a key in hex.
597 * Invoke a function to display a key in hex.
599 #define DKEY(x) mdb_dkey(x, kbuf)
605 /** An invalid page number.
606 * Mainly used to denote an empty tree.
608 #define P_INVALID (~(pgno_t)0)
610 /** Test if the flags \b f are set in a flag word \b w. */
611 #define F_ISSET(w, f) (((w) & (f)) == (f))
613 /** Round \b n up to an even number. */
614 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
616 /** Used for offsets within a single page.
617 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
620 typedef uint16_t indx_t;
622 /** Default size of memory map.
623 * This is certainly too small for any actual applications. Apps should always set
624 * the size explicitly using #mdb_env_set_mapsize().
626 #define DEFAULT_MAPSIZE 1048576
628 /** @defgroup readers Reader Lock Table
629 * Readers don't acquire any locks for their data access. Instead, they
630 * simply record their transaction ID in the reader table. The reader
631 * mutex is needed just to find an empty slot in the reader table. The
632 * slot's address is saved in thread-specific data so that subsequent read
633 * transactions started by the same thread need no further locking to proceed.
635 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
637 * No reader table is used if the database is on a read-only filesystem, or
638 * if #MDB_NOLOCK is set.
640 * Since the database uses multi-version concurrency control, readers don't
641 * actually need any locking. This table is used to keep track of which
642 * readers are using data from which old transactions, so that we'll know
643 * when a particular old transaction is no longer in use. Old transactions
644 * that have discarded any data pages can then have those pages reclaimed
645 * for use by a later write transaction.
647 * The lock table is constructed such that reader slots are aligned with the
648 * processor's cache line size. Any slot is only ever used by one thread.
649 * This alignment guarantees that there will be no contention or cache
650 * thrashing as threads update their own slot info, and also eliminates
651 * any need for locking when accessing a slot.
653 * A writer thread will scan every slot in the table to determine the oldest
654 * outstanding reader transaction. Any freed pages older than this will be
655 * reclaimed by the writer. The writer doesn't use any locks when scanning
656 * this table. This means that there's no guarantee that the writer will
657 * see the most up-to-date reader info, but that's not required for correct
658 * operation - all we need is to know the upper bound on the oldest reader,
659 * we don't care at all about the newest reader. So the only consequence of
660 * reading stale information here is that old pages might hang around a
661 * while longer before being reclaimed. That's actually good anyway, because
662 * the longer we delay reclaiming old pages, the more likely it is that a
663 * string of contiguous pages can be found after coalescing old pages from
664 * many old transactions together.
667 /** Number of slots in the reader table.
668 * This value was chosen somewhat arbitrarily. 126 readers plus a
669 * couple mutexes fit exactly into 8KB on my development machine.
670 * Applications should set the table size using #mdb_env_set_maxreaders().
672 #define DEFAULT_READERS 126
674 /** The size of a CPU cache line in bytes. We want our lock structures
675 * aligned to this size to avoid false cache line sharing in the
677 * This value works for most CPUs. For Itanium this should be 128.
683 /** The information we store in a single slot of the reader table.
684 * In addition to a transaction ID, we also record the process and
685 * thread ID that owns a slot, so that we can detect stale information,
686 * e.g. threads or processes that went away without cleaning up.
687 * @note We currently don't check for stale records. We simply re-init
688 * the table when we know that we're the only process opening the
691 typedef struct MDB_rxbody {
692 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
693 * Multiple readers that start at the same time will probably have the
694 * same ID here. Again, it's not important to exclude them from
695 * anything; all we need to know is which version of the DB they
696 * started from so we can avoid overwriting any data used in that
697 * particular version.
699 volatile txnid_t mrb_txnid;
700 /** The process ID of the process owning this reader txn. */
701 volatile MDB_PID_T mrb_pid;
702 /** The thread ID of the thread owning this txn. */
703 volatile MDB_THR_T mrb_tid;
706 /** The actual reader record, with cacheline padding. */
707 typedef struct MDB_reader {
710 /** shorthand for mrb_txnid */
711 #define mr_txnid mru.mrx.mrb_txnid
712 #define mr_pid mru.mrx.mrb_pid
713 #define mr_tid mru.mrx.mrb_tid
714 /** cache line alignment */
715 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
719 /** The header for the reader table.
720 * The table resides in a memory-mapped file. (This is a different file
721 * than is used for the main database.)
723 * For POSIX the actual mutexes reside in the shared memory of this
724 * mapped file. On Windows, mutexes are named objects allocated by the
725 * kernel; we store the mutex names in this mapped file so that other
726 * processes can grab them. This same approach is also used on
727 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
728 * process-shared POSIX mutexes. For these cases where a named object
729 * is used, the object name is derived from a 64 bit FNV hash of the
730 * environment pathname. As such, naming collisions are extremely
731 * unlikely. If a collision occurs, the results are unpredictable.
733 typedef struct MDB_txbody {
734 /** Stamp identifying this as an LMDB file. It must be set
737 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
739 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
740 char mtb_rmname[MNAME_LEN];
741 #elif defined(MDB_USE_SYSV_SEM)
745 /** Mutex protecting access to this table.
746 * This is the reader table lock used with LOCK_MUTEX().
748 mdb_mutex_t mtb_rmutex;
750 /** The ID of the last transaction committed to the database.
751 * This is recorded here only for convenience; the value can always
752 * be determined by reading the main database meta pages.
754 volatile txnid_t mtb_txnid;
755 /** The number of slots that have been used in the reader table.
756 * This always records the maximum count, it is not decremented
757 * when readers release their slots.
759 volatile unsigned mtb_numreaders;
762 /** The actual reader table definition. */
763 typedef struct MDB_txninfo {
766 #define mti_magic mt1.mtb.mtb_magic
767 #define mti_format mt1.mtb.mtb_format
768 #define mti_rmutex mt1.mtb.mtb_rmutex
769 #define mti_rmname mt1.mtb.mtb_rmname
770 #define mti_txnid mt1.mtb.mtb_txnid
771 #define mti_numreaders mt1.mtb.mtb_numreaders
772 #ifdef MDB_USE_SYSV_SEM
773 #define mti_semid mt1.mtb.mtb_semid
774 #define mti_rlocked mt1.mtb.mtb_rlocked
776 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
779 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
780 char mt2_wmname[MNAME_LEN];
781 #define mti_wmname mt2.mt2_wmname
782 #elif defined MDB_USE_SYSV_SEM
784 #define mti_wlocked mt2.mt2_wlocked
786 mdb_mutex_t mt2_wmutex;
787 #define mti_wmutex mt2.mt2_wmutex
789 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
791 MDB_reader mti_readers[1];
794 /** Lockfile format signature: version, features and field layout */
795 #define MDB_LOCK_FORMAT \
797 ((MDB_LOCK_VERSION) \
798 /* Flags which describe functionality */ \
799 + (SYSV_SEM_FLAG << 18) \
800 + (((MDB_PIDLOCK) != 0) << 16)))
803 /** Common header for all page types.
804 * Overflow records occupy a number of contiguous pages with no
805 * headers on any page after the first.
807 typedef struct MDB_page {
808 #define mp_pgno mp_p.p_pgno
809 #define mp_next mp_p.p_next
811 pgno_t p_pgno; /**< page number */
812 struct MDB_page *p_next; /**< for in-memory list of freed pages */
815 /** @defgroup mdb_page Page Flags
817 * Flags for the page headers.
820 #define P_BRANCH 0x01 /**< branch page */
821 #define P_LEAF 0x02 /**< leaf page */
822 #define P_OVERFLOW 0x04 /**< overflow page */
823 #define P_META 0x08 /**< meta page */
824 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
825 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
826 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
827 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
828 #define P_KEEP 0x8000 /**< leave this page alone during spill */
830 uint16_t mp_flags; /**< @ref mdb_page */
831 #define mp_lower mp_pb.pb.pb_lower
832 #define mp_upper mp_pb.pb.pb_upper
833 #define mp_pages mp_pb.pb_pages
836 indx_t pb_lower; /**< lower bound of free space */
837 indx_t pb_upper; /**< upper bound of free space */
839 uint32_t pb_pages; /**< number of overflow pages */
841 indx_t mp_ptrs[1]; /**< dynamic size */
844 /** Size of the page header, excluding dynamic data at the end */
845 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
847 /** Address of first usable data byte in a page, after the header */
848 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
850 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
851 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
853 /** Number of nodes on a page */
854 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
856 /** The amount of space remaining in the page */
857 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
859 /** The percentage of space used in the page, in tenths of a percent. */
860 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
861 ((env)->me_psize - PAGEHDRSZ))
862 /** The minimum page fill factor, in tenths of a percent.
863 * Pages emptier than this are candidates for merging.
865 #define FILL_THRESHOLD 250
867 /** Test if a page is a leaf page */
868 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
869 /** Test if a page is a LEAF2 page */
870 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
871 /** Test if a page is a branch page */
872 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
873 /** Test if a page is an overflow page */
874 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
875 /** Test if a page is a sub page */
876 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
878 /** The number of overflow pages needed to store the given size. */
879 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
881 /** Link in #MDB_txn.%mt_loose_pgs list */
882 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
884 /** Header for a single key/data pair within a page.
885 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
886 * We guarantee 2-byte alignment for 'MDB_node's.
888 typedef struct MDB_node {
889 /** lo and hi are used for data size on leaf nodes and for
890 * child pgno on branch nodes. On 64 bit platforms, flags
891 * is also used for pgno. (Branch nodes have no flags).
892 * They are in host byte order in case that lets some
893 * accesses be optimized into a 32-bit word access.
895 #if BYTE_ORDER == LITTLE_ENDIAN
896 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
898 unsigned short mn_hi, mn_lo;
900 /** @defgroup mdb_node Node Flags
902 * Flags for node headers.
905 #define F_BIGDATA 0x01 /**< data put on overflow page */
906 #define F_SUBDATA 0x02 /**< data is a sub-database */
907 #define F_DUPDATA 0x04 /**< data has duplicates */
909 /** valid flags for #mdb_node_add() */
910 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
913 unsigned short mn_flags; /**< @ref mdb_node */
914 unsigned short mn_ksize; /**< key size */
915 char mn_data[1]; /**< key and data are appended here */
918 /** Size of the node header, excluding dynamic data at the end */
919 #define NODESIZE offsetof(MDB_node, mn_data)
921 /** Bit position of top word in page number, for shifting mn_flags */
922 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
924 /** Size of a node in a branch page with a given key.
925 * This is just the node header plus the key, there is no data.
927 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
929 /** Size of a node in a leaf page with a given key and data.
930 * This is node header plus key plus data size.
932 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
934 /** Address of node \b i in page \b p */
935 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
937 /** Address of the key for the node */
938 #define NODEKEY(node) (void *)((node)->mn_data)
940 /** Address of the data for a node */
941 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
943 /** Get the page number pointed to by a branch node */
944 #define NODEPGNO(node) \
945 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
946 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
947 /** Set the page number in a branch node */
948 #define SETPGNO(node,pgno) do { \
949 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
950 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
952 /** Get the size of the data in a leaf node */
953 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
954 /** Set the size of the data for a leaf node */
955 #define SETDSZ(node,size) do { \
956 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
957 /** The size of a key in a node */
958 #define NODEKSZ(node) ((node)->mn_ksize)
960 /** Copy a page number from src to dst */
962 #define COPY_PGNO(dst,src) dst = src
964 #if SIZE_MAX > 4294967295UL
965 #define COPY_PGNO(dst,src) do { \
966 unsigned short *s, *d; \
967 s = (unsigned short *)&(src); \
968 d = (unsigned short *)&(dst); \
975 #define COPY_PGNO(dst,src) do { \
976 unsigned short *s, *d; \
977 s = (unsigned short *)&(src); \
978 d = (unsigned short *)&(dst); \
984 /** The address of a key in a LEAF2 page.
985 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
986 * There are no node headers, keys are stored contiguously.
988 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
990 /** Set the \b node's key into \b keyptr, if requested. */
991 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
992 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
994 /** Set the \b node's key into \b key. */
995 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
997 /** Information about a single database in the environment. */
998 typedef struct MDB_db {
999 uint32_t md_pad; /**< also ksize for LEAF2 pages */
1000 uint16_t md_flags; /**< @ref mdb_dbi_open */
1001 uint16_t md_depth; /**< depth of this tree */
1002 pgno_t md_branch_pages; /**< number of internal pages */
1003 pgno_t md_leaf_pages; /**< number of leaf pages */
1004 pgno_t md_overflow_pages; /**< number of overflow pages */
1005 size_t md_entries; /**< number of data items */
1006 pgno_t md_root; /**< the root page of this tree */
1009 /** mdb_dbi_open flags */
1010 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
1011 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
1012 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
1013 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
1015 /** Handle for the DB used to track free pages. */
1017 /** Handle for the default DB. */
1019 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
1022 /** Number of meta pages - also hardcoded elsewhere */
1025 /** Meta page content.
1026 * A meta page is the start point for accessing a database snapshot.
1027 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
1029 typedef struct MDB_meta {
1030 /** Stamp identifying this as an LMDB file. It must be set
1033 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
1034 uint32_t mm_version;
1035 void *mm_address; /**< address for fixed mapping */
1036 size_t mm_mapsize; /**< size of mmap region */
1037 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
1038 /** The size of pages used in this DB */
1039 #define mm_psize mm_dbs[FREE_DBI].md_pad
1040 /** Any persistent environment flags. @ref mdb_env */
1041 #define mm_flags mm_dbs[FREE_DBI].md_flags
1042 pgno_t mm_last_pg; /**< last used page in file */
1043 volatile txnid_t mm_txnid; /**< txnid that committed this page */
1046 /** Buffer for a stack-allocated meta page.
1047 * The members define size and alignment, and silence type
1048 * aliasing warnings. They are not used directly; that could
1049 * mean incorrectly using several union members in parallel.
1051 typedef union MDB_metabuf {
1054 char mm_pad[PAGEHDRSZ];
1059 /** Auxiliary DB info.
1060 * The information here is mostly static/read-only. There is
1061 * only a single copy of this record in the environment.
1063 typedef struct MDB_dbx {
1064 MDB_val md_name; /**< name of the database */
1065 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1066 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1067 MDB_rel_func *md_rel; /**< user relocate function */
1068 void *md_relctx; /**< user-provided context for md_rel */
1071 /** A database transaction.
1072 * Every operation requires a transaction handle.
1075 MDB_txn *mt_parent; /**< parent of a nested txn */
1076 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1078 pgno_t mt_next_pgno; /**< next unallocated page */
1079 /** The ID of this transaction. IDs are integers incrementing from 1.
1080 * Only committed write transactions increment the ID. If a transaction
1081 * aborts, the ID may be re-used by the next writer.
1084 MDB_env *mt_env; /**< the DB environment */
1085 /** The list of pages that became unused during this transaction.
1087 MDB_IDL mt_free_pgs;
1088 /** The list of loose pages that became unused and may be reused
1089 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1091 MDB_page *mt_loose_pgs;
1092 /* #Number of loose pages (#mt_loose_pgs) */
1094 /** The sorted list of dirty pages we temporarily wrote to disk
1095 * because the dirty list was full. page numbers in here are
1096 * shifted left by 1, deleted slots have the LSB set.
1098 MDB_IDL mt_spill_pgs;
1100 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1101 MDB_ID2L dirty_list;
1102 /** For read txns: This thread/txn's reader table slot, or NULL. */
1105 /** Array of records for each DB known in the environment. */
1107 /** Array of MDB_db records for each known DB */
1109 /** Array of sequence numbers for each DB handle */
1110 unsigned int *mt_dbiseqs;
1111 /** @defgroup mt_dbflag Transaction DB Flags
1115 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
1116 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1117 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1118 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1119 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1121 /** In write txns, array of cursors for each DB */
1122 MDB_cursor **mt_cursors;
1123 /** Array of flags for each DB */
1124 unsigned char *mt_dbflags;
1125 /** Number of DB records in use, or 0 when the txn is finished.
1126 * This number only ever increments until the txn finishes; we
1127 * don't decrement it when individual DB handles are closed.
1131 /** @defgroup mdb_txn Transaction Flags
1135 /** #mdb_txn_begin() flags */
1136 #define MDB_TXN_BEGIN_FLAGS (MDB_NOMETASYNC|MDB_NOSYNC|MDB_RDONLY)
1137 #define MDB_TXN_NOMETASYNC MDB_NOMETASYNC /**< don't sync meta for this txn on commit */
1138 #define MDB_TXN_NOSYNC MDB_NOSYNC /**< don't sync this txn on commit */
1139 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1140 /* internal txn flags */
1141 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1142 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1143 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1144 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1145 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1146 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1147 /** most operations on the txn are currently illegal */
1148 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1150 unsigned int mt_flags; /**< @ref mdb_txn */
1151 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1152 * Includes ancestor txns' dirty pages not hidden by other txns'
1153 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1154 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1156 unsigned int mt_dirty_room;
1159 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1160 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1161 * raise this on a 64 bit machine.
1163 #define CURSOR_STACK 32
1167 /** Cursors are used for all DB operations.
1168 * A cursor holds a path of (page pointer, key index) from the DB
1169 * root to a position in the DB, plus other state. #MDB_DUPSORT
1170 * cursors include an xcursor to the current data item. Write txns
1171 * track their cursors and keep them up to date when data moves.
1172 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1173 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1176 /** Next cursor on this DB in this txn */
1177 MDB_cursor *mc_next;
1178 /** Backup of the original cursor if this cursor is a shadow */
1179 MDB_cursor *mc_backup;
1180 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1181 struct MDB_xcursor *mc_xcursor;
1182 /** The transaction that owns this cursor */
1184 /** The database handle this cursor operates on */
1186 /** The database record for this cursor */
1188 /** The database auxiliary record for this cursor */
1190 /** The @ref mt_dbflag for this database */
1191 unsigned char *mc_dbflag;
1192 unsigned short mc_snum; /**< number of pushed pages */
1193 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1194 /** @defgroup mdb_cursor Cursor Flags
1196 * Cursor state flags.
1199 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1200 #define C_EOF 0x02 /**< No more data */
1201 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1202 #define C_DEL 0x08 /**< last op was a cursor_del */
1203 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
1204 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1206 unsigned int mc_flags; /**< @ref mdb_cursor */
1207 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1208 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1211 /** Context for sorted-dup records.
1212 * We could have gone to a fully recursive design, with arbitrarily
1213 * deep nesting of sub-databases. But for now we only handle these
1214 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1216 typedef struct MDB_xcursor {
1217 /** A sub-cursor for traversing the Dup DB */
1218 MDB_cursor mx_cursor;
1219 /** The database record for this Dup DB */
1221 /** The auxiliary DB record for this Dup DB */
1223 /** The @ref mt_dbflag for this Dup DB */
1224 unsigned char mx_dbflag;
1227 /** State of FreeDB old pages, stored in the MDB_env */
1228 typedef struct MDB_pgstate {
1229 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1230 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1233 /** The database environment. */
1235 HANDLE me_fd; /**< The main data file */
1236 HANDLE me_lfd; /**< The lock file */
1237 HANDLE me_mfd; /**< just for writing the meta pages */
1238 /** Failed to update the meta page. Probably an I/O error. */
1239 #define MDB_FATAL_ERROR 0x80000000U
1240 /** Some fields are initialized. */
1241 #define MDB_ENV_ACTIVE 0x20000000U
1242 /** me_txkey is set */
1243 #define MDB_ENV_TXKEY 0x10000000U
1244 /** fdatasync is unreliable */
1245 #define MDB_FSYNCONLY 0x08000000U
1246 uint32_t me_flags; /**< @ref mdb_env */
1247 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1248 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1249 unsigned int me_maxreaders; /**< size of the reader table */
1250 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1251 volatile int me_close_readers;
1252 MDB_dbi me_numdbs; /**< number of DBs opened */
1253 MDB_dbi me_maxdbs; /**< size of the DB table */
1254 MDB_PID_T me_pid; /**< process ID of this env */
1255 char *me_path; /**< path to the DB files */
1256 char *me_map; /**< the memory map of the data file */
1257 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1258 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1259 void *me_pbuf; /**< scratch area for DUPSORT put() */
1260 MDB_txn *me_txn; /**< current write transaction */
1261 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1262 size_t me_mapsize; /**< size of the data memory map */
1263 off_t me_size; /**< current file size */
1264 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1265 MDB_dbx *me_dbxs; /**< array of static DB info */
1266 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1267 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1268 pthread_key_t me_txkey; /**< thread-key for readers */
1269 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1270 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1271 # define me_pglast me_pgstate.mf_pglast
1272 # define me_pghead me_pgstate.mf_pghead
1273 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1274 /** IDL of pages that became unused in a write txn */
1275 MDB_IDL me_free_pgs;
1276 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1277 MDB_ID2L me_dirty_list;
1278 /** Max number of freelist items that can fit in a single overflow page */
1280 /** Max size of a node on a page */
1281 unsigned int me_nodemax;
1282 #if !(MDB_MAXKEYSIZE)
1283 unsigned int me_maxkey; /**< max size of a key */
1285 int me_live_reader; /**< have liveness lock in reader table */
1287 int me_pidquery; /**< Used in OpenProcess */
1289 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1290 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1291 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1293 mdb_mutex_t me_rmutex;
1294 mdb_mutex_t me_wmutex;
1296 void *me_userctx; /**< User-settable context */
1297 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1300 /** Nested transaction */
1301 typedef struct MDB_ntxn {
1302 MDB_txn mnt_txn; /**< the transaction */
1303 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1306 /** max number of pages to commit in one writev() call */
1307 #define MDB_COMMIT_PAGES 64
1308 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1309 #undef MDB_COMMIT_PAGES
1310 #define MDB_COMMIT_PAGES IOV_MAX
1313 /** max bytes to write in one call */
1314 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1316 /** Check \b txn and \b dbi arguments to a function */
1317 #define TXN_DBI_EXIST(txn, dbi, validity) \
1318 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1320 /** Check for misused \b dbi handles */
1321 #define TXN_DBI_CHANGED(txn, dbi) \
1322 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1324 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1325 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1326 static int mdb_page_touch(MDB_cursor *mc);
1328 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1329 "reset-tmp", "fail-begin", "fail-beginchild"}
1331 /* mdb_txn_end operation number, for logging */
1332 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1333 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1335 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1336 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1337 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1338 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1339 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1341 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1342 static int mdb_page_search_root(MDB_cursor *mc,
1343 MDB_val *key, int modify);
1344 #define MDB_PS_MODIFY 1
1345 #define MDB_PS_ROOTONLY 2
1346 #define MDB_PS_FIRST 4
1347 #define MDB_PS_LAST 8
1348 static int mdb_page_search(MDB_cursor *mc,
1349 MDB_val *key, int flags);
1350 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1352 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1353 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1354 pgno_t newpgno, unsigned int nflags);
1356 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1357 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1358 static int mdb_env_write_meta(MDB_txn *txn);
1359 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1360 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1362 static void mdb_env_close0(MDB_env *env, int excl);
1364 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1365 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1366 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1367 static void mdb_node_del(MDB_cursor *mc, int ksize);
1368 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1369 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1370 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1371 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1372 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1374 static int mdb_rebalance(MDB_cursor *mc);
1375 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1377 static void mdb_cursor_pop(MDB_cursor *mc);
1378 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1380 static int mdb_cursor_del0(MDB_cursor *mc);
1381 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1382 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1383 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1384 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1385 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1387 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1388 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1390 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1391 static void mdb_xcursor_init0(MDB_cursor *mc);
1392 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1393 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1395 static int mdb_drop0(MDB_cursor *mc, int subs);
1396 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1397 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1400 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1403 /** Compare two items pointing at size_t's of unknown alignment. */
1404 #ifdef MISALIGNED_OK
1405 # define mdb_cmp_clong mdb_cmp_long
1407 # define mdb_cmp_clong mdb_cmp_cint
1411 static SECURITY_DESCRIPTOR mdb_null_sd;
1412 static SECURITY_ATTRIBUTES mdb_all_sa;
1413 static int mdb_sec_inited;
1416 /** Return the library version info. */
1418 mdb_version(int *major, int *minor, int *patch)
1420 if (major) *major = MDB_VERSION_MAJOR;
1421 if (minor) *minor = MDB_VERSION_MINOR;
1422 if (patch) *patch = MDB_VERSION_PATCH;
1423 return MDB_VERSION_STRING;
1426 /** Table of descriptions for LMDB @ref errors */
1427 static char *const mdb_errstr[] = {
1428 "MDB_KEYEXIST: Key/data pair already exists",
1429 "MDB_NOTFOUND: No matching key/data pair found",
1430 "MDB_PAGE_NOTFOUND: Requested page not found",
1431 "MDB_CORRUPTED: Located page was wrong type",
1432 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1433 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1434 "MDB_INVALID: File is not an LMDB file",
1435 "MDB_MAP_FULL: Environment mapsize limit reached",
1436 "MDB_DBS_FULL: Environment maxdbs limit reached",
1437 "MDB_READERS_FULL: Environment maxreaders limit reached",
1438 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1439 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1440 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1441 "MDB_PAGE_FULL: Internal error - page has no more space",
1442 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1443 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1444 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1445 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1446 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1447 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1451 mdb_strerror(int err)
1454 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1455 * This works as long as no function between the call to mdb_strerror
1456 * and the actual use of the message uses more than 4K of stack.
1459 char buf[1024], *ptr = buf;
1463 return ("Successful return: 0");
1465 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1466 i = err - MDB_KEYEXIST;
1467 return mdb_errstr[i];
1471 /* These are the C-runtime error codes we use. The comment indicates
1472 * their numeric value, and the Win32 error they would correspond to
1473 * if the error actually came from a Win32 API. A major mess, we should
1474 * have used LMDB-specific error codes for everything.
1477 case ENOENT: /* 2, FILE_NOT_FOUND */
1478 case EIO: /* 5, ACCESS_DENIED */
1479 case ENOMEM: /* 12, INVALID_ACCESS */
1480 case EACCES: /* 13, INVALID_DATA */
1481 case EBUSY: /* 16, CURRENT_DIRECTORY */
1482 case EINVAL: /* 22, BAD_COMMAND */
1483 case ENOSPC: /* 28, OUT_OF_PAPER */
1484 return strerror(err);
1489 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1490 FORMAT_MESSAGE_IGNORE_INSERTS,
1491 NULL, err, 0, ptr, sizeof(buf), (va_list *)pad);
1494 return strerror(err);
1498 /** assert(3) variant in cursor context */
1499 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1500 /** assert(3) variant in transaction context */
1501 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1502 /** assert(3) variant in environment context */
1503 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1506 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1507 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1510 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1511 const char *func, const char *file, int line)
1514 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1515 file, line, expr_txt, func);
1516 if (env->me_assert_func)
1517 env->me_assert_func(env, buf);
1518 fprintf(stderr, "%s\n", buf);
1522 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1526 /** Return the page number of \b mp which may be sub-page, for debug output */
1528 mdb_dbg_pgno(MDB_page *mp)
1531 COPY_PGNO(ret, mp->mp_pgno);
1535 /** Display a key in hexadecimal and return the address of the result.
1536 * @param[in] key the key to display
1537 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1538 * @return The key in hexadecimal form.
1541 mdb_dkey(MDB_val *key, char *buf)
1544 unsigned char *c = key->mv_data;
1550 if (key->mv_size > DKBUF_MAXKEYSIZE)
1551 return "MDB_MAXKEYSIZE";
1552 /* may want to make this a dynamic check: if the key is mostly
1553 * printable characters, print it as-is instead of converting to hex.
1557 for (i=0; i<key->mv_size; i++)
1558 ptr += sprintf(ptr, "%02x", *c++);
1560 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1566 mdb_leafnode_type(MDB_node *n)
1568 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1569 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1570 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1573 /** Display all the keys in the page. */
1575 mdb_page_list(MDB_page *mp)
1577 pgno_t pgno = mdb_dbg_pgno(mp);
1578 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1580 unsigned int i, nkeys, nsize, total = 0;
1584 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1585 case P_BRANCH: type = "Branch page"; break;
1586 case P_LEAF: type = "Leaf page"; break;
1587 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1588 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1589 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1591 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1592 pgno, mp->mp_pages, state);
1595 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1596 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1599 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1603 nkeys = NUMKEYS(mp);
1604 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1606 for (i=0; i<nkeys; i++) {
1607 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1608 key.mv_size = nsize = mp->mp_pad;
1609 key.mv_data = LEAF2KEY(mp, i, nsize);
1611 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1614 node = NODEPTR(mp, i);
1615 key.mv_size = node->mn_ksize;
1616 key.mv_data = node->mn_data;
1617 nsize = NODESIZE + key.mv_size;
1618 if (IS_BRANCH(mp)) {
1619 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1623 if (F_ISSET(node->mn_flags, F_BIGDATA))
1624 nsize += sizeof(pgno_t);
1626 nsize += NODEDSZ(node);
1628 nsize += sizeof(indx_t);
1629 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1630 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1632 total = EVEN(total);
1634 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1635 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1639 mdb_cursor_chk(MDB_cursor *mc)
1645 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1646 for (i=0; i<mc->mc_top; i++) {
1648 node = NODEPTR(mp, mc->mc_ki[i]);
1649 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1652 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1658 /** Count all the pages in each DB and in the freelist
1659 * and make sure it matches the actual number of pages
1661 * All named DBs must be open for a correct count.
1663 static void mdb_audit(MDB_txn *txn)
1667 MDB_ID freecount, count;
1672 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1673 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1674 freecount += *(MDB_ID *)data.mv_data;
1675 mdb_tassert(txn, rc == MDB_NOTFOUND);
1678 for (i = 0; i<txn->mt_numdbs; i++) {
1680 if (!(txn->mt_dbflags[i] & DB_VALID))
1682 mdb_cursor_init(&mc, txn, i, &mx);
1683 if (txn->mt_dbs[i].md_root == P_INVALID)
1685 count += txn->mt_dbs[i].md_branch_pages +
1686 txn->mt_dbs[i].md_leaf_pages +
1687 txn->mt_dbs[i].md_overflow_pages;
1688 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1689 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1690 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1693 mp = mc.mc_pg[mc.mc_top];
1694 for (j=0; j<NUMKEYS(mp); j++) {
1695 MDB_node *leaf = NODEPTR(mp, j);
1696 if (leaf->mn_flags & F_SUBDATA) {
1698 memcpy(&db, NODEDATA(leaf), sizeof(db));
1699 count += db.md_branch_pages + db.md_leaf_pages +
1700 db.md_overflow_pages;
1704 mdb_tassert(txn, rc == MDB_NOTFOUND);
1707 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1708 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1709 txn->mt_txnid, freecount, count+NUM_METAS,
1710 freecount+count+NUM_METAS, txn->mt_next_pgno);
1716 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1718 return txn->mt_dbxs[dbi].md_cmp(a, b);
1722 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1724 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1725 #if UINT_MAX < SIZE_MAX
1726 if (dcmp == mdb_cmp_int && a->mv_size == sizeof(size_t))
1727 dcmp = mdb_cmp_clong;
1732 /** Allocate memory for a page.
1733 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1736 mdb_page_malloc(MDB_txn *txn, unsigned num)
1738 MDB_env *env = txn->mt_env;
1739 MDB_page *ret = env->me_dpages;
1740 size_t psize = env->me_psize, sz = psize, off;
1741 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1742 * For a single page alloc, we init everything after the page header.
1743 * For multi-page, we init the final page; if the caller needed that
1744 * many pages they will be filling in at least up to the last page.
1748 VGMEMP_ALLOC(env, ret, sz);
1749 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1750 env->me_dpages = ret->mp_next;
1753 psize -= off = PAGEHDRSZ;
1758 if ((ret = malloc(sz)) != NULL) {
1759 VGMEMP_ALLOC(env, ret, sz);
1760 if (!(env->me_flags & MDB_NOMEMINIT)) {
1761 memset((char *)ret + off, 0, psize);
1765 txn->mt_flags |= MDB_TXN_ERROR;
1769 /** Free a single page.
1770 * Saves single pages to a list, for future reuse.
1771 * (This is not used for multi-page overflow pages.)
1774 mdb_page_free(MDB_env *env, MDB_page *mp)
1776 mp->mp_next = env->me_dpages;
1777 VGMEMP_FREE(env, mp);
1778 env->me_dpages = mp;
1781 /** Free a dirty page */
1783 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1785 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1786 mdb_page_free(env, dp);
1788 /* large pages just get freed directly */
1789 VGMEMP_FREE(env, dp);
1794 /** Return all dirty pages to dpage list */
1796 mdb_dlist_free(MDB_txn *txn)
1798 MDB_env *env = txn->mt_env;
1799 MDB_ID2L dl = txn->mt_u.dirty_list;
1800 unsigned i, n = dl[0].mid;
1802 for (i = 1; i <= n; i++) {
1803 mdb_dpage_free(env, dl[i].mptr);
1808 /** Loosen or free a single page.
1809 * Saves single pages to a list for future reuse
1810 * in this same txn. It has been pulled from the freeDB
1811 * and already resides on the dirty list, but has been
1812 * deleted. Use these pages first before pulling again
1815 * If the page wasn't dirtied in this txn, just add it
1816 * to this txn's free list.
1819 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1822 pgno_t pgno = mp->mp_pgno;
1823 MDB_txn *txn = mc->mc_txn;
1825 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1826 if (txn->mt_parent) {
1827 MDB_ID2 *dl = txn->mt_u.dirty_list;
1828 /* If txn has a parent, make sure the page is in our
1832 unsigned x = mdb_mid2l_search(dl, pgno);
1833 if (x <= dl[0].mid && dl[x].mid == pgno) {
1834 if (mp != dl[x].mptr) { /* bad cursor? */
1835 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1836 txn->mt_flags |= MDB_TXN_ERROR;
1837 return MDB_CORRUPTED;
1844 /* no parent txn, so it's just ours */
1849 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1851 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1852 txn->mt_loose_pgs = mp;
1853 txn->mt_loose_count++;
1854 mp->mp_flags |= P_LOOSE;
1856 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1864 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1865 * @param[in] mc A cursor handle for the current operation.
1866 * @param[in] pflags Flags of the pages to update:
1867 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1868 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1869 * @return 0 on success, non-zero on failure.
1872 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1874 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1875 MDB_txn *txn = mc->mc_txn;
1881 int rc = MDB_SUCCESS, level;
1883 /* Mark pages seen by cursors */
1884 if (mc->mc_flags & C_UNTRACK)
1885 mc = NULL; /* will find mc in mt_cursors */
1886 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1887 for (; mc; mc=mc->mc_next) {
1888 if (!(mc->mc_flags & C_INITIALIZED))
1890 for (m3 = mc;; m3 = &mx->mx_cursor) {
1892 for (j=0; j<m3->mc_snum; j++) {
1894 if ((mp->mp_flags & Mask) == pflags)
1895 mp->mp_flags ^= P_KEEP;
1897 mx = m3->mc_xcursor;
1898 /* Proceed to mx if it is at a sub-database */
1899 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1901 if (! (mp && (mp->mp_flags & P_LEAF)))
1903 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1904 if (!(leaf->mn_flags & F_SUBDATA))
1913 /* Mark dirty root pages */
1914 for (i=0; i<txn->mt_numdbs; i++) {
1915 if (txn->mt_dbflags[i] & DB_DIRTY) {
1916 pgno_t pgno = txn->mt_dbs[i].md_root;
1917 if (pgno == P_INVALID)
1919 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1921 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1922 dp->mp_flags ^= P_KEEP;
1930 static int mdb_page_flush(MDB_txn *txn, int keep);
1932 /** Spill pages from the dirty list back to disk.
1933 * This is intended to prevent running into #MDB_TXN_FULL situations,
1934 * but note that they may still occur in a few cases:
1935 * 1) our estimate of the txn size could be too small. Currently this
1936 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1937 * 2) child txns may run out of space if their parents dirtied a
1938 * lot of pages and never spilled them. TODO: we probably should do
1939 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1940 * the parent's dirty_room is below a given threshold.
1942 * Otherwise, if not using nested txns, it is expected that apps will
1943 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1944 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1945 * If the txn never references them again, they can be left alone.
1946 * If the txn only reads them, they can be used without any fuss.
1947 * If the txn writes them again, they can be dirtied immediately without
1948 * going thru all of the work of #mdb_page_touch(). Such references are
1949 * handled by #mdb_page_unspill().
1951 * Also note, we never spill DB root pages, nor pages of active cursors,
1952 * because we'll need these back again soon anyway. And in nested txns,
1953 * we can't spill a page in a child txn if it was already spilled in a
1954 * parent txn. That would alter the parent txns' data even though
1955 * the child hasn't committed yet, and we'd have no way to undo it if
1956 * the child aborted.
1958 * @param[in] m0 cursor A cursor handle identifying the transaction and
1959 * database for which we are checking space.
1960 * @param[in] key For a put operation, the key being stored.
1961 * @param[in] data For a put operation, the data being stored.
1962 * @return 0 on success, non-zero on failure.
1965 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1967 MDB_txn *txn = m0->mc_txn;
1969 MDB_ID2L dl = txn->mt_u.dirty_list;
1970 unsigned int i, j, need;
1973 if (m0->mc_flags & C_SUB)
1976 /* Estimate how much space this op will take */
1977 i = m0->mc_db->md_depth;
1978 /* Named DBs also dirty the main DB */
1979 if (m0->mc_dbi >= CORE_DBS)
1980 i += txn->mt_dbs[MAIN_DBI].md_depth;
1981 /* For puts, roughly factor in the key+data size */
1983 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1984 i += i; /* double it for good measure */
1987 if (txn->mt_dirty_room > i)
1990 if (!txn->mt_spill_pgs) {
1991 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1992 if (!txn->mt_spill_pgs)
1995 /* purge deleted slots */
1996 MDB_IDL sl = txn->mt_spill_pgs;
1997 unsigned int num = sl[0];
1999 for (i=1; i<=num; i++) {
2006 /* Preserve pages which may soon be dirtied again */
2007 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2010 /* Less aggressive spill - we originally spilled the entire dirty list,
2011 * with a few exceptions for cursor pages and DB root pages. But this
2012 * turns out to be a lot of wasted effort because in a large txn many
2013 * of those pages will need to be used again. So now we spill only 1/8th
2014 * of the dirty pages. Testing revealed this to be a good tradeoff,
2015 * better than 1/2, 1/4, or 1/10.
2017 if (need < MDB_IDL_UM_MAX / 8)
2018 need = MDB_IDL_UM_MAX / 8;
2020 /* Save the page IDs of all the pages we're flushing */
2021 /* flush from the tail forward, this saves a lot of shifting later on. */
2022 for (i=dl[0].mid; i && need; i--) {
2023 MDB_ID pn = dl[i].mid << 1;
2025 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2027 /* Can't spill twice, make sure it's not already in a parent's
2030 if (txn->mt_parent) {
2032 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2033 if (tx2->mt_spill_pgs) {
2034 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2035 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2036 dp->mp_flags |= P_KEEP;
2044 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2048 mdb_midl_sort(txn->mt_spill_pgs);
2050 /* Flush the spilled part of dirty list */
2051 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2054 /* Reset any dirty pages we kept that page_flush didn't see */
2055 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2058 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2062 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2064 mdb_find_oldest(MDB_txn *txn)
2067 txnid_t mr, oldest = txn->mt_txnid - 1;
2068 if (txn->mt_env->me_txns) {
2069 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2070 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2081 /** Add a page to the txn's dirty list */
2083 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2086 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2088 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2089 insert = mdb_mid2l_append;
2091 insert = mdb_mid2l_insert;
2093 mid.mid = mp->mp_pgno;
2095 rc = insert(txn->mt_u.dirty_list, &mid);
2096 mdb_tassert(txn, rc == 0);
2097 txn->mt_dirty_room--;
2100 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2101 * me_pghead and mt_next_pgno.
2103 * If there are free pages available from older transactions, they
2104 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2105 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2106 * and move me_pglast to say which records were consumed. Only this
2107 * function can create me_pghead and move me_pglast/mt_next_pgno.
2108 * @param[in] mc cursor A cursor handle identifying the transaction and
2109 * database for which we are allocating.
2110 * @param[in] num the number of pages to allocate.
2111 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2112 * will always be satisfied by a single contiguous chunk of memory.
2113 * @return 0 on success, non-zero on failure.
2116 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2118 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2119 /* Get at most <Max_retries> more freeDB records once me_pghead
2120 * has enough pages. If not enough, use new pages from the map.
2121 * If <Paranoid> and mc is updating the freeDB, only get new
2122 * records if me_pghead is empty. Then the freelist cannot play
2123 * catch-up with itself by growing while trying to save it.
2125 enum { Paranoid = 1, Max_retries = 500 };
2127 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2129 int rc, retry = num * 60;
2130 MDB_txn *txn = mc->mc_txn;
2131 MDB_env *env = txn->mt_env;
2132 pgno_t pgno, *mop = env->me_pghead;
2133 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2135 txnid_t oldest = 0, last;
2140 /* If there are any loose pages, just use them */
2141 if (num == 1 && txn->mt_loose_pgs) {
2142 np = txn->mt_loose_pgs;
2143 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2144 txn->mt_loose_count--;
2145 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
2153 /* If our dirty list is already full, we can't do anything */
2154 if (txn->mt_dirty_room == 0) {
2159 for (op = MDB_FIRST;; op = MDB_NEXT) {
2164 /* Seek a big enough contiguous page range. Prefer
2165 * pages at the tail, just truncating the list.
2171 if (mop[i-n2] == pgno+n2)
2178 if (op == MDB_FIRST) { /* 1st iteration */
2179 /* Prepare to fetch more and coalesce */
2180 last = env->me_pglast;
2181 oldest = env->me_pgoldest;
2182 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2185 key.mv_data = &last; /* will look up last+1 */
2186 key.mv_size = sizeof(last);
2188 if (Paranoid && mc->mc_dbi == FREE_DBI)
2191 if (Paranoid && retry < 0 && mop_len)
2195 /* Do not fetch more if the record will be too recent */
2196 if (oldest <= last) {
2198 oldest = mdb_find_oldest(txn);
2199 env->me_pgoldest = oldest;
2205 rc = mdb_cursor_get(&m2, &key, NULL, op);
2207 if (rc == MDB_NOTFOUND)
2211 last = *(txnid_t*)key.mv_data;
2212 if (oldest <= last) {
2214 oldest = mdb_find_oldest(txn);
2215 env->me_pgoldest = oldest;
2221 np = m2.mc_pg[m2.mc_top];
2222 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2223 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
2226 idl = (MDB_ID *) data.mv_data;
2229 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2234 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2236 mop = env->me_pghead;
2238 env->me_pglast = last;
2240 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2241 last, txn->mt_dbs[FREE_DBI].md_root, i));
2243 DPRINTF(("IDL %"Z"u", idl[j]));
2245 /* Merge in descending sorted order */
2246 mdb_midl_xmerge(mop, idl);
2250 /* Use new pages from the map when nothing suitable in the freeDB */
2252 pgno = txn->mt_next_pgno;
2253 if (pgno + num >= env->me_maxpg) {
2254 DPUTS("DB size maxed out");
2260 if (env->me_flags & MDB_WRITEMAP) {
2261 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2263 if (!(np = mdb_page_malloc(txn, num))) {
2269 mop[0] = mop_len -= num;
2270 /* Move any stragglers down */
2271 for (j = i-num; j < mop_len; )
2272 mop[++j] = mop[++i];
2274 txn->mt_next_pgno = pgno + num;
2277 mdb_page_dirty(txn, np);
2283 txn->mt_flags |= MDB_TXN_ERROR;
2287 /** Copy the used portions of a non-overflow page.
2288 * @param[in] dst page to copy into
2289 * @param[in] src page to copy from
2290 * @param[in] psize size of a page
2293 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2295 enum { Align = sizeof(pgno_t) };
2296 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2298 /* If page isn't full, just copy the used portion. Adjust
2299 * alignment so memcpy may copy words instead of bytes.
2301 if ((unused &= -Align) && !IS_LEAF2(src)) {
2302 upper = (upper + PAGEBASE) & -Align;
2303 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2304 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2307 memcpy(dst, src, psize - unused);
2311 /** Pull a page off the txn's spill list, if present.
2312 * If a page being referenced was spilled to disk in this txn, bring
2313 * it back and make it dirty/writable again.
2314 * @param[in] txn the transaction handle.
2315 * @param[in] mp the page being referenced. It must not be dirty.
2316 * @param[out] ret the writable page, if any. ret is unchanged if
2317 * mp wasn't spilled.
2320 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2322 MDB_env *env = txn->mt_env;
2325 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2327 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2328 if (!tx2->mt_spill_pgs)
2330 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2331 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2334 if (txn->mt_dirty_room == 0)
2335 return MDB_TXN_FULL;
2336 if (IS_OVERFLOW(mp))
2340 if (env->me_flags & MDB_WRITEMAP) {
2343 np = mdb_page_malloc(txn, num);
2347 memcpy(np, mp, num * env->me_psize);
2349 mdb_page_copy(np, mp, env->me_psize);
2352 /* If in current txn, this page is no longer spilled.
2353 * If it happens to be the last page, truncate the spill list.
2354 * Otherwise mark it as deleted by setting the LSB.
2356 if (x == txn->mt_spill_pgs[0])
2357 txn->mt_spill_pgs[0]--;
2359 txn->mt_spill_pgs[x] |= 1;
2360 } /* otherwise, if belonging to a parent txn, the
2361 * page remains spilled until child commits
2364 mdb_page_dirty(txn, np);
2365 np->mp_flags |= P_DIRTY;
2373 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2374 * @param[in] mc cursor pointing to the page to be touched
2375 * @return 0 on success, non-zero on failure.
2378 mdb_page_touch(MDB_cursor *mc)
2380 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2381 MDB_txn *txn = mc->mc_txn;
2382 MDB_cursor *m2, *m3;
2386 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2387 if (txn->mt_flags & MDB_TXN_SPILLS) {
2389 rc = mdb_page_unspill(txn, mp, &np);
2395 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2396 (rc = mdb_page_alloc(mc, 1, &np)))
2399 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2400 mp->mp_pgno, pgno));
2401 mdb_cassert(mc, mp->mp_pgno != pgno);
2402 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2403 /* Update the parent page, if any, to point to the new page */
2405 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2406 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2407 SETPGNO(node, pgno);
2409 mc->mc_db->md_root = pgno;
2411 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2412 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2414 /* If txn has a parent, make sure the page is in our
2418 unsigned x = mdb_mid2l_search(dl, pgno);
2419 if (x <= dl[0].mid && dl[x].mid == pgno) {
2420 if (mp != dl[x].mptr) { /* bad cursor? */
2421 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2422 txn->mt_flags |= MDB_TXN_ERROR;
2423 return MDB_CORRUPTED;
2428 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2430 np = mdb_page_malloc(txn, 1);
2435 rc = mdb_mid2l_insert(dl, &mid);
2436 mdb_cassert(mc, rc == 0);
2441 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2443 np->mp_flags |= P_DIRTY;
2446 /* Adjust cursors pointing to mp */
2447 mc->mc_pg[mc->mc_top] = np;
2448 m2 = txn->mt_cursors[mc->mc_dbi];
2449 if (mc->mc_flags & C_SUB) {
2450 for (; m2; m2=m2->mc_next) {
2451 m3 = &m2->mc_xcursor->mx_cursor;
2452 if (m3->mc_snum < mc->mc_snum) continue;
2453 if (m3->mc_pg[mc->mc_top] == mp)
2454 m3->mc_pg[mc->mc_top] = np;
2457 for (; m2; m2=m2->mc_next) {
2458 if (m2->mc_snum < mc->mc_snum) continue;
2459 if (m2->mc_pg[mc->mc_top] == mp) {
2460 m2->mc_pg[mc->mc_top] = np;
2461 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2463 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2465 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2466 if (!(leaf->mn_flags & F_SUBDATA))
2467 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2475 txn->mt_flags |= MDB_TXN_ERROR;
2480 mdb_env_sync(MDB_env *env, int force)
2483 if (env->me_flags & MDB_RDONLY)
2485 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2486 if (env->me_flags & MDB_WRITEMAP) {
2487 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2488 ? MS_ASYNC : MS_SYNC;
2489 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2492 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2496 #ifdef BROKEN_FDATASYNC
2497 if (env->me_flags & MDB_FSYNCONLY) {
2498 if (fsync(env->me_fd))
2502 if (MDB_FDATASYNC(env->me_fd))
2509 /** Back up parent txn's cursors, then grab the originals for tracking */
2511 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2513 MDB_cursor *mc, *bk;
2518 for (i = src->mt_numdbs; --i >= 0; ) {
2519 if ((mc = src->mt_cursors[i]) != NULL) {
2520 size = sizeof(MDB_cursor);
2522 size += sizeof(MDB_xcursor);
2523 for (; mc; mc = bk->mc_next) {
2529 mc->mc_db = &dst->mt_dbs[i];
2530 /* Kill pointers into src - and dst to reduce abuse: The
2531 * user may not use mc until dst ends. Otherwise we'd...
2533 mc->mc_txn = NULL; /* ...set this to dst */
2534 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2535 if ((mx = mc->mc_xcursor) != NULL) {
2536 *(MDB_xcursor *)(bk+1) = *mx;
2537 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2539 mc->mc_next = dst->mt_cursors[i];
2540 dst->mt_cursors[i] = mc;
2547 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2548 * @param[in] txn the transaction handle.
2549 * @param[in] merge true to keep changes to parent cursors, false to revert.
2550 * @return 0 on success, non-zero on failure.
2553 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2555 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2559 for (i = txn->mt_numdbs; --i >= 0; ) {
2560 for (mc = cursors[i]; mc; mc = next) {
2562 if ((bk = mc->mc_backup) != NULL) {
2564 /* Commit changes to parent txn */
2565 mc->mc_next = bk->mc_next;
2566 mc->mc_backup = bk->mc_backup;
2567 mc->mc_txn = bk->mc_txn;
2568 mc->mc_db = bk->mc_db;
2569 mc->mc_dbflag = bk->mc_dbflag;
2570 if ((mx = mc->mc_xcursor) != NULL)
2571 mx->mx_cursor.mc_txn = bk->mc_txn;
2573 /* Abort nested txn */
2575 if ((mx = mc->mc_xcursor) != NULL)
2576 *mx = *(MDB_xcursor *)(bk+1);
2580 /* Only malloced cursors are permanently tracked. */
2587 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2593 Pidset = F_SETLK, Pidcheck = F_GETLK
2597 /** Set or check a pid lock. Set returns 0 on success.
2598 * Check returns 0 if the process is certainly dead, nonzero if it may
2599 * be alive (the lock exists or an error happened so we do not know).
2601 * On Windows Pidset is a no-op, we merely check for the existence
2602 * of the process with the given pid. On POSIX we use a single byte
2603 * lock on the lockfile, set at an offset equal to the pid.
2606 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2608 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2611 if (op == Pidcheck) {
2612 h = OpenProcess(env->me_pidquery, FALSE, pid);
2613 /* No documented "no such process" code, but other program use this: */
2615 return ErrCode() != ERROR_INVALID_PARAMETER;
2616 /* A process exists until all handles to it close. Has it exited? */
2617 ret = WaitForSingleObject(h, 0) != 0;
2624 struct flock lock_info;
2625 memset(&lock_info, 0, sizeof(lock_info));
2626 lock_info.l_type = F_WRLCK;
2627 lock_info.l_whence = SEEK_SET;
2628 lock_info.l_start = pid;
2629 lock_info.l_len = 1;
2630 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2631 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2633 } else if ((rc = ErrCode()) == EINTR) {
2641 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2642 * @param[in] txn the transaction handle to initialize
2643 * @return 0 on success, non-zero on failure.
2646 mdb_txn_renew0(MDB_txn *txn)
2648 MDB_env *env = txn->mt_env;
2649 MDB_txninfo *ti = env->me_txns;
2651 unsigned int i, nr, flags = txn->mt_flags;
2653 int rc, new_notls = 0;
2655 if ((flags &= MDB_TXN_RDONLY) != 0) {
2657 meta = mdb_env_pick_meta(env);
2658 txn->mt_txnid = meta->mm_txnid;
2659 txn->mt_u.reader = NULL;
2661 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2662 pthread_getspecific(env->me_txkey);
2664 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2665 return MDB_BAD_RSLOT;
2667 MDB_PID_T pid = env->me_pid;
2668 MDB_THR_T tid = pthread_self();
2669 mdb_mutexref_t rmutex = env->me_rmutex;
2671 if (!env->me_live_reader) {
2672 rc = mdb_reader_pid(env, Pidset, pid);
2675 env->me_live_reader = 1;
2678 if (LOCK_MUTEX(rc, env, rmutex))
2680 nr = ti->mti_numreaders;
2681 for (i=0; i<nr; i++)
2682 if (ti->mti_readers[i].mr_pid == 0)
2684 if (i == env->me_maxreaders) {
2685 UNLOCK_MUTEX(rmutex);
2686 return MDB_READERS_FULL;
2688 r = &ti->mti_readers[i];
2689 /* Claim the reader slot, carefully since other code
2690 * uses the reader table un-mutexed: First reset the
2691 * slot, next publish it in mti_numreaders. After
2692 * that, it is safe for mdb_env_close() to touch it.
2693 * When it will be closed, we can finally claim it.
2696 r->mr_txnid = (txnid_t)-1;
2699 ti->mti_numreaders = ++nr;
2700 env->me_close_readers = nr;
2702 UNLOCK_MUTEX(rmutex);
2704 new_notls = (env->me_flags & MDB_NOTLS);
2705 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2710 do /* LY: Retry on a race, ITS#7970. */
2711 r->mr_txnid = ti->mti_txnid;
2712 while(r->mr_txnid != ti->mti_txnid);
2713 txn->mt_txnid = r->mr_txnid;
2714 txn->mt_u.reader = r;
2715 meta = env->me_metas[txn->mt_txnid & 1];
2719 /* Not yet touching txn == env->me_txn0, it may be active */
2721 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2723 txn->mt_txnid = ti->mti_txnid;
2724 meta = env->me_metas[txn->mt_txnid & 1];
2726 meta = mdb_env_pick_meta(env);
2727 txn->mt_txnid = meta->mm_txnid;
2731 if (txn->mt_txnid == mdb_debug_start)
2734 txn->mt_child = NULL;
2735 txn->mt_loose_pgs = NULL;
2736 txn->mt_loose_count = 0;
2737 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2738 txn->mt_u.dirty_list = env->me_dirty_list;
2739 txn->mt_u.dirty_list[0].mid = 0;
2740 txn->mt_free_pgs = env->me_free_pgs;
2741 txn->mt_free_pgs[0] = 0;
2742 txn->mt_spill_pgs = NULL;
2744 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2747 /* Copy the DB info and flags */
2748 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
2750 /* Moved to here to avoid a data race in read TXNs */
2751 txn->mt_next_pgno = meta->mm_last_pg+1;
2753 txn->mt_flags = flags;
2756 txn->mt_numdbs = env->me_numdbs;
2757 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
2758 x = env->me_dbflags[i];
2759 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2760 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
2762 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
2763 txn->mt_dbflags[FREE_DBI] = DB_VALID;
2765 if (env->me_flags & MDB_FATAL_ERROR) {
2766 DPUTS("environment had fatal error, must shutdown!");
2768 } else if (env->me_maxpg < txn->mt_next_pgno) {
2769 rc = MDB_MAP_RESIZED;
2773 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
2778 mdb_txn_renew(MDB_txn *txn)
2782 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
2785 rc = mdb_txn_renew0(txn);
2786 if (rc == MDB_SUCCESS) {
2787 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2788 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2789 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2795 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2799 int rc, size, tsize;
2801 flags &= MDB_TXN_BEGIN_FLAGS;
2802 flags |= env->me_flags & MDB_WRITEMAP;
2804 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
2808 /* Nested transactions: Max 1 child, write txns only, no writemap */
2809 flags |= parent->mt_flags;
2810 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
2811 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2813 /* Child txns save MDB_pgstate and use own copy of cursors */
2814 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
2815 size += tsize = sizeof(MDB_ntxn);
2816 } else if (flags & MDB_RDONLY) {
2817 size = env->me_maxdbs * (sizeof(MDB_db)+1);
2818 size += tsize = sizeof(MDB_txn);
2820 /* Reuse preallocated write txn. However, do not touch it until
2821 * mdb_txn_renew0() succeeds, since it currently may be active.
2826 if ((txn = calloc(1, size)) == NULL) {
2827 DPRINTF(("calloc: %s", strerror(errno)));
2830 txn->mt_dbxs = env->me_dbxs; /* static */
2831 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2832 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
2833 txn->mt_flags = flags;
2838 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2839 txn->mt_dbiseqs = parent->mt_dbiseqs;
2840 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2841 if (!txn->mt_u.dirty_list ||
2842 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2844 free(txn->mt_u.dirty_list);
2848 txn->mt_txnid = parent->mt_txnid;
2849 txn->mt_dirty_room = parent->mt_dirty_room;
2850 txn->mt_u.dirty_list[0].mid = 0;
2851 txn->mt_spill_pgs = NULL;
2852 txn->mt_next_pgno = parent->mt_next_pgno;
2853 parent->mt_flags |= MDB_TXN_HAS_CHILD;
2854 parent->mt_child = txn;
2855 txn->mt_parent = parent;
2856 txn->mt_numdbs = parent->mt_numdbs;
2857 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2858 /* Copy parent's mt_dbflags, but clear DB_NEW */
2859 for (i=0; i<txn->mt_numdbs; i++)
2860 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2862 ntxn = (MDB_ntxn *)txn;
2863 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2864 if (env->me_pghead) {
2865 size = MDB_IDL_SIZEOF(env->me_pghead);
2866 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2868 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2873 rc = mdb_cursor_shadow(parent, txn);
2875 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
2876 } else { /* MDB_RDONLY */
2877 txn->mt_dbiseqs = env->me_dbiseqs;
2879 rc = mdb_txn_renew0(txn);
2882 if (txn != env->me_txn0)
2885 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
2887 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2888 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
2889 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2896 mdb_txn_env(MDB_txn *txn)
2898 if(!txn) return NULL;
2903 mdb_txn_id(MDB_txn *txn)
2906 return txn->mt_txnid;
2909 /** Export or close DBI handles opened in this txn. */
2911 mdb_dbis_update(MDB_txn *txn, int keep)
2914 MDB_dbi n = txn->mt_numdbs;
2915 MDB_env *env = txn->mt_env;
2916 unsigned char *tdbflags = txn->mt_dbflags;
2918 for (i = n; --i >= CORE_DBS;) {
2919 if (tdbflags[i] & DB_NEW) {
2921 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2923 char *ptr = env->me_dbxs[i].md_name.mv_data;
2925 env->me_dbxs[i].md_name.mv_data = NULL;
2926 env->me_dbxs[i].md_name.mv_size = 0;
2927 env->me_dbflags[i] = 0;
2928 env->me_dbiseqs[i]++;
2934 if (keep && env->me_numdbs < n)
2938 /** End a transaction, except successful commit of a nested transaction.
2939 * May be called twice for readonly txns: First reset it, then abort.
2940 * @param[in] txn the transaction handle to end
2941 * @param[in] mode why and how to end the transaction
2944 mdb_txn_end(MDB_txn *txn, unsigned mode)
2946 MDB_env *env = txn->mt_env;
2948 static const char *const names[] = MDB_END_NAMES;
2951 /* Export or close DBI handles opened in this txn */
2952 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
2954 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2955 names[mode & MDB_END_OPMASK],
2956 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2957 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2959 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2960 if (txn->mt_u.reader) {
2961 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2962 if (!(env->me_flags & MDB_NOTLS)) {
2963 txn->mt_u.reader = NULL; /* txn does not own reader */
2964 } else if (mode & MDB_END_SLOT) {
2965 txn->mt_u.reader->mr_pid = 0;
2966 txn->mt_u.reader = NULL;
2967 } /* else txn owns the slot until it does MDB_END_SLOT */
2969 txn->mt_numdbs = 0; /* prevent further DBI activity */
2970 txn->mt_flags |= MDB_TXN_FINISHED;
2972 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
2973 pgno_t *pghead = env->me_pghead;
2975 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
2976 mdb_cursors_close(txn, 0);
2977 if (!(env->me_flags & MDB_WRITEMAP)) {
2978 mdb_dlist_free(txn);
2982 txn->mt_flags = MDB_TXN_FINISHED;
2984 if (!txn->mt_parent) {
2985 mdb_midl_shrink(&txn->mt_free_pgs);
2986 env->me_free_pgs = txn->mt_free_pgs;
2988 env->me_pghead = NULL;
2992 mode = 0; /* txn == env->me_txn0, do not free() it */
2994 /* The writer mutex was locked in mdb_txn_begin. */
2996 UNLOCK_MUTEX(env->me_wmutex);
2998 txn->mt_parent->mt_child = NULL;
2999 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
3000 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
3001 mdb_midl_free(txn->mt_free_pgs);
3002 mdb_midl_free(txn->mt_spill_pgs);
3003 free(txn->mt_u.dirty_list);
3006 mdb_midl_free(pghead);
3009 if (mode & MDB_END_FREE)
3014 mdb_txn_reset(MDB_txn *txn)
3019 /* This call is only valid for read-only txns */
3020 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3023 mdb_txn_end(txn, MDB_END_RESET);
3027 mdb_txn_abort(MDB_txn *txn)
3033 mdb_txn_abort(txn->mt_child);
3035 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3038 /** Save the freelist as of this transaction to the freeDB.
3039 * This changes the freelist. Keep trying until it stabilizes.
3042 mdb_freelist_save(MDB_txn *txn)
3044 /* env->me_pghead[] can grow and shrink during this call.
3045 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3046 * Page numbers cannot disappear from txn->mt_free_pgs[].
3049 MDB_env *env = txn->mt_env;
3050 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3051 txnid_t pglast = 0, head_id = 0;
3052 pgno_t freecnt = 0, *free_pgs, *mop;
3053 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3055 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3057 if (env->me_pghead) {
3058 /* Make sure first page of freeDB is touched and on freelist */
3059 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3060 if (rc && rc != MDB_NOTFOUND)
3064 if (!env->me_pghead && txn->mt_loose_pgs) {
3065 /* Put loose page numbers in mt_free_pgs, since
3066 * we may be unable to return them to me_pghead.
3068 MDB_page *mp = txn->mt_loose_pgs;
3069 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3071 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3072 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3073 txn->mt_loose_pgs = NULL;
3074 txn->mt_loose_count = 0;
3077 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3078 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3079 ? SSIZE_MAX : maxfree_1pg;
3082 /* Come back here after each Put() in case freelist changed */
3087 /* If using records from freeDB which we have not yet
3088 * deleted, delete them and any we reserved for me_pghead.
3090 while (pglast < env->me_pglast) {
3091 rc = mdb_cursor_first(&mc, &key, NULL);
3094 pglast = head_id = *(txnid_t *)key.mv_data;
3095 total_room = head_room = 0;
3096 mdb_tassert(txn, pglast <= env->me_pglast);
3097 rc = mdb_cursor_del(&mc, 0);
3102 /* Save the IDL of pages freed by this txn, to a single record */
3103 if (freecnt < txn->mt_free_pgs[0]) {
3105 /* Make sure last page of freeDB is touched and on freelist */
3106 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3107 if (rc && rc != MDB_NOTFOUND)
3110 free_pgs = txn->mt_free_pgs;
3111 /* Write to last page of freeDB */
3112 key.mv_size = sizeof(txn->mt_txnid);
3113 key.mv_data = &txn->mt_txnid;
3115 freecnt = free_pgs[0];
3116 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3117 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3120 /* Retry if mt_free_pgs[] grew during the Put() */
3121 free_pgs = txn->mt_free_pgs;
3122 } while (freecnt < free_pgs[0]);
3123 mdb_midl_sort(free_pgs);
3124 memcpy(data.mv_data, free_pgs, data.mv_size);
3127 unsigned int i = free_pgs[0];
3128 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
3129 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3131 DPRINTF(("IDL %"Z"u", free_pgs[i]));
3137 mop = env->me_pghead;
3138 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3140 /* Reserve records for me_pghead[]. Split it if multi-page,
3141 * to avoid searching freeDB for a page range. Use keys in
3142 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3144 if (total_room >= mop_len) {
3145 if (total_room == mop_len || --more < 0)
3147 } else if (head_room >= maxfree_1pg && head_id > 1) {
3148 /* Keep current record (overflow page), add a new one */
3152 /* (Re)write {key = head_id, IDL length = head_room} */
3153 total_room -= head_room;
3154 head_room = mop_len - total_room;
3155 if (head_room > maxfree_1pg && head_id > 1) {
3156 /* Overflow multi-page for part of me_pghead */
3157 head_room /= head_id; /* amortize page sizes */
3158 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3159 } else if (head_room < 0) {
3160 /* Rare case, not bothering to delete this record */
3163 key.mv_size = sizeof(head_id);
3164 key.mv_data = &head_id;
3165 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3166 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3169 /* IDL is initially empty, zero out at least the length */
3170 pgs = (pgno_t *)data.mv_data;
3171 j = head_room > clean_limit ? head_room : 0;
3175 total_room += head_room;
3178 /* Return loose page numbers to me_pghead, though usually none are
3179 * left at this point. The pages themselves remain in dirty_list.
3181 if (txn->mt_loose_pgs) {
3182 MDB_page *mp = txn->mt_loose_pgs;
3183 unsigned count = txn->mt_loose_count;
3185 /* Room for loose pages + temp IDL with same */
3186 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3188 mop = env->me_pghead;
3189 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3190 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3191 loose[ ++count ] = mp->mp_pgno;
3193 mdb_midl_sort(loose);
3194 mdb_midl_xmerge(mop, loose);
3195 txn->mt_loose_pgs = NULL;
3196 txn->mt_loose_count = 0;
3200 /* Fill in the reserved me_pghead records */
3206 rc = mdb_cursor_first(&mc, &key, &data);
3207 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3208 txnid_t id = *(txnid_t *)key.mv_data;
3209 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3212 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3214 if (len > mop_len) {
3216 data.mv_size = (len + 1) * sizeof(MDB_ID);
3218 data.mv_data = mop -= len;
3221 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3223 if (rc || !(mop_len -= len))
3230 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3231 * @param[in] txn the transaction that's being committed
3232 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3233 * @return 0 on success, non-zero on failure.
3236 mdb_page_flush(MDB_txn *txn, int keep)
3238 MDB_env *env = txn->mt_env;
3239 MDB_ID2L dl = txn->mt_u.dirty_list;
3240 unsigned psize = env->me_psize, j;
3241 int i, pagecount = dl[0].mid, rc;
3242 size_t size = 0, pos = 0;
3244 MDB_page *dp = NULL;
3248 struct iovec iov[MDB_COMMIT_PAGES];
3249 ssize_t wpos = 0, wsize = 0, wres;
3250 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3256 if (env->me_flags & MDB_WRITEMAP) {
3257 /* Clear dirty flags */
3258 while (++i <= pagecount) {
3260 /* Don't flush this page yet */
3261 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3262 dp->mp_flags &= ~P_KEEP;
3266 dp->mp_flags &= ~P_DIRTY;
3271 /* Write the pages */
3273 if (++i <= pagecount) {
3275 /* Don't flush this page yet */
3276 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3277 dp->mp_flags &= ~P_KEEP;
3282 /* clear dirty flag */
3283 dp->mp_flags &= ~P_DIRTY;
3286 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3291 /* Windows actually supports scatter/gather I/O, but only on
3292 * unbuffered file handles. Since we're relying on the OS page
3293 * cache for all our data, that's self-defeating. So we just
3294 * write pages one at a time. We use the ov structure to set
3295 * the write offset, to at least save the overhead of a Seek
3298 DPRINTF(("committing page %"Z"u", pgno));
3299 memset(&ov, 0, sizeof(ov));
3300 ov.Offset = pos & 0xffffffff;
3301 ov.OffsetHigh = pos >> 16 >> 16;
3302 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3304 DPRINTF(("WriteFile: %d", rc));
3308 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3309 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3312 /* Write previous page(s) */
3313 #ifdef MDB_USE_PWRITEV
3314 wres = pwritev(env->me_fd, iov, n, wpos);
3317 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3320 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3324 DPRINTF(("lseek: %s", strerror(rc)));
3327 wres = writev(env->me_fd, iov, n);
3330 if (wres != wsize) {
3335 DPRINTF(("Write error: %s", strerror(rc)));
3337 rc = EIO; /* TODO: Use which error code? */
3338 DPUTS("short write, filesystem full?");
3349 DPRINTF(("committing page %"Z"u", pgno));
3350 next_pos = pos + size;
3351 iov[n].iov_len = size;
3352 iov[n].iov_base = (char *)dp;
3358 /* MIPS has cache coherency issues, this is a no-op everywhere else
3359 * Note: for any size >= on-chip cache size, entire on-chip cache is
3362 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3364 for (i = keep; ++i <= pagecount; ) {
3366 /* This is a page we skipped above */
3369 dl[j].mid = dp->mp_pgno;
3372 mdb_dpage_free(env, dp);
3377 txn->mt_dirty_room += i - j;
3383 mdb_txn_commit(MDB_txn *txn)
3386 unsigned int i, end_mode;
3392 /* mdb_txn_end() mode for a commit which writes nothing */
3393 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3395 if (txn->mt_child) {
3396 rc = mdb_txn_commit(txn->mt_child);
3403 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3407 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3408 DPUTS("txn has failed/finished, can't commit");
3410 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3415 if (txn->mt_parent) {
3416 MDB_txn *parent = txn->mt_parent;
3420 unsigned x, y, len, ps_len;
3422 /* Append our free list to parent's */
3423 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3426 mdb_midl_free(txn->mt_free_pgs);
3427 /* Failures after this must either undo the changes
3428 * to the parent or set MDB_TXN_ERROR in the parent.
3431 parent->mt_next_pgno = txn->mt_next_pgno;
3432 parent->mt_flags = txn->mt_flags;
3434 /* Merge our cursors into parent's and close them */
3435 mdb_cursors_close(txn, 1);
3437 /* Update parent's DB table. */
3438 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3439 parent->mt_numdbs = txn->mt_numdbs;
3440 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3441 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3442 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3443 /* preserve parent's DB_NEW status */
3444 x = parent->mt_dbflags[i] & DB_NEW;
3445 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3448 dst = parent->mt_u.dirty_list;
3449 src = txn->mt_u.dirty_list;
3450 /* Remove anything in our dirty list from parent's spill list */
3451 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3453 pspill[0] = (pgno_t)-1;
3454 /* Mark our dirty pages as deleted in parent spill list */
3455 for (i=0, len=src[0].mid; ++i <= len; ) {
3456 MDB_ID pn = src[i].mid << 1;
3457 while (pn > pspill[x])
3459 if (pn == pspill[x]) {
3464 /* Squash deleted pagenums if we deleted any */
3465 for (x=y; ++x <= ps_len; )
3466 if (!(pspill[x] & 1))
3467 pspill[++y] = pspill[x];
3471 /* Find len = length of merging our dirty list with parent's */
3473 dst[0].mid = 0; /* simplify loops */
3474 if (parent->mt_parent) {
3475 len = x + src[0].mid;
3476 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3477 for (i = x; y && i; y--) {
3478 pgno_t yp = src[y].mid;
3479 while (yp < dst[i].mid)
3481 if (yp == dst[i].mid) {
3486 } else { /* Simplify the above for single-ancestor case */
3487 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3489 /* Merge our dirty list with parent's */
3491 for (i = len; y; dst[i--] = src[y--]) {
3492 pgno_t yp = src[y].mid;
3493 while (yp < dst[x].mid)
3494 dst[i--] = dst[x--];
3495 if (yp == dst[x].mid)
3496 free(dst[x--].mptr);
3498 mdb_tassert(txn, i == x);
3500 free(txn->mt_u.dirty_list);
3501 parent->mt_dirty_room = txn->mt_dirty_room;
3502 if (txn->mt_spill_pgs) {
3503 if (parent->mt_spill_pgs) {
3504 /* TODO: Prevent failure here, so parent does not fail */
3505 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3507 parent->mt_flags |= MDB_TXN_ERROR;
3508 mdb_midl_free(txn->mt_spill_pgs);
3509 mdb_midl_sort(parent->mt_spill_pgs);
3511 parent->mt_spill_pgs = txn->mt_spill_pgs;
3515 /* Append our loose page list to parent's */
3516 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(lp))
3518 *lp = txn->mt_loose_pgs;
3519 parent->mt_loose_count += txn->mt_loose_count;
3521 parent->mt_child = NULL;
3522 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3527 if (txn != env->me_txn) {
3528 DPUTS("attempt to commit unknown transaction");
3533 mdb_cursors_close(txn, 0);
3535 if (!txn->mt_u.dirty_list[0].mid &&
3536 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3539 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3540 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3542 /* Update DB root pointers */
3543 if (txn->mt_numdbs > CORE_DBS) {
3547 data.mv_size = sizeof(MDB_db);
3549 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3550 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3551 if (txn->mt_dbflags[i] & DB_DIRTY) {
3552 if (TXN_DBI_CHANGED(txn, i)) {
3556 data.mv_data = &txn->mt_dbs[i];
3557 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3565 rc = mdb_freelist_save(txn);
3569 mdb_midl_free(env->me_pghead);
3570 env->me_pghead = NULL;
3571 mdb_midl_shrink(&txn->mt_free_pgs);
3577 if ((rc = mdb_page_flush(txn, 0)))
3579 if (!F_ISSET(txn->mt_flags, MDB_TXN_NOSYNC) &&
3580 (rc = mdb_env_sync(env, 0)))
3582 if ((rc = mdb_env_write_meta(txn)))
3584 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3587 mdb_txn_end(txn, end_mode);
3595 /** Read the environment parameters of a DB environment before
3596 * mapping it into memory.
3597 * @param[in] env the environment handle
3598 * @param[out] meta address of where to store the meta information
3599 * @return 0 on success, non-zero on failure.
3602 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3608 enum { Size = sizeof(pbuf) };
3610 /* We don't know the page size yet, so use a minimum value.
3611 * Read both meta pages so we can use the latest one.
3614 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3618 memset(&ov, 0, sizeof(ov));
3620 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3621 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3624 rc = pread(env->me_fd, &pbuf, Size, off);
3627 if (rc == 0 && off == 0)
3629 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3630 DPRINTF(("read: %s", mdb_strerror(rc)));
3634 p = (MDB_page *)&pbuf;
3636 if (!F_ISSET(p->mp_flags, P_META)) {
3637 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3642 if (m->mm_magic != MDB_MAGIC) {
3643 DPUTS("meta has invalid magic");
3647 if (m->mm_version != MDB_DATA_VERSION) {
3648 DPRINTF(("database is version %u, expected version %u",
3649 m->mm_version, MDB_DATA_VERSION));
3650 return MDB_VERSION_MISMATCH;
3653 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3659 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3661 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3663 meta->mm_magic = MDB_MAGIC;
3664 meta->mm_version = MDB_DATA_VERSION;
3665 meta->mm_mapsize = env->me_mapsize;
3666 meta->mm_psize = env->me_psize;
3667 meta->mm_last_pg = NUM_METAS-1;
3668 meta->mm_flags = env->me_flags & 0xffff;
3669 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3670 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3671 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3674 /** Write the environment parameters of a freshly created DB environment.
3675 * @param[in] env the environment handle
3676 * @param[in] meta the #MDB_meta to write
3677 * @return 0 on success, non-zero on failure.
3680 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3688 memset(&ov, 0, sizeof(ov));
3689 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3691 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3694 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3695 len = pwrite(fd, ptr, size, pos); \
3696 if (len == -1 && ErrCode() == EINTR) continue; \
3697 rc = (len >= 0); break; } while(1)
3700 DPUTS("writing new meta page");
3702 psize = env->me_psize;
3704 p = calloc(NUM_METAS, psize);
3708 p->mp_flags = P_META;
3709 *(MDB_meta *)METADATA(p) = *meta;
3711 q = (MDB_page *)((char *)p + psize);
3713 q->mp_flags = P_META;
3714 *(MDB_meta *)METADATA(q) = *meta;
3716 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
3719 else if ((unsigned) len == psize * NUM_METAS)
3727 /** Update the environment info to commit a transaction.
3728 * @param[in] txn the transaction that's being committed
3729 * @return 0 on success, non-zero on failure.
3732 mdb_env_write_meta(MDB_txn *txn)
3735 MDB_meta meta, metab, *mp;
3739 int rc, len, toggle;
3748 toggle = txn->mt_txnid & 1;
3749 DPRINTF(("writing meta page %d for root page %"Z"u",
3750 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3753 flags = txn->mt_flags & env->me_flags;
3754 mp = env->me_metas[toggle];
3755 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3756 /* Persist any increases of mapsize config */
3757 if (mapsize < env->me_mapsize)
3758 mapsize = env->me_mapsize;
3760 if (flags & MDB_WRITEMAP) {
3761 mp->mm_mapsize = mapsize;
3762 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3763 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3764 mp->mm_last_pg = txn->mt_next_pgno - 1;
3765 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
3766 !(defined(__i386__) || defined(__x86_64__))
3767 /* LY: issue a memory barrier, if not x86. ITS#7969 */
3768 __sync_synchronize();
3770 mp->mm_txnid = txn->mt_txnid;
3771 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3772 unsigned meta_size = env->me_psize;
3773 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3774 ptr = (char *)mp - PAGEHDRSZ;
3775 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3776 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
3780 if (MDB_MSYNC(ptr, meta_size, rc)) {
3787 metab.mm_txnid = mp->mm_txnid;
3788 metab.mm_last_pg = mp->mm_last_pg;
3790 meta.mm_mapsize = mapsize;
3791 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3792 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3793 meta.mm_last_pg = txn->mt_next_pgno - 1;
3794 meta.mm_txnid = txn->mt_txnid;
3796 off = offsetof(MDB_meta, mm_mapsize);
3797 ptr = (char *)&meta + off;
3798 len = sizeof(MDB_meta) - off;
3799 off += (char *)mp - env->me_map;
3801 /* Write to the SYNC fd */
3802 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
3805 memset(&ov, 0, sizeof(ov));
3807 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3812 rc = pwrite(mfd, ptr, len, off);
3815 rc = rc < 0 ? ErrCode() : EIO;
3820 DPUTS("write failed, disk error?");
3821 /* On a failure, the pagecache still contains the new data.
3822 * Write some old data back, to prevent it from being used.
3823 * Use the non-SYNC fd; we know it will fail anyway.
3825 meta.mm_last_pg = metab.mm_last_pg;
3826 meta.mm_txnid = metab.mm_txnid;
3828 memset(&ov, 0, sizeof(ov));
3830 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3832 r2 = pwrite(env->me_fd, ptr, len, off);
3833 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3836 env->me_flags |= MDB_FATAL_ERROR;
3839 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3840 CACHEFLUSH(env->me_map + off, len, DCACHE);
3842 /* Memory ordering issues are irrelevant; since the entire writer
3843 * is wrapped by wmutex, all of these changes will become visible
3844 * after the wmutex is unlocked. Since the DB is multi-version,
3845 * readers will get consistent data regardless of how fresh or
3846 * how stale their view of these values is.
3849 env->me_txns->mti_txnid = txn->mt_txnid;
3854 /** Check both meta pages to see which one is newer.
3855 * @param[in] env the environment handle
3856 * @return newest #MDB_meta.
3859 mdb_env_pick_meta(const MDB_env *env)
3861 MDB_meta *const *metas = env->me_metas;
3862 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
3866 mdb_env_create(MDB_env **env)
3870 e = calloc(1, sizeof(MDB_env));
3874 e->me_maxreaders = DEFAULT_READERS;
3875 e->me_maxdbs = e->me_numdbs = CORE_DBS;
3876 e->me_fd = INVALID_HANDLE_VALUE;
3877 e->me_lfd = INVALID_HANDLE_VALUE;
3878 e->me_mfd = INVALID_HANDLE_VALUE;
3879 #ifdef MDB_USE_POSIX_SEM
3880 e->me_rmutex = SEM_FAILED;
3881 e->me_wmutex = SEM_FAILED;
3882 #elif defined MDB_USE_SYSV_SEM
3883 e->me_rmutex->semid = -1;
3884 e->me_wmutex->semid = -1;
3886 e->me_pid = getpid();
3887 GET_PAGESIZE(e->me_os_psize);
3888 VGMEMP_CREATE(e,0,0);
3894 mdb_env_map(MDB_env *env, void *addr)
3897 unsigned int flags = env->me_flags;
3901 LONG sizelo, sizehi;
3904 if (flags & MDB_RDONLY) {
3905 /* Don't set explicit map size, use whatever exists */
3910 msize = env->me_mapsize;
3911 sizelo = msize & 0xffffffff;
3912 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3914 /* Windows won't create mappings for zero length files.
3915 * and won't map more than the file size.
3916 * Just set the maxsize right now.
3918 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3919 || !SetEndOfFile(env->me_fd)
3920 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3924 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3925 PAGE_READWRITE : PAGE_READONLY,
3926 sizehi, sizelo, NULL);
3929 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3930 FILE_MAP_WRITE : FILE_MAP_READ,
3932 rc = env->me_map ? 0 : ErrCode();
3937 int prot = PROT_READ;
3938 if (flags & MDB_WRITEMAP) {
3940 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3943 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3945 if (env->me_map == MAP_FAILED) {
3950 if (flags & MDB_NORDAHEAD) {
3951 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3953 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3955 #ifdef POSIX_MADV_RANDOM
3956 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3957 #endif /* POSIX_MADV_RANDOM */
3958 #endif /* MADV_RANDOM */
3962 /* Can happen because the address argument to mmap() is just a
3963 * hint. mmap() can pick another, e.g. if the range is in use.
3964 * The MAP_FIXED flag would prevent that, but then mmap could
3965 * instead unmap existing pages to make room for the new map.
3967 if (addr && env->me_map != addr)
3968 return EBUSY; /* TODO: Make a new MDB_* error code? */
3970 p = (MDB_page *)env->me_map;
3971 env->me_metas[0] = METADATA(p);
3972 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3978 mdb_env_set_mapsize(MDB_env *env, size_t size)
3980 /* If env is already open, caller is responsible for making
3981 * sure there are no active txns.
3989 meta = mdb_env_pick_meta(env);
3991 size = meta->mm_mapsize;
3993 /* Silently round up to minimum if the size is too small */
3994 size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
3998 munmap(env->me_map, env->me_mapsize);
3999 env->me_mapsize = size;
4000 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4001 rc = mdb_env_map(env, old);
4005 env->me_mapsize = size;
4007 env->me_maxpg = env->me_mapsize / env->me_psize;
4012 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4016 env->me_maxdbs = dbs + CORE_DBS;
4021 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4023 if (env->me_map || readers < 1)
4025 env->me_maxreaders = readers;
4030 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4032 if (!env || !readers)
4034 *readers = env->me_maxreaders;
4039 mdb_fsize(HANDLE fd, size_t *size)
4042 LARGE_INTEGER fsize;
4044 if (!GetFileSizeEx(fd, &fsize))
4047 *size = fsize.QuadPart;
4059 #ifdef BROKEN_FDATASYNC
4060 #include <sys/utsname.h>
4061 #include <sys/vfs.h>
4064 /** Further setup required for opening an LMDB environment
4067 mdb_env_open2(MDB_env *env)
4069 unsigned int flags = env->me_flags;
4070 int i, newenv = 0, rc;
4074 /* See if we should use QueryLimited */
4076 if ((rc & 0xff) > 5)
4077 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4079 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4082 #ifdef BROKEN_FDATASYNC
4083 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4084 * https://lkml.org/lkml/2012/9/3/83
4085 * Kernels after 3.6-rc6 are known good.
4086 * https://lkml.org/lkml/2012/9/10/556
4087 * See if the DB is on ext3/ext4, then check for new enough kernel
4088 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4093 fstatfs(env->me_fd, &st);
4094 while (st.f_type == 0xEF53) {
4098 if (uts.release[0] < '3') {
4099 if (!strncmp(uts.release, "2.6.32.", 7)) {
4100 i = atoi(uts.release+7);
4102 break; /* 2.6.32.60 and newer is OK */
4103 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4104 i = atoi(uts.release+7);
4106 break; /* 2.6.34.15 and newer is OK */
4108 } else if (uts.release[0] == '3') {
4109 i = atoi(uts.release+2);
4111 break; /* 3.6 and newer is OK */
4113 i = atoi(uts.release+4);
4115 break; /* 3.5.4 and newer is OK */
4116 } else if (i == 2) {
4117 i = atoi(uts.release+4);
4119 break; /* 3.2.30 and newer is OK */
4121 } else { /* 4.x and newer is OK */
4124 env->me_flags |= MDB_FSYNCONLY;
4130 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4133 DPUTS("new mdbenv");
4135 env->me_psize = env->me_os_psize;
4136 if (env->me_psize > MAX_PAGESIZE)
4137 env->me_psize = MAX_PAGESIZE;
4138 memset(&meta, 0, sizeof(meta));
4139 mdb_env_init_meta0(env, &meta);
4140 meta.mm_mapsize = DEFAULT_MAPSIZE;
4142 env->me_psize = meta.mm_psize;
4145 /* Was a mapsize configured? */
4146 if (!env->me_mapsize) {
4147 env->me_mapsize = meta.mm_mapsize;
4150 /* Make sure mapsize >= committed data size. Even when using
4151 * mm_mapsize, which could be broken in old files (ITS#7789).
4153 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4154 if (env->me_mapsize < minsize)
4155 env->me_mapsize = minsize;
4157 meta.mm_mapsize = env->me_mapsize;
4159 if (newenv && !(flags & MDB_FIXEDMAP)) {
4160 /* mdb_env_map() may grow the datafile. Write the metapages
4161 * first, so the file will be valid if initialization fails.
4162 * Except with FIXEDMAP, since we do not yet know mm_address.
4163 * We could fill in mm_address later, but then a different
4164 * program might end up doing that - one with a memory layout
4165 * and map address which does not suit the main program.
4167 rc = mdb_env_init_meta(env, &meta);
4173 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4178 if (flags & MDB_FIXEDMAP)
4179 meta.mm_address = env->me_map;
4180 i = mdb_env_init_meta(env, &meta);
4181 if (i != MDB_SUCCESS) {
4186 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4187 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4189 #if !(MDB_MAXKEYSIZE)
4190 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4192 env->me_maxpg = env->me_mapsize / env->me_psize;
4196 MDB_meta *meta = mdb_env_pick_meta(env);
4197 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4199 DPRINTF(("opened database version %u, pagesize %u",
4200 meta->mm_version, env->me_psize));
4201 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4202 DPRINTF(("depth: %u", db->md_depth));
4203 DPRINTF(("entries: %"Z"u", db->md_entries));
4204 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
4205 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
4206 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
4207 DPRINTF(("root: %"Z"u", db->md_root));
4215 /** Release a reader thread's slot in the reader lock table.
4216 * This function is called automatically when a thread exits.
4217 * @param[in] ptr This points to the slot in the reader lock table.
4220 mdb_env_reader_dest(void *ptr)
4222 MDB_reader *reader = ptr;
4228 /** Junk for arranging thread-specific callbacks on Windows. This is
4229 * necessarily platform and compiler-specific. Windows supports up
4230 * to 1088 keys. Let's assume nobody opens more than 64 environments
4231 * in a single process, for now. They can override this if needed.
4233 #ifndef MAX_TLS_KEYS
4234 #define MAX_TLS_KEYS 64
4236 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4237 static int mdb_tls_nkeys;
4239 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4243 case DLL_PROCESS_ATTACH: break;
4244 case DLL_THREAD_ATTACH: break;
4245 case DLL_THREAD_DETACH:
4246 for (i=0; i<mdb_tls_nkeys; i++) {
4247 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4249 mdb_env_reader_dest(r);
4253 case DLL_PROCESS_DETACH: break;
4258 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4260 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4264 /* Force some symbol references.
4265 * _tls_used forces the linker to create the TLS directory if not already done
4266 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4268 #pragma comment(linker, "/INCLUDE:_tls_used")
4269 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4270 #pragma const_seg(".CRT$XLB")
4271 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4272 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4275 #pragma comment(linker, "/INCLUDE:__tls_used")
4276 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4277 #pragma data_seg(".CRT$XLB")
4278 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4280 #endif /* WIN 32/64 */
4281 #endif /* !__GNUC__ */
4284 /** Downgrade the exclusive lock on the region back to shared */
4286 mdb_env_share_locks(MDB_env *env, int *excl)
4289 MDB_meta *meta = mdb_env_pick_meta(env);
4291 env->me_txns->mti_txnid = meta->mm_txnid;
4296 /* First acquire a shared lock. The Unlock will
4297 * then release the existing exclusive lock.
4299 memset(&ov, 0, sizeof(ov));
4300 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4303 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4309 struct flock lock_info;
4310 /* The shared lock replaces the existing lock */
4311 memset((void *)&lock_info, 0, sizeof(lock_info));
4312 lock_info.l_type = F_RDLCK;
4313 lock_info.l_whence = SEEK_SET;
4314 lock_info.l_start = 0;
4315 lock_info.l_len = 1;
4316 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4317 (rc = ErrCode()) == EINTR) ;
4318 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4325 /** Try to get exclusive lock, otherwise shared.
4326 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4329 mdb_env_excl_lock(MDB_env *env, int *excl)
4333 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4337 memset(&ov, 0, sizeof(ov));
4338 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4345 struct flock lock_info;
4346 memset((void *)&lock_info, 0, sizeof(lock_info));
4347 lock_info.l_type = F_WRLCK;
4348 lock_info.l_whence = SEEK_SET;
4349 lock_info.l_start = 0;
4350 lock_info.l_len = 1;
4351 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4352 (rc = ErrCode()) == EINTR) ;
4356 # ifndef MDB_USE_POSIX_MUTEX
4357 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4360 lock_info.l_type = F_RDLCK;
4361 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4362 (rc = ErrCode()) == EINTR) ;
4372 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4374 * @(#) $Revision: 5.1 $
4375 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4376 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4378 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4382 * Please do not copyright this code. This code is in the public domain.
4384 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4385 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4386 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4387 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4388 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4389 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4390 * PERFORMANCE OF THIS SOFTWARE.
4393 * chongo <Landon Curt Noll> /\oo/\
4394 * http://www.isthe.com/chongo/
4396 * Share and Enjoy! :-)
4399 typedef unsigned long long mdb_hash_t;
4400 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4402 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4403 * @param[in] val value to hash
4404 * @param[in] hval initial value for hash
4405 * @return 64 bit hash
4407 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4408 * hval arg on the first call.
4411 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4413 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4414 unsigned char *end = s + val->mv_size;
4416 * FNV-1a hash each octet of the string
4419 /* xor the bottom with the current octet */
4420 hval ^= (mdb_hash_t)*s++;
4422 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4423 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4424 (hval << 7) + (hval << 8) + (hval << 40);
4426 /* return our new hash value */
4430 /** Hash the string and output the encoded hash.
4431 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4432 * very short name limits. We don't care about the encoding being reversible,
4433 * we just want to preserve as many bits of the input as possible in a
4434 * small printable string.
4435 * @param[in] str string to hash
4436 * @param[out] encbuf an array of 11 chars to hold the hash
4438 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4441 mdb_pack85(unsigned long l, char *out)
4445 for (i=0; i<5; i++) {
4446 *out++ = mdb_a85[l % 85];
4452 mdb_hash_enc(MDB_val *val, char *encbuf)
4454 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4456 mdb_pack85(h, encbuf);
4457 mdb_pack85(h>>32, encbuf+5);
4462 /** Open and/or initialize the lock region for the environment.
4463 * @param[in] env The LMDB environment.
4464 * @param[in] lpath The pathname of the file used for the lock region.
4465 * @param[in] mode The Unix permissions for the file, if we create it.
4466 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4467 * @return 0 on success, non-zero on failure.
4470 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4473 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4475 # define MDB_ERRCODE_ROFS EROFS
4476 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4477 # define MDB_CLOEXEC O_CLOEXEC
4480 # define MDB_CLOEXEC 0
4483 #ifdef MDB_USE_SYSV_SEM
4491 env->me_lfd = CreateFileA(lpath, GENERIC_READ|GENERIC_WRITE,
4492 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4493 FILE_ATTRIBUTE_NORMAL, NULL);
4495 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4497 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4499 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4504 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4505 /* Lose record locks when exec*() */
4506 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4507 fcntl(env->me_lfd, F_SETFD, fdflags);
4510 if (!(env->me_flags & MDB_NOTLS)) {
4511 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4514 env->me_flags |= MDB_ENV_TXKEY;
4516 /* Windows TLS callbacks need help finding their TLS info. */
4517 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4521 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4525 /* Try to get exclusive lock. If we succeed, then
4526 * nobody is using the lock region and we should initialize it.
4528 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4531 size = GetFileSize(env->me_lfd, NULL);
4533 size = lseek(env->me_lfd, 0, SEEK_END);
4534 if (size == -1) goto fail_errno;
4536 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4537 if (size < rsize && *excl > 0) {
4539 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4540 || !SetEndOfFile(env->me_lfd))
4543 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4547 size = rsize - sizeof(MDB_txninfo);
4548 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4553 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4555 if (!mh) goto fail_errno;
4556 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4558 if (!env->me_txns) goto fail_errno;
4560 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4562 if (m == MAP_FAILED) goto fail_errno;
4568 BY_HANDLE_FILE_INFORMATION stbuf;
4577 if (!mdb_sec_inited) {
4578 InitializeSecurityDescriptor(&mdb_null_sd,
4579 SECURITY_DESCRIPTOR_REVISION);
4580 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4581 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4582 mdb_all_sa.bInheritHandle = FALSE;
4583 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4586 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4587 idbuf.volume = stbuf.dwVolumeSerialNumber;
4588 idbuf.nhigh = stbuf.nFileIndexHigh;
4589 idbuf.nlow = stbuf.nFileIndexLow;
4590 val.mv_data = &idbuf;
4591 val.mv_size = sizeof(idbuf);
4592 mdb_hash_enc(&val, encbuf);
4593 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4594 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4595 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4596 if (!env->me_rmutex) goto fail_errno;
4597 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4598 if (!env->me_wmutex) goto fail_errno;
4599 #elif defined(MDB_USE_POSIX_SEM)
4608 #if defined(__NetBSD__)
4609 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4611 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4612 idbuf.dev = stbuf.st_dev;
4613 idbuf.ino = stbuf.st_ino;
4614 val.mv_data = &idbuf;
4615 val.mv_size = sizeof(idbuf);
4616 mdb_hash_enc(&val, encbuf);
4617 #ifdef MDB_SHORT_SEMNAMES
4618 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4620 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4621 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4622 /* Clean up after a previous run, if needed: Try to
4623 * remove both semaphores before doing anything else.
4625 sem_unlink(env->me_txns->mti_rmname);
4626 sem_unlink(env->me_txns->mti_wmname);
4627 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4628 O_CREAT|O_EXCL, mode, 1);
4629 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4630 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4631 O_CREAT|O_EXCL, mode, 1);
4632 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4633 #elif defined(MDB_USE_SYSV_SEM)
4634 unsigned short vals[2] = {1, 1};
4635 key_t key = ftok(lpath, 'M');
4638 semid = semget(key, 2, (mode & 0777) | IPC_CREAT);
4642 if (semctl(semid, 0, SETALL, semu) < 0)
4644 env->me_txns->mti_semid = semid;
4645 #else /* MDB_USE_POSIX_MUTEX: */
4646 pthread_mutexattr_t mattr;
4648 if ((rc = pthread_mutexattr_init(&mattr))
4649 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4650 #ifdef MDB_ROBUST_SUPPORTED
4651 || (rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST))
4653 || (rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr))
4654 || (rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr)))
4656 pthread_mutexattr_destroy(&mattr);
4657 #endif /* _WIN32 || ... */
4659 env->me_txns->mti_magic = MDB_MAGIC;
4660 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4661 env->me_txns->mti_txnid = 0;
4662 env->me_txns->mti_numreaders = 0;
4665 #ifdef MDB_USE_SYSV_SEM
4666 struct semid_ds buf;
4668 if (env->me_txns->mti_magic != MDB_MAGIC) {
4669 DPUTS("lock region has invalid magic");
4673 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4674 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4675 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4676 rc = MDB_VERSION_MISMATCH;
4680 if (rc && rc != EACCES && rc != EAGAIN) {
4684 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4685 if (!env->me_rmutex) goto fail_errno;
4686 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4687 if (!env->me_wmutex) goto fail_errno;
4688 #elif defined(MDB_USE_POSIX_SEM)
4689 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4690 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4691 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4692 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4693 #elif defined(MDB_USE_SYSV_SEM)
4694 semid = env->me_txns->mti_semid;
4696 /* check for read access */
4697 if (semctl(semid, 0, IPC_STAT, semu) < 0)
4699 /* check for write access */
4700 if (semctl(semid, 0, IPC_SET, semu) < 0)
4704 #ifdef MDB_USE_SYSV_SEM
4705 env->me_rmutex->semid = semid;
4706 env->me_wmutex->semid = semid;
4707 env->me_rmutex->semnum = 0;
4708 env->me_wmutex->semnum = 1;
4709 env->me_rmutex->locked = &env->me_txns->mti_rlocked;
4710 env->me_wmutex->locked = &env->me_txns->mti_wlocked;
4721 /** The name of the lock file in the DB environment */
4722 #define LOCKNAME "/lock.mdb"
4723 /** The name of the data file in the DB environment */
4724 #define DATANAME "/data.mdb"
4725 /** The suffix of the lock file when no subdir is used */
4726 #define LOCKSUFF "-lock"
4727 /** Only a subset of the @ref mdb_env flags can be changed
4728 * at runtime. Changing other flags requires closing the
4729 * environment and re-opening it with the new flags.
4731 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4732 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
4733 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4735 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4736 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4740 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4742 int oflags, rc, len, excl = -1;
4743 char *lpath, *dpath;
4745 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4749 if (flags & MDB_NOSUBDIR) {
4750 rc = len + sizeof(LOCKSUFF) + len + 1;
4752 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4757 if (flags & MDB_NOSUBDIR) {
4758 dpath = lpath + len + sizeof(LOCKSUFF);
4759 sprintf(lpath, "%s" LOCKSUFF, path);
4760 strcpy(dpath, path);
4762 dpath = lpath + len + sizeof(LOCKNAME);
4763 sprintf(lpath, "%s" LOCKNAME, path);
4764 sprintf(dpath, "%s" DATANAME, path);
4768 flags |= env->me_flags;
4769 if (flags & MDB_RDONLY) {
4770 /* silently ignore WRITEMAP when we're only getting read access */
4771 flags &= ~MDB_WRITEMAP;
4773 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4774 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4777 env->me_flags = flags |= MDB_ENV_ACTIVE;
4781 env->me_path = strdup(path);
4782 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4783 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4784 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4785 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4789 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
4791 /* For RDONLY, get lockfile after we know datafile exists */
4792 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4793 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4799 if (F_ISSET(flags, MDB_RDONLY)) {
4800 oflags = GENERIC_READ;
4801 len = OPEN_EXISTING;
4803 oflags = GENERIC_READ|GENERIC_WRITE;
4806 mode = FILE_ATTRIBUTE_NORMAL;
4807 env->me_fd = CreateFileA(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4808 NULL, len, mode, NULL);
4810 if (F_ISSET(flags, MDB_RDONLY))
4813 oflags = O_RDWR | O_CREAT;
4815 env->me_fd = open(dpath, oflags, mode);
4817 if (env->me_fd == INVALID_HANDLE_VALUE) {
4822 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4823 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4828 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4829 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4830 env->me_mfd = env->me_fd;
4832 /* Synchronous fd for meta writes. Needed even with
4833 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4836 len = OPEN_EXISTING;
4837 env->me_mfd = CreateFileA(dpath, oflags,
4838 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4839 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4842 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4844 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4849 DPRINTF(("opened dbenv %p", (void *) env));
4851 rc = mdb_env_share_locks(env, &excl);
4855 if (!(flags & MDB_RDONLY)) {
4857 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
4858 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
4859 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
4860 (txn = calloc(1, size)))
4862 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
4863 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
4864 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
4865 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
4867 txn->mt_dbxs = env->me_dbxs;
4868 txn->mt_flags = MDB_TXN_FINISHED;
4878 mdb_env_close0(env, excl);
4884 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4886 mdb_env_close0(MDB_env *env, int excl)
4890 if (!(env->me_flags & MDB_ENV_ACTIVE))
4893 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4895 for (i = env->me_maxdbs; --i >= CORE_DBS; )
4896 free(env->me_dbxs[i].md_name.mv_data);
4901 free(env->me_dbiseqs);
4902 free(env->me_dbflags);
4904 free(env->me_dirty_list);
4906 mdb_midl_free(env->me_free_pgs);
4908 if (env->me_flags & MDB_ENV_TXKEY) {
4909 pthread_key_delete(env->me_txkey);
4911 /* Delete our key from the global list */
4912 for (i=0; i<mdb_tls_nkeys; i++)
4913 if (mdb_tls_keys[i] == env->me_txkey) {
4914 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4922 munmap(env->me_map, env->me_mapsize);
4924 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4925 (void) close(env->me_mfd);
4926 if (env->me_fd != INVALID_HANDLE_VALUE)
4927 (void) close(env->me_fd);
4929 MDB_PID_T pid = env->me_pid;
4930 /* Clearing readers is done in this function because
4931 * me_txkey with its destructor must be disabled first.
4933 * We skip the the reader mutex, so we touch only
4934 * data owned by this process (me_close_readers and
4935 * our readers), and clear each reader atomically.
4937 for (i = env->me_close_readers; --i >= 0; )
4938 if (env->me_txns->mti_readers[i].mr_pid == pid)
4939 env->me_txns->mti_readers[i].mr_pid = 0;
4941 if (env->me_rmutex) {
4942 CloseHandle(env->me_rmutex);
4943 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4945 /* Windows automatically destroys the mutexes when
4946 * the last handle closes.
4948 #elif defined(MDB_USE_POSIX_SEM)
4949 if (env->me_rmutex != SEM_FAILED) {
4950 sem_close(env->me_rmutex);
4951 if (env->me_wmutex != SEM_FAILED)
4952 sem_close(env->me_wmutex);
4953 /* If we have the filelock: If we are the
4954 * only remaining user, clean up semaphores.
4957 mdb_env_excl_lock(env, &excl);
4959 sem_unlink(env->me_txns->mti_rmname);
4960 sem_unlink(env->me_txns->mti_wmname);
4963 #elif defined(MDB_USE_SYSV_SEM)
4964 if (env->me_rmutex->semid != -1) {
4965 /* If we have the filelock: If we are the
4966 * only remaining user, clean up semaphores.
4969 mdb_env_excl_lock(env, &excl);
4971 semctl(env->me_rmutex->semid, 0, IPC_RMID);
4974 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4976 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4979 /* Unlock the lockfile. Windows would have unlocked it
4980 * after closing anyway, but not necessarily at once.
4982 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4985 (void) close(env->me_lfd);
4988 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4992 mdb_env_close(MDB_env *env)
4999 VGMEMP_DESTROY(env);
5000 while ((dp = env->me_dpages) != NULL) {
5001 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5002 env->me_dpages = dp->mp_next;
5006 mdb_env_close0(env, 0);
5010 /** Compare two items pointing at aligned size_t's */
5012 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5014 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
5015 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
5018 /** Compare two items pointing at aligned unsigned int's.
5020 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5021 * but #mdb_cmp_clong() is called instead if the data type is size_t.
5024 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5026 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5027 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5030 /** Compare two items pointing at unsigned ints of unknown alignment.
5031 * Nodes and keys are guaranteed to be 2-byte aligned.
5034 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5036 #if BYTE_ORDER == LITTLE_ENDIAN
5037 unsigned short *u, *c;
5040 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5041 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5044 } while(!x && u > (unsigned short *)a->mv_data);
5047 unsigned short *u, *c, *end;
5050 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5051 u = (unsigned short *)a->mv_data;
5052 c = (unsigned short *)b->mv_data;
5055 } while(!x && u < end);
5060 /** Compare two items lexically */
5062 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5069 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5075 diff = memcmp(a->mv_data, b->mv_data, len);
5076 return diff ? diff : len_diff<0 ? -1 : len_diff;
5079 /** Compare two items in reverse byte order */
5081 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5083 const unsigned char *p1, *p2, *p1_lim;
5087 p1_lim = (const unsigned char *)a->mv_data;
5088 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5089 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5091 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5097 while (p1 > p1_lim) {
5098 diff = *--p1 - *--p2;
5102 return len_diff<0 ? -1 : len_diff;
5105 /** Search for key within a page, using binary search.
5106 * Returns the smallest entry larger or equal to the key.
5107 * If exactp is non-null, stores whether the found entry was an exact match
5108 * in *exactp (1 or 0).
5109 * Updates the cursor index with the index of the found entry.
5110 * If no entry larger or equal to the key is found, returns NULL.
5113 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5115 unsigned int i = 0, nkeys;
5118 MDB_page *mp = mc->mc_pg[mc->mc_top];
5119 MDB_node *node = NULL;
5124 nkeys = NUMKEYS(mp);
5126 DPRINTF(("searching %u keys in %s %spage %"Z"u",
5127 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5130 low = IS_LEAF(mp) ? 0 : 1;
5132 cmp = mc->mc_dbx->md_cmp;
5134 /* Branch pages have no data, so if using integer keys,
5135 * alignment is guaranteed. Use faster mdb_cmp_int.
5137 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5138 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
5145 nodekey.mv_size = mc->mc_db->md_pad;
5146 node = NODEPTR(mp, 0); /* fake */
5147 while (low <= high) {
5148 i = (low + high) >> 1;
5149 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5150 rc = cmp(key, &nodekey);
5151 DPRINTF(("found leaf index %u [%s], rc = %i",
5152 i, DKEY(&nodekey), rc));
5161 while (low <= high) {
5162 i = (low + high) >> 1;
5164 node = NODEPTR(mp, i);
5165 nodekey.mv_size = NODEKSZ(node);
5166 nodekey.mv_data = NODEKEY(node);
5168 rc = cmp(key, &nodekey);
5171 DPRINTF(("found leaf index %u [%s], rc = %i",
5172 i, DKEY(&nodekey), rc));
5174 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
5175 i, DKEY(&nodekey), NODEPGNO(node), rc));
5186 if (rc > 0) { /* Found entry is less than the key. */
5187 i++; /* Skip to get the smallest entry larger than key. */
5189 node = NODEPTR(mp, i);
5192 *exactp = (rc == 0 && nkeys > 0);
5193 /* store the key index */
5194 mc->mc_ki[mc->mc_top] = i;
5196 /* There is no entry larger or equal to the key. */
5199 /* nodeptr is fake for LEAF2 */
5205 mdb_cursor_adjust(MDB_cursor *mc, func)
5209 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5210 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5217 /** Pop a page off the top of the cursor's stack. */
5219 mdb_cursor_pop(MDB_cursor *mc)
5222 DPRINTF(("popping page %"Z"u off db %d cursor %p",
5223 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5231 /** Push a page onto the top of the cursor's stack. */
5233 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5235 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
5236 DDBI(mc), (void *) mc));
5238 if (mc->mc_snum >= CURSOR_STACK) {
5239 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5240 return MDB_CURSOR_FULL;
5243 mc->mc_top = mc->mc_snum++;
5244 mc->mc_pg[mc->mc_top] = mp;
5245 mc->mc_ki[mc->mc_top] = 0;
5250 /** Find the address of the page corresponding to a given page number.
5251 * @param[in] txn the transaction for this access.
5252 * @param[in] pgno the page number for the page to retrieve.
5253 * @param[out] ret address of a pointer where the page's address will be stored.
5254 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5255 * @return 0 on success, non-zero on failure.
5258 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
5260 MDB_env *env = txn->mt_env;
5264 if (! (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_WRITEMAP))) {
5268 MDB_ID2L dl = tx2->mt_u.dirty_list;
5270 /* Spilled pages were dirtied in this txn and flushed
5271 * because the dirty list got full. Bring this page
5272 * back in from the map (but don't unspill it here,
5273 * leave that unless page_touch happens again).
5275 if (tx2->mt_spill_pgs) {
5276 MDB_ID pn = pgno << 1;
5277 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5278 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5279 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5284 unsigned x = mdb_mid2l_search(dl, pgno);
5285 if (x <= dl[0].mid && dl[x].mid == pgno) {
5291 } while ((tx2 = tx2->mt_parent) != NULL);
5294 if (pgno < txn->mt_next_pgno) {
5296 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5298 DPRINTF(("page %"Z"u not found", pgno));
5299 txn->mt_flags |= MDB_TXN_ERROR;
5300 return MDB_PAGE_NOTFOUND;
5310 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
5311 * The cursor is at the root page, set up the rest of it.
5314 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
5316 MDB_page *mp = mc->mc_pg[mc->mc_top];
5320 while (IS_BRANCH(mp)) {
5324 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
5325 mdb_cassert(mc, NUMKEYS(mp) > 1);
5326 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
5328 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
5330 if (flags & MDB_PS_LAST)
5331 i = NUMKEYS(mp) - 1;
5334 node = mdb_node_search(mc, key, &exact);
5336 i = NUMKEYS(mp) - 1;
5338 i = mc->mc_ki[mc->mc_top];
5340 mdb_cassert(mc, i > 0);
5344 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
5347 mdb_cassert(mc, i < NUMKEYS(mp));
5348 node = NODEPTR(mp, i);
5350 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5353 mc->mc_ki[mc->mc_top] = i;
5354 if ((rc = mdb_cursor_push(mc, mp)))
5357 if (flags & MDB_PS_MODIFY) {
5358 if ((rc = mdb_page_touch(mc)) != 0)
5360 mp = mc->mc_pg[mc->mc_top];
5365 DPRINTF(("internal error, index points to a %02X page!?",
5367 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5368 return MDB_CORRUPTED;
5371 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
5372 key ? DKEY(key) : "null"));
5373 mc->mc_flags |= C_INITIALIZED;
5374 mc->mc_flags &= ~C_EOF;
5379 /** Search for the lowest key under the current branch page.
5380 * This just bypasses a NUMKEYS check in the current page
5381 * before calling mdb_page_search_root(), because the callers
5382 * are all in situations where the current page is known to
5386 mdb_page_search_lowest(MDB_cursor *mc)
5388 MDB_page *mp = mc->mc_pg[mc->mc_top];
5389 MDB_node *node = NODEPTR(mp, 0);
5392 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5395 mc->mc_ki[mc->mc_top] = 0;
5396 if ((rc = mdb_cursor_push(mc, mp)))
5398 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5401 /** Search for the page a given key should be in.
5402 * Push it and its parent pages on the cursor stack.
5403 * @param[in,out] mc the cursor for this operation.
5404 * @param[in] key the key to search for, or NULL for first/last page.
5405 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5406 * are touched (updated with new page numbers).
5407 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5408 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5409 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5410 * @return 0 on success, non-zero on failure.
5413 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5418 /* Make sure the txn is still viable, then find the root from
5419 * the txn's db table and set it as the root of the cursor's stack.
5421 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
5422 DPUTS("transaction may not be used now");
5425 /* Make sure we're using an up-to-date root */
5426 if (*mc->mc_dbflag & DB_STALE) {
5428 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5430 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5431 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5438 MDB_node *leaf = mdb_node_search(&mc2,
5439 &mc->mc_dbx->md_name, &exact);
5441 return MDB_NOTFOUND;
5442 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
5443 return MDB_INCOMPATIBLE; /* not a named DB */
5444 rc = mdb_node_read(mc->mc_txn, leaf, &data);
5447 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5449 /* The txn may not know this DBI, or another process may
5450 * have dropped and recreated the DB with other flags.
5452 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5453 return MDB_INCOMPATIBLE;
5454 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5456 *mc->mc_dbflag &= ~DB_STALE;
5458 root = mc->mc_db->md_root;
5460 if (root == P_INVALID) { /* Tree is empty. */
5461 DPUTS("tree is empty");
5462 return MDB_NOTFOUND;
5466 mdb_cassert(mc, root > 1);
5467 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5468 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
5474 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5475 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5477 if (flags & MDB_PS_MODIFY) {
5478 if ((rc = mdb_page_touch(mc)))
5482 if (flags & MDB_PS_ROOTONLY)
5485 return mdb_page_search_root(mc, key, flags);
5489 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5491 MDB_txn *txn = mc->mc_txn;
5492 pgno_t pg = mp->mp_pgno;
5493 unsigned x = 0, ovpages = mp->mp_pages;
5494 MDB_env *env = txn->mt_env;
5495 MDB_IDL sl = txn->mt_spill_pgs;
5496 MDB_ID pn = pg << 1;
5499 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5500 /* If the page is dirty or on the spill list we just acquired it,
5501 * so we should give it back to our current free list, if any.
5502 * Otherwise put it onto the list of pages we freed in this txn.
5504 * Won't create me_pghead: me_pglast must be inited along with it.
5505 * Unsupported in nested txns: They would need to hide the page
5506 * range in ancestor txns' dirty and spilled lists.
5508 if (env->me_pghead &&
5510 ((mp->mp_flags & P_DIRTY) ||
5511 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5515 MDB_ID2 *dl, ix, iy;
5516 rc = mdb_midl_need(&env->me_pghead, ovpages);
5519 if (!(mp->mp_flags & P_DIRTY)) {
5520 /* This page is no longer spilled */
5527 /* Remove from dirty list */
5528 dl = txn->mt_u.dirty_list;
5530 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5536 mdb_cassert(mc, x > 1);
5538 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5539 txn->mt_flags |= MDB_TXN_ERROR;
5540 return MDB_CORRUPTED;
5543 if (!(env->me_flags & MDB_WRITEMAP))
5544 mdb_dpage_free(env, mp);
5546 /* Insert in me_pghead */
5547 mop = env->me_pghead;
5548 j = mop[0] + ovpages;
5549 for (i = mop[0]; i && mop[i] < pg; i--)
5555 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5559 mc->mc_db->md_overflow_pages -= ovpages;
5563 /** Return the data associated with a given node.
5564 * @param[in] txn The transaction for this operation.
5565 * @param[in] leaf The node being read.
5566 * @param[out] data Updated to point to the node's data.
5567 * @return 0 on success, non-zero on failure.
5570 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5572 MDB_page *omp; /* overflow page */
5576 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5577 data->mv_size = NODEDSZ(leaf);
5578 data->mv_data = NODEDATA(leaf);
5582 /* Read overflow data.
5584 data->mv_size = NODEDSZ(leaf);
5585 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5586 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5587 DPRINTF(("read overflow page %"Z"u failed", pgno));
5590 data->mv_data = METADATA(omp);
5596 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5597 MDB_val *key, MDB_val *data)
5604 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5606 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
5609 if (txn->mt_flags & MDB_TXN_BLOCKED)
5612 mdb_cursor_init(&mc, txn, dbi, &mx);
5613 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5616 /** Find a sibling for a page.
5617 * Replaces the page at the top of the cursor's stack with the
5618 * specified sibling, if one exists.
5619 * @param[in] mc The cursor for this operation.
5620 * @param[in] move_right Non-zero if the right sibling is requested,
5621 * otherwise the left sibling.
5622 * @return 0 on success, non-zero on failure.
5625 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5631 if (mc->mc_snum < 2) {
5632 return MDB_NOTFOUND; /* root has no siblings */
5636 DPRINTF(("parent page is page %"Z"u, index %u",
5637 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5639 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5640 : (mc->mc_ki[mc->mc_top] == 0)) {
5641 DPRINTF(("no more keys left, moving to %s sibling",
5642 move_right ? "right" : "left"));
5643 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5644 /* undo cursor_pop before returning */
5651 mc->mc_ki[mc->mc_top]++;
5653 mc->mc_ki[mc->mc_top]--;
5654 DPRINTF(("just moving to %s index key %u",
5655 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5657 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5659 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5660 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5661 /* mc will be inconsistent if caller does mc_snum++ as above */
5662 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5666 mdb_cursor_push(mc, mp);
5668 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5673 /** Move the cursor to the next data item. */
5675 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5681 if (mc->mc_flags & C_EOF) {
5682 return MDB_NOTFOUND;
5685 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5687 mp = mc->mc_pg[mc->mc_top];
5689 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5690 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5691 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5692 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5693 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5694 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5695 if (rc == MDB_SUCCESS)
5696 MDB_GET_KEY(leaf, key);
5701 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5702 if (op == MDB_NEXT_DUP)
5703 return MDB_NOTFOUND;
5707 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5708 mdb_dbg_pgno(mp), (void *) mc));
5709 if (mc->mc_flags & C_DEL)
5712 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5713 DPUTS("=====> move to next sibling page");
5714 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5715 mc->mc_flags |= C_EOF;
5718 mp = mc->mc_pg[mc->mc_top];
5719 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5721 mc->mc_ki[mc->mc_top]++;
5724 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5725 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5728 key->mv_size = mc->mc_db->md_pad;
5729 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5733 mdb_cassert(mc, IS_LEAF(mp));
5734 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5736 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5737 mdb_xcursor_init1(mc, leaf);
5740 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5743 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5744 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5745 if (rc != MDB_SUCCESS)
5750 MDB_GET_KEY(leaf, key);
5754 /** Move the cursor to the previous data item. */
5756 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5762 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5764 mp = mc->mc_pg[mc->mc_top];
5766 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5767 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5768 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5769 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5770 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5771 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5772 if (rc == MDB_SUCCESS) {
5773 MDB_GET_KEY(leaf, key);
5774 mc->mc_flags &= ~C_EOF;
5780 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5781 if (op == MDB_PREV_DUP)
5782 return MDB_NOTFOUND;
5786 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5787 mdb_dbg_pgno(mp), (void *) mc));
5789 if (mc->mc_ki[mc->mc_top] == 0) {
5790 DPUTS("=====> move to prev sibling page");
5791 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5794 mp = mc->mc_pg[mc->mc_top];
5795 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5796 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5798 mc->mc_ki[mc->mc_top]--;
5800 mc->mc_flags &= ~C_EOF;
5802 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5803 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5806 key->mv_size = mc->mc_db->md_pad;
5807 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5811 mdb_cassert(mc, IS_LEAF(mp));
5812 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5814 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5815 mdb_xcursor_init1(mc, leaf);
5818 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5821 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5822 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5823 if (rc != MDB_SUCCESS)
5828 MDB_GET_KEY(leaf, key);
5832 /** Set the cursor on a specific data item. */
5834 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5835 MDB_cursor_op op, int *exactp)
5839 MDB_node *leaf = NULL;
5842 if (key->mv_size == 0)
5843 return MDB_BAD_VALSIZE;
5846 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5848 /* See if we're already on the right page */
5849 if (mc->mc_flags & C_INITIALIZED) {
5852 mp = mc->mc_pg[mc->mc_top];
5854 mc->mc_ki[mc->mc_top] = 0;
5855 return MDB_NOTFOUND;
5857 if (mp->mp_flags & P_LEAF2) {
5858 nodekey.mv_size = mc->mc_db->md_pad;
5859 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5861 leaf = NODEPTR(mp, 0);
5862 MDB_GET_KEY2(leaf, nodekey);
5864 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5866 /* Probably happens rarely, but first node on the page
5867 * was the one we wanted.
5869 mc->mc_ki[mc->mc_top] = 0;
5876 unsigned int nkeys = NUMKEYS(mp);
5878 if (mp->mp_flags & P_LEAF2) {
5879 nodekey.mv_data = LEAF2KEY(mp,
5880 nkeys-1, nodekey.mv_size);
5882 leaf = NODEPTR(mp, nkeys-1);
5883 MDB_GET_KEY2(leaf, nodekey);
5885 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5887 /* last node was the one we wanted */
5888 mc->mc_ki[mc->mc_top] = nkeys-1;
5894 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5895 /* This is definitely the right page, skip search_page */
5896 if (mp->mp_flags & P_LEAF2) {
5897 nodekey.mv_data = LEAF2KEY(mp,
5898 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5900 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5901 MDB_GET_KEY2(leaf, nodekey);
5903 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5905 /* current node was the one we wanted */
5915 /* If any parents have right-sibs, search.
5916 * Otherwise, there's nothing further.
5918 for (i=0; i<mc->mc_top; i++)
5920 NUMKEYS(mc->mc_pg[i])-1)
5922 if (i == mc->mc_top) {
5923 /* There are no other pages */
5924 mc->mc_ki[mc->mc_top] = nkeys;
5925 return MDB_NOTFOUND;
5929 /* There are no other pages */
5930 mc->mc_ki[mc->mc_top] = 0;
5931 if (op == MDB_SET_RANGE && !exactp) {
5935 return MDB_NOTFOUND;
5939 rc = mdb_page_search(mc, key, 0);
5940 if (rc != MDB_SUCCESS)
5943 mp = mc->mc_pg[mc->mc_top];
5944 mdb_cassert(mc, IS_LEAF(mp));
5947 leaf = mdb_node_search(mc, key, exactp);
5948 if (exactp != NULL && !*exactp) {
5949 /* MDB_SET specified and not an exact match. */
5950 return MDB_NOTFOUND;
5954 DPUTS("===> inexact leaf not found, goto sibling");
5955 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5956 mc->mc_flags |= C_EOF;
5957 return rc; /* no entries matched */
5959 mp = mc->mc_pg[mc->mc_top];
5960 mdb_cassert(mc, IS_LEAF(mp));
5961 leaf = NODEPTR(mp, 0);
5965 mc->mc_flags |= C_INITIALIZED;
5966 mc->mc_flags &= ~C_EOF;
5969 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5970 key->mv_size = mc->mc_db->md_pad;
5971 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5976 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5977 mdb_xcursor_init1(mc, leaf);
5980 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5981 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5982 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5985 if (op == MDB_GET_BOTH) {
5991 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5992 if (rc != MDB_SUCCESS)
5995 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5998 if ((rc = mdb_node_read(mc->mc_txn, leaf, &olddata)) != MDB_SUCCESS)
6000 dcmp = mc->mc_dbx->md_dcmp;
6001 #if UINT_MAX < SIZE_MAX
6002 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6003 dcmp = mdb_cmp_clong;
6005 rc = dcmp(data, &olddata);
6007 if (op == MDB_GET_BOTH || rc > 0)
6008 return MDB_NOTFOUND;
6015 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6016 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
6021 /* The key already matches in all other cases */
6022 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6023 MDB_GET_KEY(leaf, key);
6024 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6029 /** Move the cursor to the first item in the database. */
6031 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6037 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6039 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6040 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6041 if (rc != MDB_SUCCESS)
6044 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6046 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6047 mc->mc_flags |= C_INITIALIZED;
6048 mc->mc_flags &= ~C_EOF;
6050 mc->mc_ki[mc->mc_top] = 0;
6052 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6053 key->mv_size = mc->mc_db->md_pad;
6054 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
6059 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6060 mdb_xcursor_init1(mc, leaf);
6061 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6065 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
6069 MDB_GET_KEY(leaf, key);
6073 /** Move the cursor to the last item in the database. */
6075 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6081 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6083 if (!(mc->mc_flags & C_EOF)) {
6085 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6086 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
6087 if (rc != MDB_SUCCESS)
6090 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6093 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
6094 mc->mc_flags |= C_INITIALIZED|C_EOF;
6095 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6097 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6098 key->mv_size = mc->mc_db->md_pad;
6099 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
6104 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6105 mdb_xcursor_init1(mc, leaf);
6106 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6110 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
6115 MDB_GET_KEY(leaf, key);
6120 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6125 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
6130 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
6134 case MDB_GET_CURRENT:
6135 if (!(mc->mc_flags & C_INITIALIZED)) {
6138 MDB_page *mp = mc->mc_pg[mc->mc_top];
6139 int nkeys = NUMKEYS(mp);
6140 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
6141 mc->mc_ki[mc->mc_top] = nkeys;
6147 key->mv_size = mc->mc_db->md_pad;
6148 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6150 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6151 MDB_GET_KEY(leaf, key);
6153 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6154 if (mc->mc_flags & C_DEL)
6155 mdb_xcursor_init1(mc, leaf);
6156 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
6158 rc = mdb_node_read(mc->mc_txn, leaf, data);
6165 case MDB_GET_BOTH_RANGE:
6170 if (mc->mc_xcursor == NULL) {
6171 rc = MDB_INCOMPATIBLE;
6181 rc = mdb_cursor_set(mc, key, data, op,
6182 op == MDB_SET_RANGE ? NULL : &exact);
6185 case MDB_GET_MULTIPLE:
6186 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6190 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6191 rc = MDB_INCOMPATIBLE;
6195 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6196 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6199 case MDB_NEXT_MULTIPLE:
6204 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6205 rc = MDB_INCOMPATIBLE;
6208 if (!(mc->mc_flags & C_INITIALIZED))
6209 rc = mdb_cursor_first(mc, key, data);
6211 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6212 if (rc == MDB_SUCCESS) {
6213 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6216 mx = &mc->mc_xcursor->mx_cursor;
6217 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
6219 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
6220 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
6228 case MDB_NEXT_NODUP:
6229 if (!(mc->mc_flags & C_INITIALIZED))
6230 rc = mdb_cursor_first(mc, key, data);
6232 rc = mdb_cursor_next(mc, key, data, op);
6236 case MDB_PREV_NODUP:
6237 if (!(mc->mc_flags & C_INITIALIZED)) {
6238 rc = mdb_cursor_last(mc, key, data);
6241 mc->mc_flags |= C_INITIALIZED;
6242 mc->mc_ki[mc->mc_top]++;
6244 rc = mdb_cursor_prev(mc, key, data, op);
6247 rc = mdb_cursor_first(mc, key, data);
6250 mfunc = mdb_cursor_first;
6252 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6256 if (mc->mc_xcursor == NULL) {
6257 rc = MDB_INCOMPATIBLE;
6261 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6262 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6263 MDB_GET_KEY(leaf, key);
6264 rc = mdb_node_read(mc->mc_txn, leaf, data);
6268 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6272 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
6275 rc = mdb_cursor_last(mc, key, data);
6278 mfunc = mdb_cursor_last;
6281 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
6286 if (mc->mc_flags & C_DEL)
6287 mc->mc_flags ^= C_DEL;
6292 /** Touch all the pages in the cursor stack. Set mc_top.
6293 * Makes sure all the pages are writable, before attempting a write operation.
6294 * @param[in] mc The cursor to operate on.
6297 mdb_cursor_touch(MDB_cursor *mc)
6299 int rc = MDB_SUCCESS;
6301 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & DB_DIRTY)) {
6304 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6306 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
6307 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
6310 *mc->mc_dbflag |= DB_DIRTY;
6315 rc = mdb_page_touch(mc);
6316 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
6317 mc->mc_top = mc->mc_snum-1;
6322 /** Do not spill pages to disk if txn is getting full, may fail instead */
6323 #define MDB_NOSPILL 0x8000
6326 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6330 MDB_node *leaf = NULL;
6331 MDB_page *fp, *mp, *sub_root = NULL;
6333 MDB_val xdata, *rdata, dkey, olddata;
6335 int do_sub = 0, insert_key, insert_data;
6336 unsigned int mcount = 0, dcount = 0, nospill;
6339 unsigned int nflags;
6342 if (mc == NULL || key == NULL)
6345 env = mc->mc_txn->mt_env;
6347 /* Check this first so counter will always be zero on any
6350 if (flags & MDB_MULTIPLE) {
6351 dcount = data[1].mv_size;
6352 data[1].mv_size = 0;
6353 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
6354 return MDB_INCOMPATIBLE;
6357 nospill = flags & MDB_NOSPILL;
6358 flags &= ~MDB_NOSPILL;
6360 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6361 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6363 if (key->mv_size-1 >= ENV_MAXKEY(env))
6364 return MDB_BAD_VALSIZE;
6366 #if SIZE_MAX > MAXDATASIZE
6367 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
6368 return MDB_BAD_VALSIZE;
6370 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
6371 return MDB_BAD_VALSIZE;
6374 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
6375 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
6379 if (flags == MDB_CURRENT) {
6380 if (!(mc->mc_flags & C_INITIALIZED))
6383 } else if (mc->mc_db->md_root == P_INVALID) {
6384 /* new database, cursor has nothing to point to */
6387 mc->mc_flags &= ~C_INITIALIZED;
6392 if (flags & MDB_APPEND) {
6394 rc = mdb_cursor_last(mc, &k2, &d2);
6396 rc = mc->mc_dbx->md_cmp(key, &k2);
6399 mc->mc_ki[mc->mc_top]++;
6401 /* new key is <= last key */
6406 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6408 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6409 DPRINTF(("duplicate key [%s]", DKEY(key)));
6411 return MDB_KEYEXIST;
6413 if (rc && rc != MDB_NOTFOUND)
6417 if (mc->mc_flags & C_DEL)
6418 mc->mc_flags ^= C_DEL;
6420 /* Cursor is positioned, check for room in the dirty list */
6422 if (flags & MDB_MULTIPLE) {
6424 xdata.mv_size = data->mv_size * dcount;
6428 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6432 if (rc == MDB_NO_ROOT) {
6434 /* new database, write a root leaf page */
6435 DPUTS("allocating new root leaf page");
6436 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6439 mdb_cursor_push(mc, np);
6440 mc->mc_db->md_root = np->mp_pgno;
6441 mc->mc_db->md_depth++;
6442 *mc->mc_dbflag |= DB_DIRTY;
6443 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6445 np->mp_flags |= P_LEAF2;
6446 mc->mc_flags |= C_INITIALIZED;
6448 /* make sure all cursor pages are writable */
6449 rc2 = mdb_cursor_touch(mc);
6454 insert_key = insert_data = rc;
6456 /* The key does not exist */
6457 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6458 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6459 LEAFSIZE(key, data) > env->me_nodemax)
6461 /* Too big for a node, insert in sub-DB. Set up an empty
6462 * "old sub-page" for prep_subDB to expand to a full page.
6464 fp_flags = P_LEAF|P_DIRTY;
6466 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6467 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6468 olddata.mv_size = PAGEHDRSZ;
6472 /* there's only a key anyway, so this is a no-op */
6473 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6475 unsigned int ksize = mc->mc_db->md_pad;
6476 if (key->mv_size != ksize)
6477 return MDB_BAD_VALSIZE;
6478 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6479 memcpy(ptr, key->mv_data, ksize);
6481 /* if overwriting slot 0 of leaf, need to
6482 * update branch key if there is a parent page
6484 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6485 unsigned short top = mc->mc_top;
6487 /* slot 0 is always an empty key, find real slot */
6488 while (mc->mc_top && !mc->mc_ki[mc->mc_top])
6490 if (mc->mc_ki[mc->mc_top])
6491 rc2 = mdb_update_key(mc, key);
6502 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6503 olddata.mv_size = NODEDSZ(leaf);
6504 olddata.mv_data = NODEDATA(leaf);
6507 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6508 /* Prepare (sub-)page/sub-DB to accept the new item,
6509 * if needed. fp: old sub-page or a header faking
6510 * it. mp: new (sub-)page. offset: growth in page
6511 * size. xdata: node data with new page or DB.
6513 unsigned i, offset = 0;
6514 mp = fp = xdata.mv_data = env->me_pbuf;
6515 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6517 /* Was a single item before, must convert now */
6518 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6520 /* Just overwrite the current item */
6521 if (flags == MDB_CURRENT)
6523 dcmp = mc->mc_dbx->md_dcmp;
6524 #if UINT_MAX < SIZE_MAX
6525 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6526 dcmp = mdb_cmp_clong;
6528 /* does data match? */
6529 if (!dcmp(data, &olddata)) {
6530 if (flags & MDB_NODUPDATA)
6531 return MDB_KEYEXIST;
6536 /* Back up original data item */
6537 dkey.mv_size = olddata.mv_size;
6538 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6540 /* Make sub-page header for the dup items, with dummy body */
6541 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6542 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6543 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6544 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6545 fp->mp_flags |= P_LEAF2;
6546 fp->mp_pad = data->mv_size;
6547 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6549 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6550 (dkey.mv_size & 1) + (data->mv_size & 1);
6552 fp->mp_upper = xdata.mv_size - PAGEBASE;
6553 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6554 } else if (leaf->mn_flags & F_SUBDATA) {
6555 /* Data is on sub-DB, just store it */
6556 flags |= F_DUPDATA|F_SUBDATA;
6559 /* Data is on sub-page */
6560 fp = olddata.mv_data;
6563 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6564 offset = EVEN(NODESIZE + sizeof(indx_t) +
6568 offset = fp->mp_pad;
6569 if (SIZELEFT(fp) < offset) {
6570 offset *= 4; /* space for 4 more */
6573 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6575 fp->mp_flags |= P_DIRTY;
6576 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6577 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6581 xdata.mv_size = olddata.mv_size + offset;
6584 fp_flags = fp->mp_flags;
6585 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6586 /* Too big for a sub-page, convert to sub-DB */
6587 fp_flags &= ~P_SUBP;
6589 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6590 fp_flags |= P_LEAF2;
6591 dummy.md_pad = fp->mp_pad;
6592 dummy.md_flags = MDB_DUPFIXED;
6593 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6594 dummy.md_flags |= MDB_INTEGERKEY;
6600 dummy.md_branch_pages = 0;
6601 dummy.md_leaf_pages = 1;
6602 dummy.md_overflow_pages = 0;
6603 dummy.md_entries = NUMKEYS(fp);
6604 xdata.mv_size = sizeof(MDB_db);
6605 xdata.mv_data = &dummy;
6606 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6608 offset = env->me_psize - olddata.mv_size;
6609 flags |= F_DUPDATA|F_SUBDATA;
6610 dummy.md_root = mp->mp_pgno;
6614 mp->mp_flags = fp_flags | P_DIRTY;
6615 mp->mp_pad = fp->mp_pad;
6616 mp->mp_lower = fp->mp_lower;
6617 mp->mp_upper = fp->mp_upper + offset;
6618 if (fp_flags & P_LEAF2) {
6619 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6621 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6622 olddata.mv_size - fp->mp_upper - PAGEBASE);
6623 for (i=0; i<NUMKEYS(fp); i++)
6624 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6632 mdb_node_del(mc, 0);
6636 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
6637 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
6638 return MDB_INCOMPATIBLE;
6639 /* overflow page overwrites need special handling */
6640 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6643 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6645 memcpy(&pg, olddata.mv_data, sizeof(pg));
6646 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6648 ovpages = omp->mp_pages;
6650 /* Is the ov page large enough? */
6651 if (ovpages >= dpages) {
6652 if (!(omp->mp_flags & P_DIRTY) &&
6653 (level || (env->me_flags & MDB_WRITEMAP)))
6655 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6658 level = 0; /* dirty in this txn or clean */
6661 if (omp->mp_flags & P_DIRTY) {
6662 /* yes, overwrite it. Note in this case we don't
6663 * bother to try shrinking the page if the new data
6664 * is smaller than the overflow threshold.
6667 /* It is writable only in a parent txn */
6668 size_t sz = (size_t) env->me_psize * ovpages, off;
6669 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6675 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6676 mdb_cassert(mc, rc2 == 0);
6677 if (!(flags & MDB_RESERVE)) {
6678 /* Copy end of page, adjusting alignment so
6679 * compiler may copy words instead of bytes.
6681 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6682 memcpy((size_t *)((char *)np + off),
6683 (size_t *)((char *)omp + off), sz - off);
6686 memcpy(np, omp, sz); /* Copy beginning of page */
6689 SETDSZ(leaf, data->mv_size);
6690 if (F_ISSET(flags, MDB_RESERVE))
6691 data->mv_data = METADATA(omp);
6693 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6697 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6699 } else if (data->mv_size == olddata.mv_size) {
6700 /* same size, just replace it. Note that we could
6701 * also reuse this node if the new data is smaller,
6702 * but instead we opt to shrink the node in that case.
6704 if (F_ISSET(flags, MDB_RESERVE))
6705 data->mv_data = olddata.mv_data;
6706 else if (!(mc->mc_flags & C_SUB))
6707 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6709 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6714 mdb_node_del(mc, 0);
6720 nflags = flags & NODE_ADD_FLAGS;
6721 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6722 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6723 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6724 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6726 nflags |= MDB_SPLIT_REPLACE;
6727 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6729 /* There is room already in this leaf page. */
6730 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6731 if (rc == 0 && insert_key) {
6732 /* Adjust other cursors pointing to mp */
6733 MDB_cursor *m2, *m3;
6734 MDB_dbi dbi = mc->mc_dbi;
6735 unsigned i = mc->mc_top;
6736 MDB_page *mp = mc->mc_pg[i];
6738 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6739 if (mc->mc_flags & C_SUB)
6740 m3 = &m2->mc_xcursor->mx_cursor;
6743 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6744 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6751 if (rc == MDB_SUCCESS) {
6752 /* Now store the actual data in the child DB. Note that we're
6753 * storing the user data in the keys field, so there are strict
6754 * size limits on dupdata. The actual data fields of the child
6755 * DB are all zero size.
6758 int xflags, new_dupdata;
6763 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6764 if (flags & MDB_CURRENT) {
6765 xflags = MDB_CURRENT|MDB_NOSPILL;
6767 mdb_xcursor_init1(mc, leaf);
6768 xflags = (flags & MDB_NODUPDATA) ?
6769 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6772 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
6773 new_dupdata = (int)dkey.mv_size;
6774 /* converted, write the original data first */
6776 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6779 /* we've done our job */
6782 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
6783 /* Adjust other cursors pointing to mp */
6785 MDB_xcursor *mx = mc->mc_xcursor;
6786 unsigned i = mc->mc_top;
6787 MDB_page *mp = mc->mc_pg[i];
6789 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6790 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6791 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6792 if (m2->mc_pg[i] == mp) {
6793 if (m2->mc_ki[i] == mc->mc_ki[i]) {
6794 mdb_xcursor_init2(m2, mx, new_dupdata);
6795 } else if (!insert_key) {
6796 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[i]);
6797 if (!(n2->mn_flags & F_SUBDATA))
6798 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
6803 ecount = mc->mc_xcursor->mx_db.md_entries;
6804 if (flags & MDB_APPENDDUP)
6805 xflags |= MDB_APPEND;
6806 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6807 if (flags & F_SUBDATA) {
6808 void *db = NODEDATA(leaf);
6809 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6811 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6813 /* Increment count unless we just replaced an existing item. */
6815 mc->mc_db->md_entries++;
6817 /* Invalidate txn if we created an empty sub-DB */
6820 /* If we succeeded and the key didn't exist before,
6821 * make sure the cursor is marked valid.
6823 mc->mc_flags |= C_INITIALIZED;
6825 if (flags & MDB_MULTIPLE) {
6828 /* let caller know how many succeeded, if any */
6829 data[1].mv_size = mcount;
6830 if (mcount < dcount) {
6831 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6832 insert_key = insert_data = 0;
6839 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6842 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6847 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6853 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6854 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6856 if (!(mc->mc_flags & C_INITIALIZED))
6859 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6860 return MDB_NOTFOUND;
6862 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6865 rc = mdb_cursor_touch(mc);
6869 mp = mc->mc_pg[mc->mc_top];
6872 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6874 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6875 if (flags & MDB_NODUPDATA) {
6876 /* mdb_cursor_del0() will subtract the final entry */
6877 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6879 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6880 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6882 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6885 /* If sub-DB still has entries, we're done */
6886 if (mc->mc_xcursor->mx_db.md_entries) {
6887 if (leaf->mn_flags & F_SUBDATA) {
6888 /* update subDB info */
6889 void *db = NODEDATA(leaf);
6890 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6893 /* shrink fake page */
6894 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6895 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6896 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6897 /* fix other sub-DB cursors pointed at fake pages on this page */
6898 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6899 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6900 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6901 if (m2->mc_pg[mc->mc_top] == mp) {
6902 if (m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top]) {
6903 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6905 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
6906 if (!(n2->mn_flags & F_SUBDATA))
6907 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
6912 mc->mc_db->md_entries--;
6913 mc->mc_flags |= C_DEL;
6916 /* otherwise fall thru and delete the sub-DB */
6919 if (leaf->mn_flags & F_SUBDATA) {
6920 /* add all the child DB's pages to the free list */
6921 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6926 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
6927 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
6928 rc = MDB_INCOMPATIBLE;
6932 /* add overflow pages to free list */
6933 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6937 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6938 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6939 (rc = mdb_ovpage_free(mc, omp)))
6944 return mdb_cursor_del0(mc);
6947 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6951 /** Allocate and initialize new pages for a database.
6952 * @param[in] mc a cursor on the database being added to.
6953 * @param[in] flags flags defining what type of page is being allocated.
6954 * @param[in] num the number of pages to allocate. This is usually 1,
6955 * unless allocating overflow pages for a large record.
6956 * @param[out] mp Address of a page, or NULL on failure.
6957 * @return 0 on success, non-zero on failure.
6960 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6965 if ((rc = mdb_page_alloc(mc, num, &np)))
6967 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6968 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6969 np->mp_flags = flags | P_DIRTY;
6970 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
6971 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
6974 mc->mc_db->md_branch_pages++;
6975 else if (IS_LEAF(np))
6976 mc->mc_db->md_leaf_pages++;
6977 else if (IS_OVERFLOW(np)) {
6978 mc->mc_db->md_overflow_pages += num;
6986 /** Calculate the size of a leaf node.
6987 * The size depends on the environment's page size; if a data item
6988 * is too large it will be put onto an overflow page and the node
6989 * size will only include the key and not the data. Sizes are always
6990 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6991 * of the #MDB_node headers.
6992 * @param[in] env The environment handle.
6993 * @param[in] key The key for the node.
6994 * @param[in] data The data for the node.
6995 * @return The number of bytes needed to store the node.
6998 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
7002 sz = LEAFSIZE(key, data);
7003 if (sz > env->me_nodemax) {
7004 /* put on overflow page */
7005 sz -= data->mv_size - sizeof(pgno_t);
7008 return EVEN(sz + sizeof(indx_t));
7011 /** Calculate the size of a branch node.
7012 * The size should depend on the environment's page size but since
7013 * we currently don't support spilling large keys onto overflow
7014 * pages, it's simply the size of the #MDB_node header plus the
7015 * size of the key. Sizes are always rounded up to an even number
7016 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7017 * @param[in] env The environment handle.
7018 * @param[in] key The key for the node.
7019 * @return The number of bytes needed to store the node.
7022 mdb_branch_size(MDB_env *env, MDB_val *key)
7027 if (sz > env->me_nodemax) {
7028 /* put on overflow page */
7029 /* not implemented */
7030 /* sz -= key->size - sizeof(pgno_t); */
7033 return sz + sizeof(indx_t);
7036 /** Add a node to the page pointed to by the cursor.
7037 * @param[in] mc The cursor for this operation.
7038 * @param[in] indx The index on the page where the new node should be added.
7039 * @param[in] key The key for the new node.
7040 * @param[in] data The data for the new node, if any.
7041 * @param[in] pgno The page number, if adding a branch node.
7042 * @param[in] flags Flags for the node.
7043 * @return 0 on success, non-zero on failure. Possible errors are:
7045 * <li>ENOMEM - failed to allocate overflow pages for the node.
7046 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
7047 * should never happen since all callers already calculate the
7048 * page's free space before calling this function.
7052 mdb_node_add(MDB_cursor *mc, indx_t indx,
7053 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
7056 size_t node_size = NODESIZE;
7060 MDB_page *mp = mc->mc_pg[mc->mc_top];
7061 MDB_page *ofp = NULL; /* overflow page */
7065 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
7067 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
7068 IS_LEAF(mp) ? "leaf" : "branch",
7069 IS_SUBP(mp) ? "sub-" : "",
7070 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
7071 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
7074 /* Move higher keys up one slot. */
7075 int ksize = mc->mc_db->md_pad, dif;
7076 char *ptr = LEAF2KEY(mp, indx, ksize);
7077 dif = NUMKEYS(mp) - indx;
7079 memmove(ptr+ksize, ptr, dif*ksize);
7080 /* insert new key */
7081 memcpy(ptr, key->mv_data, ksize);
7083 /* Just using these for counting */
7084 mp->mp_lower += sizeof(indx_t);
7085 mp->mp_upper -= ksize - sizeof(indx_t);
7089 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
7091 node_size += key->mv_size;
7093 mdb_cassert(mc, key && data);
7094 if (F_ISSET(flags, F_BIGDATA)) {
7095 /* Data already on overflow page. */
7096 node_size += sizeof(pgno_t);
7097 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
7098 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
7100 /* Put data on overflow page. */
7101 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
7102 data->mv_size, node_size+data->mv_size));
7103 node_size = EVEN(node_size + sizeof(pgno_t));
7104 if ((ssize_t)node_size > room)
7106 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
7108 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
7112 node_size += data->mv_size;
7115 node_size = EVEN(node_size);
7116 if ((ssize_t)node_size > room)
7120 /* Move higher pointers up one slot. */
7121 for (i = NUMKEYS(mp); i > indx; i--)
7122 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
7124 /* Adjust free space offsets. */
7125 ofs = mp->mp_upper - node_size;
7126 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
7127 mp->mp_ptrs[indx] = ofs;
7129 mp->mp_lower += sizeof(indx_t);
7131 /* Write the node data. */
7132 node = NODEPTR(mp, indx);
7133 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
7134 node->mn_flags = flags;
7136 SETDSZ(node,data->mv_size);
7141 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7144 ndata = NODEDATA(node);
7146 if (F_ISSET(flags, F_BIGDATA))
7147 memcpy(ndata, data->mv_data, sizeof(pgno_t));
7148 else if (F_ISSET(flags, MDB_RESERVE))
7149 data->mv_data = ndata;
7151 memcpy(ndata, data->mv_data, data->mv_size);
7153 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
7154 ndata = METADATA(ofp);
7155 if (F_ISSET(flags, MDB_RESERVE))
7156 data->mv_data = ndata;
7158 memcpy(ndata, data->mv_data, data->mv_size);
7165 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
7166 mdb_dbg_pgno(mp), NUMKEYS(mp)));
7167 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
7168 DPRINTF(("node size = %"Z"u", node_size));
7169 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7170 return MDB_PAGE_FULL;
7173 /** Delete the specified node from a page.
7174 * @param[in] mc Cursor pointing to the node to delete.
7175 * @param[in] ksize The size of a node. Only used if the page is
7176 * part of a #MDB_DUPFIXED database.
7179 mdb_node_del(MDB_cursor *mc, int ksize)
7181 MDB_page *mp = mc->mc_pg[mc->mc_top];
7182 indx_t indx = mc->mc_ki[mc->mc_top];
7184 indx_t i, j, numkeys, ptr;
7188 DPRINTF(("delete node %u on %s page %"Z"u", indx,
7189 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
7190 numkeys = NUMKEYS(mp);
7191 mdb_cassert(mc, indx < numkeys);
7194 int x = numkeys - 1 - indx;
7195 base = LEAF2KEY(mp, indx, ksize);
7197 memmove(base, base + ksize, x * ksize);
7198 mp->mp_lower -= sizeof(indx_t);
7199 mp->mp_upper += ksize - sizeof(indx_t);
7203 node = NODEPTR(mp, indx);
7204 sz = NODESIZE + node->mn_ksize;
7206 if (F_ISSET(node->mn_flags, F_BIGDATA))
7207 sz += sizeof(pgno_t);
7209 sz += NODEDSZ(node);
7213 ptr = mp->mp_ptrs[indx];
7214 for (i = j = 0; i < numkeys; i++) {
7216 mp->mp_ptrs[j] = mp->mp_ptrs[i];
7217 if (mp->mp_ptrs[i] < ptr)
7218 mp->mp_ptrs[j] += sz;
7223 base = (char *)mp + mp->mp_upper + PAGEBASE;
7224 memmove(base + sz, base, ptr - mp->mp_upper);
7226 mp->mp_lower -= sizeof(indx_t);
7230 /** Compact the main page after deleting a node on a subpage.
7231 * @param[in] mp The main page to operate on.
7232 * @param[in] indx The index of the subpage on the main page.
7235 mdb_node_shrink(MDB_page *mp, indx_t indx)
7240 indx_t delta, nsize, len, ptr;
7243 node = NODEPTR(mp, indx);
7244 sp = (MDB_page *)NODEDATA(node);
7245 delta = SIZELEFT(sp);
7246 nsize = NODEDSZ(node) - delta;
7248 /* Prepare to shift upward, set len = length(subpage part to shift) */
7252 return; /* do not make the node uneven-sized */
7254 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
7255 for (i = NUMKEYS(sp); --i >= 0; )
7256 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
7259 sp->mp_upper = sp->mp_lower;
7260 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
7261 SETDSZ(node, nsize);
7263 /* Shift <lower nodes...initial part of subpage> upward */
7264 base = (char *)mp + mp->mp_upper + PAGEBASE;
7265 memmove(base + delta, base, (char *)sp + len - base);
7267 ptr = mp->mp_ptrs[indx];
7268 for (i = NUMKEYS(mp); --i >= 0; ) {
7269 if (mp->mp_ptrs[i] <= ptr)
7270 mp->mp_ptrs[i] += delta;
7272 mp->mp_upper += delta;
7275 /** Initial setup of a sorted-dups cursor.
7276 * Sorted duplicates are implemented as a sub-database for the given key.
7277 * The duplicate data items are actually keys of the sub-database.
7278 * Operations on the duplicate data items are performed using a sub-cursor
7279 * initialized when the sub-database is first accessed. This function does
7280 * the preliminary setup of the sub-cursor, filling in the fields that
7281 * depend only on the parent DB.
7282 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7285 mdb_xcursor_init0(MDB_cursor *mc)
7287 MDB_xcursor *mx = mc->mc_xcursor;
7289 mx->mx_cursor.mc_xcursor = NULL;
7290 mx->mx_cursor.mc_txn = mc->mc_txn;
7291 mx->mx_cursor.mc_db = &mx->mx_db;
7292 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
7293 mx->mx_cursor.mc_dbi = mc->mc_dbi;
7294 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
7295 mx->mx_cursor.mc_snum = 0;
7296 mx->mx_cursor.mc_top = 0;
7297 mx->mx_cursor.mc_flags = C_SUB;
7298 mx->mx_dbx.md_name.mv_size = 0;
7299 mx->mx_dbx.md_name.mv_data = NULL;
7300 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
7301 mx->mx_dbx.md_dcmp = NULL;
7302 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
7305 /** Final setup of a sorted-dups cursor.
7306 * Sets up the fields that depend on the data from the main cursor.
7307 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7308 * @param[in] node The data containing the #MDB_db record for the
7309 * sorted-dup database.
7312 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
7314 MDB_xcursor *mx = mc->mc_xcursor;
7316 if (node->mn_flags & F_SUBDATA) {
7317 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
7318 mx->mx_cursor.mc_pg[0] = 0;
7319 mx->mx_cursor.mc_snum = 0;
7320 mx->mx_cursor.mc_top = 0;
7321 mx->mx_cursor.mc_flags = C_SUB;
7323 MDB_page *fp = NODEDATA(node);
7324 mx->mx_db.md_pad = 0;
7325 mx->mx_db.md_flags = 0;
7326 mx->mx_db.md_depth = 1;
7327 mx->mx_db.md_branch_pages = 0;
7328 mx->mx_db.md_leaf_pages = 1;
7329 mx->mx_db.md_overflow_pages = 0;
7330 mx->mx_db.md_entries = NUMKEYS(fp);
7331 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
7332 mx->mx_cursor.mc_snum = 1;
7333 mx->mx_cursor.mc_top = 0;
7334 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
7335 mx->mx_cursor.mc_pg[0] = fp;
7336 mx->mx_cursor.mc_ki[0] = 0;
7337 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7338 mx->mx_db.md_flags = MDB_DUPFIXED;
7339 mx->mx_db.md_pad = fp->mp_pad;
7340 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7341 mx->mx_db.md_flags |= MDB_INTEGERKEY;
7344 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7345 mx->mx_db.md_root));
7346 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
7347 #if UINT_MAX < SIZE_MAX
7348 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
7349 mx->mx_dbx.md_cmp = mdb_cmp_clong;
7354 /** Fixup a sorted-dups cursor due to underlying update.
7355 * Sets up some fields that depend on the data from the main cursor.
7356 * Almost the same as init1, but skips initialization steps if the
7357 * xcursor had already been used.
7358 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
7359 * @param[in] src_mx The xcursor of an up-to-date cursor.
7360 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
7363 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
7365 MDB_xcursor *mx = mc->mc_xcursor;
7368 mx->mx_cursor.mc_snum = 1;
7369 mx->mx_cursor.mc_top = 0;
7370 mx->mx_cursor.mc_flags |= C_INITIALIZED;
7371 mx->mx_cursor.mc_ki[0] = 0;
7372 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
7373 #if UINT_MAX < SIZE_MAX
7374 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
7376 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
7379 mx->mx_db = src_mx->mx_db;
7380 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
7381 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7382 mx->mx_db.md_root));
7385 /** Initialize a cursor for a given transaction and database. */
7387 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
7390 mc->mc_backup = NULL;
7393 mc->mc_db = &txn->mt_dbs[dbi];
7394 mc->mc_dbx = &txn->mt_dbxs[dbi];
7395 mc->mc_dbflag = &txn->mt_dbflags[dbi];
7401 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
7402 mdb_tassert(txn, mx != NULL);
7403 mc->mc_xcursor = mx;
7404 mdb_xcursor_init0(mc);
7406 mc->mc_xcursor = NULL;
7408 if (*mc->mc_dbflag & DB_STALE) {
7409 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
7414 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
7417 size_t size = sizeof(MDB_cursor);
7419 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
7422 if (txn->mt_flags & MDB_TXN_BLOCKED)
7425 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7428 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
7429 size += sizeof(MDB_xcursor);
7431 if ((mc = malloc(size)) != NULL) {
7432 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
7433 if (txn->mt_cursors) {
7434 mc->mc_next = txn->mt_cursors[dbi];
7435 txn->mt_cursors[dbi] = mc;
7436 mc->mc_flags |= C_UNTRACK;
7448 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
7450 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
7453 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
7456 if (txn->mt_flags & MDB_TXN_BLOCKED)
7459 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
7463 /* Return the count of duplicate data items for the current key */
7465 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7469 if (mc == NULL || countp == NULL)
7472 if (mc->mc_xcursor == NULL)
7473 return MDB_INCOMPATIBLE;
7475 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
7478 if (!(mc->mc_flags & C_INITIALIZED))
7481 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
7482 return MDB_NOTFOUND;
7484 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7485 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7488 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7491 *countp = mc->mc_xcursor->mx_db.md_entries;
7497 mdb_cursor_close(MDB_cursor *mc)
7499 if (mc && !mc->mc_backup) {
7500 /* remove from txn, if tracked */
7501 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7502 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7503 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7505 *prev = mc->mc_next;
7512 mdb_cursor_txn(MDB_cursor *mc)
7514 if (!mc) return NULL;
7519 mdb_cursor_dbi(MDB_cursor *mc)
7524 /** Replace the key for a branch node with a new key.
7525 * @param[in] mc Cursor pointing to the node to operate on.
7526 * @param[in] key The new key to use.
7527 * @return 0 on success, non-zero on failure.
7530 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7536 int delta, ksize, oksize;
7537 indx_t ptr, i, numkeys, indx;
7540 indx = mc->mc_ki[mc->mc_top];
7541 mp = mc->mc_pg[mc->mc_top];
7542 node = NODEPTR(mp, indx);
7543 ptr = mp->mp_ptrs[indx];
7547 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7548 k2.mv_data = NODEKEY(node);
7549 k2.mv_size = node->mn_ksize;
7550 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7552 mdb_dkey(&k2, kbuf2),
7558 /* Sizes must be 2-byte aligned. */
7559 ksize = EVEN(key->mv_size);
7560 oksize = EVEN(node->mn_ksize);
7561 delta = ksize - oksize;
7563 /* Shift node contents if EVEN(key length) changed. */
7565 if (delta > 0 && SIZELEFT(mp) < delta) {
7567 /* not enough space left, do a delete and split */
7568 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7569 pgno = NODEPGNO(node);
7570 mdb_node_del(mc, 0);
7571 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7574 numkeys = NUMKEYS(mp);
7575 for (i = 0; i < numkeys; i++) {
7576 if (mp->mp_ptrs[i] <= ptr)
7577 mp->mp_ptrs[i] -= delta;
7580 base = (char *)mp + mp->mp_upper + PAGEBASE;
7581 len = ptr - mp->mp_upper + NODESIZE;
7582 memmove(base - delta, base, len);
7583 mp->mp_upper -= delta;
7585 node = NODEPTR(mp, indx);
7588 /* But even if no shift was needed, update ksize */
7589 if (node->mn_ksize != key->mv_size)
7590 node->mn_ksize = key->mv_size;
7593 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7599 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7601 /** Move a node from csrc to cdst.
7604 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
7611 unsigned short flags;
7615 /* Mark src and dst as dirty. */
7616 if ((rc = mdb_page_touch(csrc)) ||
7617 (rc = mdb_page_touch(cdst)))
7620 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7621 key.mv_size = csrc->mc_db->md_pad;
7622 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7624 data.mv_data = NULL;
7628 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7629 mdb_cassert(csrc, !((size_t)srcnode & 1));
7630 srcpg = NODEPGNO(srcnode);
7631 flags = srcnode->mn_flags;
7632 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7633 unsigned int snum = csrc->mc_snum;
7635 /* must find the lowest key below src */
7636 rc = mdb_page_search_lowest(csrc);
7639 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7640 key.mv_size = csrc->mc_db->md_pad;
7641 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7643 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7644 key.mv_size = NODEKSZ(s2);
7645 key.mv_data = NODEKEY(s2);
7647 csrc->mc_snum = snum--;
7648 csrc->mc_top = snum;
7650 key.mv_size = NODEKSZ(srcnode);
7651 key.mv_data = NODEKEY(srcnode);
7653 data.mv_size = NODEDSZ(srcnode);
7654 data.mv_data = NODEDATA(srcnode);
7656 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7657 unsigned int snum = cdst->mc_snum;
7660 /* must find the lowest key below dst */
7661 mdb_cursor_copy(cdst, &mn);
7662 rc = mdb_page_search_lowest(&mn);
7665 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7666 bkey.mv_size = mn.mc_db->md_pad;
7667 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7669 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7670 bkey.mv_size = NODEKSZ(s2);
7671 bkey.mv_data = NODEKEY(s2);
7673 mn.mc_snum = snum--;
7676 rc = mdb_update_key(&mn, &bkey);
7681 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7682 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7683 csrc->mc_ki[csrc->mc_top],
7685 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7686 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7688 /* Add the node to the destination page.
7690 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7691 if (rc != MDB_SUCCESS)
7694 /* Delete the node from the source page.
7696 mdb_node_del(csrc, key.mv_size);
7699 /* Adjust other cursors pointing to mp */
7700 MDB_cursor *m2, *m3;
7701 MDB_dbi dbi = csrc->mc_dbi;
7704 mp = cdst->mc_pg[csrc->mc_top];
7705 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7706 if (csrc->mc_flags & C_SUB)
7707 m3 = &m2->mc_xcursor->mx_cursor;
7710 if (m3 == cdst) continue;
7711 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] >=
7712 cdst->mc_ki[csrc->mc_top]) {
7713 m3->mc_ki[csrc->mc_top]++;
7717 mp = csrc->mc_pg[csrc->mc_top];
7718 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7719 if (csrc->mc_flags & C_SUB)
7720 m3 = &m2->mc_xcursor->mx_cursor;
7723 if (m3 == csrc) continue;
7724 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
7725 csrc->mc_ki[csrc->mc_top]) {
7726 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7727 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7732 /* Update the parent separators.
7734 if (csrc->mc_ki[csrc->mc_top] == 0) {
7735 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7736 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7737 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7739 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7740 key.mv_size = NODEKSZ(srcnode);
7741 key.mv_data = NODEKEY(srcnode);
7743 DPRINTF(("update separator for source page %"Z"u to [%s]",
7744 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7745 mdb_cursor_copy(csrc, &mn);
7748 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7751 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7753 indx_t ix = csrc->mc_ki[csrc->mc_top];
7754 nullkey.mv_size = 0;
7755 csrc->mc_ki[csrc->mc_top] = 0;
7756 rc = mdb_update_key(csrc, &nullkey);
7757 csrc->mc_ki[csrc->mc_top] = ix;
7758 mdb_cassert(csrc, rc == MDB_SUCCESS);
7762 if (cdst->mc_ki[cdst->mc_top] == 0) {
7763 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7764 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7765 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7767 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7768 key.mv_size = NODEKSZ(srcnode);
7769 key.mv_data = NODEKEY(srcnode);
7771 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7772 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7773 mdb_cursor_copy(cdst, &mn);
7776 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7779 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7781 indx_t ix = cdst->mc_ki[cdst->mc_top];
7782 nullkey.mv_size = 0;
7783 cdst->mc_ki[cdst->mc_top] = 0;
7784 rc = mdb_update_key(cdst, &nullkey);
7785 cdst->mc_ki[cdst->mc_top] = ix;
7786 mdb_cassert(cdst, rc == MDB_SUCCESS);
7793 /** Merge one page into another.
7794 * The nodes from the page pointed to by \b csrc will
7795 * be copied to the page pointed to by \b cdst and then
7796 * the \b csrc page will be freed.
7797 * @param[in] csrc Cursor pointing to the source page.
7798 * @param[in] cdst Cursor pointing to the destination page.
7799 * @return 0 on success, non-zero on failure.
7802 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7804 MDB_page *psrc, *pdst;
7811 psrc = csrc->mc_pg[csrc->mc_top];
7812 pdst = cdst->mc_pg[cdst->mc_top];
7814 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7816 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7817 mdb_cassert(csrc, cdst->mc_snum > 1);
7819 /* Mark dst as dirty. */
7820 if ((rc = mdb_page_touch(cdst)))
7823 /* Move all nodes from src to dst.
7825 j = nkeys = NUMKEYS(pdst);
7826 if (IS_LEAF2(psrc)) {
7827 key.mv_size = csrc->mc_db->md_pad;
7828 key.mv_data = METADATA(psrc);
7829 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7830 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7831 if (rc != MDB_SUCCESS)
7833 key.mv_data = (char *)key.mv_data + key.mv_size;
7836 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7837 srcnode = NODEPTR(psrc, i);
7838 if (i == 0 && IS_BRANCH(psrc)) {
7841 mdb_cursor_copy(csrc, &mn);
7842 /* must find the lowest key below src */
7843 rc = mdb_page_search_lowest(&mn);
7846 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7847 key.mv_size = mn.mc_db->md_pad;
7848 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7850 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7851 key.mv_size = NODEKSZ(s2);
7852 key.mv_data = NODEKEY(s2);
7855 key.mv_size = srcnode->mn_ksize;
7856 key.mv_data = NODEKEY(srcnode);
7859 data.mv_size = NODEDSZ(srcnode);
7860 data.mv_data = NODEDATA(srcnode);
7861 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7862 if (rc != MDB_SUCCESS)
7867 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7868 pdst->mp_pgno, NUMKEYS(pdst),
7869 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7871 /* Unlink the src page from parent and add to free list.
7874 mdb_node_del(csrc, 0);
7875 if (csrc->mc_ki[csrc->mc_top] == 0) {
7877 rc = mdb_update_key(csrc, &key);
7885 psrc = csrc->mc_pg[csrc->mc_top];
7886 /* If not operating on FreeDB, allow this page to be reused
7887 * in this txn. Otherwise just add to free list.
7889 rc = mdb_page_loose(csrc, psrc);
7893 csrc->mc_db->md_leaf_pages--;
7895 csrc->mc_db->md_branch_pages--;
7897 /* Adjust other cursors pointing to mp */
7898 MDB_cursor *m2, *m3;
7899 MDB_dbi dbi = csrc->mc_dbi;
7901 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7902 if (csrc->mc_flags & C_SUB)
7903 m3 = &m2->mc_xcursor->mx_cursor;
7906 if (m3 == csrc) continue;
7907 if (m3->mc_snum < csrc->mc_snum) continue;
7908 if (m3->mc_pg[csrc->mc_top] == psrc) {
7909 m3->mc_pg[csrc->mc_top] = pdst;
7910 m3->mc_ki[csrc->mc_top] += nkeys;
7915 unsigned int snum = cdst->mc_snum;
7916 uint16_t depth = cdst->mc_db->md_depth;
7917 mdb_cursor_pop(cdst);
7918 rc = mdb_rebalance(cdst);
7919 /* Did the tree height change? */
7920 if (depth != cdst->mc_db->md_depth)
7921 snum += cdst->mc_db->md_depth - depth;
7922 cdst->mc_snum = snum;
7923 cdst->mc_top = snum-1;
7928 /** Copy the contents of a cursor.
7929 * @param[in] csrc The cursor to copy from.
7930 * @param[out] cdst The cursor to copy to.
7933 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7937 cdst->mc_txn = csrc->mc_txn;
7938 cdst->mc_dbi = csrc->mc_dbi;
7939 cdst->mc_db = csrc->mc_db;
7940 cdst->mc_dbx = csrc->mc_dbx;
7941 cdst->mc_snum = csrc->mc_snum;
7942 cdst->mc_top = csrc->mc_top;
7943 cdst->mc_flags = csrc->mc_flags;
7945 for (i=0; i<csrc->mc_snum; i++) {
7946 cdst->mc_pg[i] = csrc->mc_pg[i];
7947 cdst->mc_ki[i] = csrc->mc_ki[i];
7951 /** Rebalance the tree after a delete operation.
7952 * @param[in] mc Cursor pointing to the page where rebalancing
7954 * @return 0 on success, non-zero on failure.
7957 mdb_rebalance(MDB_cursor *mc)
7961 unsigned int ptop, minkeys, thresh;
7965 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
7970 thresh = FILL_THRESHOLD;
7972 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7973 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7974 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7975 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7977 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
7978 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7979 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7980 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7984 if (mc->mc_snum < 2) {
7985 MDB_page *mp = mc->mc_pg[0];
7987 DPUTS("Can't rebalance a subpage, ignoring");
7990 if (NUMKEYS(mp) == 0) {
7991 DPUTS("tree is completely empty");
7992 mc->mc_db->md_root = P_INVALID;
7993 mc->mc_db->md_depth = 0;
7994 mc->mc_db->md_leaf_pages = 0;
7995 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7998 /* Adjust cursors pointing to mp */
8001 mc->mc_flags &= ~C_INITIALIZED;
8003 MDB_cursor *m2, *m3;
8004 MDB_dbi dbi = mc->mc_dbi;
8006 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8007 if (mc->mc_flags & C_SUB)
8008 m3 = &m2->mc_xcursor->mx_cursor;
8011 if (m3->mc_snum < mc->mc_snum) continue;
8012 if (m3->mc_pg[0] == mp) {
8015 m3->mc_flags &= ~C_INITIALIZED;
8019 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
8021 DPUTS("collapsing root page!");
8022 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8025 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
8026 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
8029 mc->mc_db->md_depth--;
8030 mc->mc_db->md_branch_pages--;
8031 mc->mc_ki[0] = mc->mc_ki[1];
8032 for (i = 1; i<mc->mc_db->md_depth; i++) {
8033 mc->mc_pg[i] = mc->mc_pg[i+1];
8034 mc->mc_ki[i] = mc->mc_ki[i+1];
8037 /* Adjust other cursors pointing to mp */
8038 MDB_cursor *m2, *m3;
8039 MDB_dbi dbi = mc->mc_dbi;
8041 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8042 if (mc->mc_flags & C_SUB)
8043 m3 = &m2->mc_xcursor->mx_cursor;
8046 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
8047 if (m3->mc_pg[0] == mp) {
8048 for (i=0; i<m3->mc_snum; i++) {
8049 m3->mc_pg[i] = m3->mc_pg[i+1];
8050 m3->mc_ki[i] = m3->mc_ki[i+1];
8058 DPUTS("root page doesn't need rebalancing");
8062 /* The parent (branch page) must have at least 2 pointers,
8063 * otherwise the tree is invalid.
8065 ptop = mc->mc_top-1;
8066 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
8068 /* Leaf page fill factor is below the threshold.
8069 * Try to move keys from left or right neighbor, or
8070 * merge with a neighbor page.
8075 mdb_cursor_copy(mc, &mn);
8076 mn.mc_xcursor = NULL;
8078 oldki = mc->mc_ki[mc->mc_top];
8079 if (mc->mc_ki[ptop] == 0) {
8080 /* We're the leftmost leaf in our parent.
8082 DPUTS("reading right neighbor");
8084 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8085 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
8088 mn.mc_ki[mn.mc_top] = 0;
8089 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
8091 /* There is at least one neighbor to the left.
8093 DPUTS("reading left neighbor");
8095 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8096 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
8099 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
8100 mc->mc_ki[mc->mc_top] = 0;
8103 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
8104 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
8105 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
8107 /* If the neighbor page is above threshold and has enough keys,
8108 * move one key from it. Otherwise we should try to merge them.
8109 * (A branch page must never have less than 2 keys.)
8111 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
8112 rc = mdb_node_move(&mn, mc);
8113 if (mc->mc_ki[mc->mc_top-1]) {
8117 if (mc->mc_ki[ptop] == 0) {
8118 rc = mdb_page_merge(&mn, mc);
8121 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
8122 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
8123 /* We want mdb_rebalance to find mn when doing fixups */
8124 if (mc->mc_flags & C_SUB) {
8125 dummy.mc_next = mc->mc_txn->mt_cursors[mc->mc_dbi];
8126 mc->mc_txn->mt_cursors[mc->mc_dbi] = &dummy;
8127 dummy.mc_xcursor = (MDB_xcursor *)&mn;
8129 mn.mc_next = mc->mc_txn->mt_cursors[mc->mc_dbi];
8130 mc->mc_txn->mt_cursors[mc->mc_dbi] = &mn;
8132 rc = mdb_page_merge(mc, &mn);
8133 if (mc->mc_flags & C_SUB)
8134 mc->mc_txn->mt_cursors[mc->mc_dbi] = dummy.mc_next;
8136 mc->mc_txn->mt_cursors[mc->mc_dbi] = mn.mc_next;
8137 mdb_cursor_copy(&mn, mc);
8139 mc->mc_flags &= ~C_EOF;
8141 mc->mc_ki[mc->mc_top] = oldki;
8145 /** Complete a delete operation started by #mdb_cursor_del(). */
8147 mdb_cursor_del0(MDB_cursor *mc)
8153 MDB_cursor *m2, *m3;
8154 MDB_dbi dbi = mc->mc_dbi;
8156 ki = mc->mc_ki[mc->mc_top];
8157 mp = mc->mc_pg[mc->mc_top];
8158 mdb_node_del(mc, mc->mc_db->md_pad);
8159 mc->mc_db->md_entries--;
8161 /* Adjust other cursors pointing to mp */
8162 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8163 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8164 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8166 if (m3 == mc || m3->mc_snum < mc->mc_snum)
8168 if (m3->mc_pg[mc->mc_top] == mp) {
8169 if (m3->mc_ki[mc->mc_top] >= ki) {
8170 m3->mc_flags |= C_DEL;
8171 if (m3->mc_ki[mc->mc_top] > ki)
8172 m3->mc_ki[mc->mc_top]--;
8173 else if (mc->mc_db->md_flags & MDB_DUPSORT)
8174 m3->mc_xcursor->mx_cursor.mc_flags |= C_EOF;
8179 rc = mdb_rebalance(mc);
8181 if (rc == MDB_SUCCESS) {
8182 /* DB is totally empty now, just bail out.
8183 * Other cursors adjustments were already done
8184 * by mdb_rebalance and aren't needed here.
8189 mp = mc->mc_pg[mc->mc_top];
8190 nkeys = NUMKEYS(mp);
8192 /* Adjust other cursors pointing to mp */
8193 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
8194 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8195 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8197 if (m3->mc_snum < mc->mc_snum)
8199 if (m3->mc_pg[mc->mc_top] == mp) {
8200 /* if m3 points past last node in page, find next sibling */
8201 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8202 rc = mdb_cursor_sibling(m3, 1);
8203 if (rc == MDB_NOTFOUND) {
8204 m3->mc_flags |= C_EOF;
8210 mc->mc_flags |= C_DEL;
8214 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8219 mdb_del(MDB_txn *txn, MDB_dbi dbi,
8220 MDB_val *key, MDB_val *data)
8222 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8225 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8226 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8228 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
8229 /* must ignore any data */
8233 return mdb_del0(txn, dbi, key, data, 0);
8237 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
8238 MDB_val *key, MDB_val *data, unsigned flags)
8243 MDB_val rdata, *xdata;
8247 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
8249 mdb_cursor_init(&mc, txn, dbi, &mx);
8258 flags |= MDB_NODUPDATA;
8260 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
8262 /* let mdb_page_split know about this cursor if needed:
8263 * delete will trigger a rebalance; if it needs to move
8264 * a node from one page to another, it will have to
8265 * update the parent's separator key(s). If the new sepkey
8266 * is larger than the current one, the parent page may
8267 * run out of space, triggering a split. We need this
8268 * cursor to be consistent until the end of the rebalance.
8270 mc.mc_flags |= C_UNTRACK;
8271 mc.mc_next = txn->mt_cursors[dbi];
8272 txn->mt_cursors[dbi] = &mc;
8273 rc = mdb_cursor_del(&mc, flags);
8274 txn->mt_cursors[dbi] = mc.mc_next;
8279 /** Split a page and insert a new node.
8280 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
8281 * The cursor will be updated to point to the actual page and index where
8282 * the node got inserted after the split.
8283 * @param[in] newkey The key for the newly inserted node.
8284 * @param[in] newdata The data for the newly inserted node.
8285 * @param[in] newpgno The page number, if the new node is a branch node.
8286 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
8287 * @return 0 on success, non-zero on failure.
8290 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
8291 unsigned int nflags)
8294 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
8297 int i, j, split_indx, nkeys, pmax;
8298 MDB_env *env = mc->mc_txn->mt_env;
8300 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
8301 MDB_page *copy = NULL;
8302 MDB_page *mp, *rp, *pp;
8307 mp = mc->mc_pg[mc->mc_top];
8308 newindx = mc->mc_ki[mc->mc_top];
8309 nkeys = NUMKEYS(mp);
8311 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
8312 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
8313 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
8315 /* Create a right sibling. */
8316 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
8318 rp->mp_pad = mp->mp_pad;
8319 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
8321 if (mc->mc_snum < 2) {
8322 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
8324 /* shift current top to make room for new parent */
8325 mc->mc_pg[1] = mc->mc_pg[0];
8326 mc->mc_ki[1] = mc->mc_ki[0];
8329 mc->mc_db->md_root = pp->mp_pgno;
8330 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
8331 new_root = mc->mc_db->md_depth++;
8333 /* Add left (implicit) pointer. */
8334 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
8335 /* undo the pre-push */
8336 mc->mc_pg[0] = mc->mc_pg[1];
8337 mc->mc_ki[0] = mc->mc_ki[1];
8338 mc->mc_db->md_root = mp->mp_pgno;
8339 mc->mc_db->md_depth--;
8346 ptop = mc->mc_top-1;
8347 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
8350 mc->mc_flags |= C_SPLITTING;
8351 mdb_cursor_copy(mc, &mn);
8352 mn.mc_pg[mn.mc_top] = rp;
8353 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
8355 if (nflags & MDB_APPEND) {
8356 mn.mc_ki[mn.mc_top] = 0;
8358 split_indx = newindx;
8362 split_indx = (nkeys+1) / 2;
8367 unsigned int lsize, rsize, ksize;
8368 /* Move half of the keys to the right sibling */
8369 x = mc->mc_ki[mc->mc_top] - split_indx;
8370 ksize = mc->mc_db->md_pad;
8371 split = LEAF2KEY(mp, split_indx, ksize);
8372 rsize = (nkeys - split_indx) * ksize;
8373 lsize = (nkeys - split_indx) * sizeof(indx_t);
8374 mp->mp_lower -= lsize;
8375 rp->mp_lower += lsize;
8376 mp->mp_upper += rsize - lsize;
8377 rp->mp_upper -= rsize - lsize;
8378 sepkey.mv_size = ksize;
8379 if (newindx == split_indx) {
8380 sepkey.mv_data = newkey->mv_data;
8382 sepkey.mv_data = split;
8385 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
8386 memcpy(rp->mp_ptrs, split, rsize);
8387 sepkey.mv_data = rp->mp_ptrs;
8388 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
8389 memcpy(ins, newkey->mv_data, ksize);
8390 mp->mp_lower += sizeof(indx_t);
8391 mp->mp_upper -= ksize - sizeof(indx_t);
8394 memcpy(rp->mp_ptrs, split, x * ksize);
8395 ins = LEAF2KEY(rp, x, ksize);
8396 memcpy(ins, newkey->mv_data, ksize);
8397 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
8398 rp->mp_lower += sizeof(indx_t);
8399 rp->mp_upper -= ksize - sizeof(indx_t);
8400 mc->mc_ki[mc->mc_top] = x;
8401 mc->mc_pg[mc->mc_top] = rp;
8404 int psize, nsize, k;
8405 /* Maximum free space in an empty page */
8406 pmax = env->me_psize - PAGEHDRSZ;
8408 nsize = mdb_leaf_size(env, newkey, newdata);
8410 nsize = mdb_branch_size(env, newkey);
8411 nsize = EVEN(nsize);
8413 /* grab a page to hold a temporary copy */
8414 copy = mdb_page_malloc(mc->mc_txn, 1);
8419 copy->mp_pgno = mp->mp_pgno;
8420 copy->mp_flags = mp->mp_flags;
8421 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
8422 copy->mp_upper = env->me_psize - PAGEBASE;
8424 /* prepare to insert */
8425 for (i=0, j=0; i<nkeys; i++) {
8427 copy->mp_ptrs[j++] = 0;
8429 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
8432 /* When items are relatively large the split point needs
8433 * to be checked, because being off-by-one will make the
8434 * difference between success or failure in mdb_node_add.
8436 * It's also relevant if a page happens to be laid out
8437 * such that one half of its nodes are all "small" and
8438 * the other half of its nodes are "large." If the new
8439 * item is also "large" and falls on the half with
8440 * "large" nodes, it also may not fit.
8442 * As a final tweak, if the new item goes on the last
8443 * spot on the page (and thus, onto the new page), bias
8444 * the split so the new page is emptier than the old page.
8445 * This yields better packing during sequential inserts.
8447 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
8448 /* Find split point */
8450 if (newindx <= split_indx || newindx >= nkeys) {
8452 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
8457 for (; i!=k; i+=j) {
8462 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8463 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
8465 if (F_ISSET(node->mn_flags, F_BIGDATA))
8466 psize += sizeof(pgno_t);
8468 psize += NODEDSZ(node);
8470 psize = EVEN(psize);
8472 if (psize > pmax || i == k-j) {
8473 split_indx = i + (j<0);
8478 if (split_indx == newindx) {
8479 sepkey.mv_size = newkey->mv_size;
8480 sepkey.mv_data = newkey->mv_data;
8482 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
8483 sepkey.mv_size = node->mn_ksize;
8484 sepkey.mv_data = NODEKEY(node);
8489 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
8491 /* Copy separator key to the parent.
8493 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
8497 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
8502 if (mn.mc_snum == mc->mc_snum) {
8503 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
8504 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
8505 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
8506 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
8511 /* Right page might now have changed parent.
8512 * Check if left page also changed parent.
8514 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8515 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8516 for (i=0; i<ptop; i++) {
8517 mc->mc_pg[i] = mn.mc_pg[i];
8518 mc->mc_ki[i] = mn.mc_ki[i];
8520 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8521 if (mn.mc_ki[ptop]) {
8522 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8524 /* find right page's left sibling */
8525 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8526 mdb_cursor_sibling(mc, 0);
8531 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8534 mc->mc_flags ^= C_SPLITTING;
8535 if (rc != MDB_SUCCESS) {
8538 if (nflags & MDB_APPEND) {
8539 mc->mc_pg[mc->mc_top] = rp;
8540 mc->mc_ki[mc->mc_top] = 0;
8541 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8544 for (i=0; i<mc->mc_top; i++)
8545 mc->mc_ki[i] = mn.mc_ki[i];
8546 } else if (!IS_LEAF2(mp)) {
8548 mc->mc_pg[mc->mc_top] = rp;
8553 rkey.mv_data = newkey->mv_data;
8554 rkey.mv_size = newkey->mv_size;
8560 /* Update index for the new key. */
8561 mc->mc_ki[mc->mc_top] = j;
8563 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8564 rkey.mv_data = NODEKEY(node);
8565 rkey.mv_size = node->mn_ksize;
8567 xdata.mv_data = NODEDATA(node);
8568 xdata.mv_size = NODEDSZ(node);
8571 pgno = NODEPGNO(node);
8572 flags = node->mn_flags;
8575 if (!IS_LEAF(mp) && j == 0) {
8576 /* First branch index doesn't need key data. */
8580 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8586 mc->mc_pg[mc->mc_top] = copy;
8591 } while (i != split_indx);
8593 nkeys = NUMKEYS(copy);
8594 for (i=0; i<nkeys; i++)
8595 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8596 mp->mp_lower = copy->mp_lower;
8597 mp->mp_upper = copy->mp_upper;
8598 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8599 env->me_psize - copy->mp_upper - PAGEBASE);
8601 /* reset back to original page */
8602 if (newindx < split_indx) {
8603 mc->mc_pg[mc->mc_top] = mp;
8604 if (nflags & MDB_RESERVE) {
8605 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
8606 if (!(node->mn_flags & F_BIGDATA))
8607 newdata->mv_data = NODEDATA(node);
8610 mc->mc_pg[mc->mc_top] = rp;
8612 /* Make sure mc_ki is still valid.
8614 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8615 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8616 for (i=0; i<=ptop; i++) {
8617 mc->mc_pg[i] = mn.mc_pg[i];
8618 mc->mc_ki[i] = mn.mc_ki[i];
8625 /* Adjust other cursors pointing to mp */
8626 MDB_cursor *m2, *m3;
8627 MDB_dbi dbi = mc->mc_dbi;
8628 int fixup = NUMKEYS(mp);
8630 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8631 if (mc->mc_flags & C_SUB)
8632 m3 = &m2->mc_xcursor->mx_cursor;
8637 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8639 if (m3->mc_flags & C_SPLITTING)
8644 for (k=new_root; k>=0; k--) {
8645 m3->mc_ki[k+1] = m3->mc_ki[k];
8646 m3->mc_pg[k+1] = m3->mc_pg[k];
8648 if (m3->mc_ki[0] >= split_indx) {
8653 m3->mc_pg[0] = mc->mc_pg[0];
8657 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8658 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8659 m3->mc_ki[mc->mc_top]++;
8660 if (m3->mc_ki[mc->mc_top] >= fixup) {
8661 m3->mc_pg[mc->mc_top] = rp;
8662 m3->mc_ki[mc->mc_top] -= fixup;
8663 m3->mc_ki[ptop] = mn.mc_ki[ptop];
8665 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8666 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8671 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8674 if (copy) /* tmp page */
8675 mdb_page_free(env, copy);
8677 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8682 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8683 MDB_val *key, MDB_val *data, unsigned int flags)
8688 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8691 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
8694 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8695 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8697 mdb_cursor_init(&mc, txn, dbi, &mx);
8698 return mdb_cursor_put(&mc, key, data, flags);
8702 #define MDB_WBUF (1024*1024)
8705 /** State needed for a compacting copy. */
8706 typedef struct mdb_copy {
8707 pthread_mutex_t mc_mutex;
8708 pthread_cond_t mc_cond;
8715 pgno_t mc_next_pgno;
8718 volatile int mc_new;
8723 /** Dedicated writer thread for compacting copy. */
8724 static THREAD_RET ESECT CALL_CONV
8725 mdb_env_copythr(void *arg)
8729 int toggle = 0, wsize, rc;
8732 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8735 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8738 pthread_mutex_lock(&my->mc_mutex);
8740 pthread_cond_signal(&my->mc_cond);
8743 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8744 if (my->mc_new < 0) {
8749 wsize = my->mc_wlen[toggle];
8750 ptr = my->mc_wbuf[toggle];
8753 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8757 } else if (len > 0) {
8771 /* If there's an overflow page tail, write it too */
8772 if (my->mc_olen[toggle]) {
8773 wsize = my->mc_olen[toggle];
8774 ptr = my->mc_over[toggle];
8775 my->mc_olen[toggle] = 0;
8778 my->mc_wlen[toggle] = 0;
8780 pthread_cond_signal(&my->mc_cond);
8782 pthread_cond_signal(&my->mc_cond);
8783 pthread_mutex_unlock(&my->mc_mutex);
8784 return (THREAD_RET)0;
8788 /** Tell the writer thread there's a buffer ready to write */
8790 mdb_env_cthr_toggle(mdb_copy *my, int st)
8792 int toggle = my->mc_toggle ^ 1;
8793 pthread_mutex_lock(&my->mc_mutex);
8794 if (my->mc_status) {
8795 pthread_mutex_unlock(&my->mc_mutex);
8796 return my->mc_status;
8798 while (my->mc_new == 1)
8799 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8801 my->mc_toggle = toggle;
8802 pthread_cond_signal(&my->mc_cond);
8803 pthread_mutex_unlock(&my->mc_mutex);
8807 /** Depth-first tree traversal for compacting copy. */
8809 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8812 MDB_txn *txn = my->mc_txn;
8814 MDB_page *mo, *mp, *leaf;
8819 /* Empty DB, nothing to do */
8820 if (*pg == P_INVALID)
8827 rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
8830 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8834 /* Make cursor pages writable */
8835 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8839 for (i=0; i<mc.mc_top; i++) {
8840 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8841 mc.mc_pg[i] = (MDB_page *)ptr;
8842 ptr += my->mc_env->me_psize;
8845 /* This is writable space for a leaf page. Usually not needed. */
8846 leaf = (MDB_page *)ptr;
8848 toggle = my->mc_toggle;
8849 while (mc.mc_snum > 0) {
8851 mp = mc.mc_pg[mc.mc_top];
8855 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8856 for (i=0; i<n; i++) {
8857 ni = NODEPTR(mp, i);
8858 if (ni->mn_flags & F_BIGDATA) {
8862 /* Need writable leaf */
8864 mc.mc_pg[mc.mc_top] = leaf;
8865 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8867 ni = NODEPTR(mp, i);
8870 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8871 rc = mdb_page_get(txn, pg, &omp, NULL);
8874 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8875 rc = mdb_env_cthr_toggle(my, 1);
8878 toggle = my->mc_toggle;
8880 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8881 memcpy(mo, omp, my->mc_env->me_psize);
8882 mo->mp_pgno = my->mc_next_pgno;
8883 my->mc_next_pgno += omp->mp_pages;
8884 my->mc_wlen[toggle] += my->mc_env->me_psize;
8885 if (omp->mp_pages > 1) {
8886 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
8887 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
8888 rc = mdb_env_cthr_toggle(my, 1);
8891 toggle = my->mc_toggle;
8893 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
8894 } else if (ni->mn_flags & F_SUBDATA) {
8897 /* Need writable leaf */
8899 mc.mc_pg[mc.mc_top] = leaf;
8900 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8902 ni = NODEPTR(mp, i);
8905 memcpy(&db, NODEDATA(ni), sizeof(db));
8906 my->mc_toggle = toggle;
8907 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
8910 toggle = my->mc_toggle;
8911 memcpy(NODEDATA(ni), &db, sizeof(db));
8916 mc.mc_ki[mc.mc_top]++;
8917 if (mc.mc_ki[mc.mc_top] < n) {
8920 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
8922 rc = mdb_page_get(txn, pg, &mp, NULL);
8927 mc.mc_ki[mc.mc_top] = 0;
8928 if (IS_BRANCH(mp)) {
8929 /* Whenever we advance to a sibling branch page,
8930 * we must proceed all the way down to its first leaf.
8932 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
8935 mc.mc_pg[mc.mc_top] = mp;
8939 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8940 rc = mdb_env_cthr_toggle(my, 1);
8943 toggle = my->mc_toggle;
8945 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8946 mdb_page_copy(mo, mp, my->mc_env->me_psize);
8947 mo->mp_pgno = my->mc_next_pgno++;
8948 my->mc_wlen[toggle] += my->mc_env->me_psize;
8950 /* Update parent if there is one */
8951 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
8952 SETPGNO(ni, mo->mp_pgno);
8953 mdb_cursor_pop(&mc);
8955 /* Otherwise we're done */
8965 /** Copy environment with compaction. */
8967 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
8972 MDB_txn *txn = NULL;
8977 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
8978 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
8979 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
8980 if (my.mc_wbuf[0] == NULL)
8983 pthread_mutex_init(&my.mc_mutex, NULL);
8984 pthread_cond_init(&my.mc_cond, NULL);
8985 #ifdef HAVE_MEMALIGN
8986 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
8987 if (my.mc_wbuf[0] == NULL)
8990 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_os_psize, MDB_WBUF*2);
8995 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
8996 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
9001 my.mc_next_pgno = NUM_METAS;
9007 THREAD_CREATE(thr, mdb_env_copythr, &my);
9009 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9013 mp = (MDB_page *)my.mc_wbuf[0];
9014 memset(mp, 0, NUM_METAS * env->me_psize);
9016 mp->mp_flags = P_META;
9017 mm = (MDB_meta *)METADATA(mp);
9018 mdb_env_init_meta0(env, mm);
9019 mm->mm_address = env->me_metas[0]->mm_address;
9021 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
9023 mp->mp_flags = P_META;
9024 *(MDB_meta *)METADATA(mp) = *mm;
9025 mm = (MDB_meta *)METADATA(mp);
9027 /* Count the number of free pages, subtract from lastpg to find
9028 * number of active pages
9031 MDB_ID freecount = 0;
9034 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
9035 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
9036 freecount += *(MDB_ID *)data.mv_data;
9037 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
9038 txn->mt_dbs[FREE_DBI].md_leaf_pages +
9039 txn->mt_dbs[FREE_DBI].md_overflow_pages;
9041 /* Set metapage 1 */
9042 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
9043 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
9044 if (mm->mm_last_pg > NUM_METAS-1) {
9045 mm->mm_dbs[MAIN_DBI].md_root = mm->mm_last_pg;
9048 mm->mm_dbs[MAIN_DBI].md_root = P_INVALID;
9051 my.mc_wlen[0] = env->me_psize * NUM_METAS;
9053 pthread_mutex_lock(&my.mc_mutex);
9055 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
9056 pthread_mutex_unlock(&my.mc_mutex);
9057 rc = mdb_env_cwalk(&my, &txn->mt_dbs[MAIN_DBI].md_root, 0);
9058 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
9059 rc = mdb_env_cthr_toggle(&my, 1);
9060 mdb_env_cthr_toggle(&my, -1);
9061 pthread_mutex_lock(&my.mc_mutex);
9063 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
9064 pthread_mutex_unlock(&my.mc_mutex);
9069 CloseHandle(my.mc_cond);
9070 CloseHandle(my.mc_mutex);
9071 _aligned_free(my.mc_wbuf[0]);
9073 pthread_cond_destroy(&my.mc_cond);
9074 pthread_mutex_destroy(&my.mc_mutex);
9075 free(my.mc_wbuf[0]);
9080 /** Copy environment as-is. */
9082 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
9084 MDB_txn *txn = NULL;
9085 mdb_mutexref_t wmutex = NULL;
9091 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9095 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9098 /* Do the lock/unlock of the reader mutex before starting the
9099 * write txn. Otherwise other read txns could block writers.
9101 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9106 /* We must start the actual read txn after blocking writers */
9107 mdb_txn_end(txn, MDB_END_RESET_TMP);
9109 /* Temporarily block writers until we snapshot the meta pages */
9110 wmutex = env->me_wmutex;
9111 if (LOCK_MUTEX(rc, env, wmutex))
9114 rc = mdb_txn_renew0(txn);
9116 UNLOCK_MUTEX(wmutex);
9121 wsize = env->me_psize * NUM_METAS;
9125 DO_WRITE(rc, fd, ptr, w2, len);
9129 } else if (len > 0) {
9135 /* Non-blocking or async handles are not supported */
9141 UNLOCK_MUTEX(wmutex);
9146 w2 = txn->mt_next_pgno * env->me_psize;
9149 if ((rc = mdb_fsize(env->me_fd, &fsize)))
9156 if (wsize > MAX_WRITE)
9160 DO_WRITE(rc, fd, ptr, w2, len);
9164 } else if (len > 0) {
9181 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
9183 if (flags & MDB_CP_COMPACT)
9184 return mdb_env_copyfd1(env, fd);
9186 return mdb_env_copyfd0(env, fd);
9190 mdb_env_copyfd(MDB_env *env, HANDLE fd)
9192 return mdb_env_copyfd2(env, fd, 0);
9196 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
9200 HANDLE newfd = INVALID_HANDLE_VALUE;
9202 if (env->me_flags & MDB_NOSUBDIR) {
9203 lpath = (char *)path;
9206 len += sizeof(DATANAME);
9207 lpath = malloc(len);
9210 sprintf(lpath, "%s" DATANAME, path);
9213 /* The destination path must exist, but the destination file must not.
9214 * We don't want the OS to cache the writes, since the source data is
9215 * already in the OS cache.
9218 newfd = CreateFileA(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
9219 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
9221 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
9223 if (newfd == INVALID_HANDLE_VALUE) {
9228 if (env->me_psize >= env->me_os_psize) {
9230 /* Set O_DIRECT if the file system supports it */
9231 if ((rc = fcntl(newfd, F_GETFL)) != -1)
9232 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
9234 #ifdef F_NOCACHE /* __APPLE__ */
9235 rc = fcntl(newfd, F_NOCACHE, 1);
9243 rc = mdb_env_copyfd2(env, newfd, flags);
9246 if (!(env->me_flags & MDB_NOSUBDIR))
9248 if (newfd != INVALID_HANDLE_VALUE)
9249 if (close(newfd) < 0 && rc == MDB_SUCCESS)
9256 mdb_env_copy(MDB_env *env, const char *path)
9258 return mdb_env_copy2(env, path, 0);
9262 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
9264 if (flag & ~CHANGEABLE)
9267 env->me_flags |= flag;
9269 env->me_flags &= ~flag;
9274 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
9279 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
9284 mdb_env_set_userctx(MDB_env *env, void *ctx)
9288 env->me_userctx = ctx;
9293 mdb_env_get_userctx(MDB_env *env)
9295 return env ? env->me_userctx : NULL;
9299 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
9304 env->me_assert_func = func;
9310 mdb_env_get_path(MDB_env *env, const char **arg)
9315 *arg = env->me_path;
9320 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
9329 /** Common code for #mdb_stat() and #mdb_env_stat().
9330 * @param[in] env the environment to operate in.
9331 * @param[in] db the #MDB_db record containing the stats to return.
9332 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
9333 * @return 0, this function always succeeds.
9336 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
9338 arg->ms_psize = env->me_psize;
9339 arg->ms_depth = db->md_depth;
9340 arg->ms_branch_pages = db->md_branch_pages;
9341 arg->ms_leaf_pages = db->md_leaf_pages;
9342 arg->ms_overflow_pages = db->md_overflow_pages;
9343 arg->ms_entries = db->md_entries;
9349 mdb_env_stat(MDB_env *env, MDB_stat *arg)
9353 if (env == NULL || arg == NULL)
9356 meta = mdb_env_pick_meta(env);
9358 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
9362 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
9366 if (env == NULL || arg == NULL)
9369 meta = mdb_env_pick_meta(env);
9370 arg->me_mapaddr = meta->mm_address;
9371 arg->me_last_pgno = meta->mm_last_pg;
9372 arg->me_last_txnid = meta->mm_txnid;
9374 arg->me_mapsize = env->me_mapsize;
9375 arg->me_maxreaders = env->me_maxreaders;
9376 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
9380 /** Set the default comparison functions for a database.
9381 * Called immediately after a database is opened to set the defaults.
9382 * The user can then override them with #mdb_set_compare() or
9383 * #mdb_set_dupsort().
9384 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
9385 * @param[in] dbi A database handle returned by #mdb_dbi_open()
9388 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
9390 uint16_t f = txn->mt_dbs[dbi].md_flags;
9392 txn->mt_dbxs[dbi].md_cmp =
9393 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
9394 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
9396 txn->mt_dbxs[dbi].md_dcmp =
9397 !(f & MDB_DUPSORT) ? 0 :
9398 ((f & MDB_INTEGERDUP)
9399 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
9400 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
9403 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
9409 int rc, dbflag, exact;
9410 unsigned int unused = 0, seq;
9413 if (flags & ~VALID_FLAGS)
9415 if (txn->mt_flags & MDB_TXN_BLOCKED)
9421 if (flags & PERSISTENT_FLAGS) {
9422 uint16_t f2 = flags & PERSISTENT_FLAGS;
9423 /* make sure flag changes get committed */
9424 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
9425 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
9426 txn->mt_flags |= MDB_TXN_DIRTY;
9429 mdb_default_cmp(txn, MAIN_DBI);
9433 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
9434 mdb_default_cmp(txn, MAIN_DBI);
9437 /* Is the DB already open? */
9439 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
9440 if (!txn->mt_dbxs[i].md_name.mv_size) {
9441 /* Remember this free slot */
9442 if (!unused) unused = i;
9445 if (len == txn->mt_dbxs[i].md_name.mv_size &&
9446 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
9452 /* If no free slot and max hit, fail */
9453 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
9454 return MDB_DBS_FULL;
9456 /* Cannot mix named databases with some mainDB flags */
9457 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
9458 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
9460 /* Find the DB info */
9461 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
9464 key.mv_data = (void *)name;
9465 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
9466 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
9467 if (rc == MDB_SUCCESS) {
9468 /* make sure this is actually a DB */
9469 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
9470 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
9471 return MDB_INCOMPATIBLE;
9472 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
9473 /* Create if requested */
9474 data.mv_size = sizeof(MDB_db);
9475 data.mv_data = &dummy;
9476 memset(&dummy, 0, sizeof(dummy));
9477 dummy.md_root = P_INVALID;
9478 dummy.md_flags = flags & PERSISTENT_FLAGS;
9479 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
9483 /* OK, got info, add to table */
9484 if (rc == MDB_SUCCESS) {
9485 unsigned int slot = unused ? unused : txn->mt_numdbs;
9486 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
9487 txn->mt_dbxs[slot].md_name.mv_size = len;
9488 txn->mt_dbxs[slot].md_rel = NULL;
9489 txn->mt_dbflags[slot] = dbflag;
9490 /* txn-> and env-> are the same in read txns, use
9491 * tmp variable to avoid undefined assignment
9493 seq = ++txn->mt_env->me_dbiseqs[slot];
9494 txn->mt_dbiseqs[slot] = seq;
9496 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
9498 mdb_default_cmp(txn, slot);
9508 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9510 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
9513 if (txn->mt_flags & MDB_TXN_BLOCKED)
9516 if (txn->mt_dbflags[dbi] & DB_STALE) {
9519 /* Stale, must read the DB's root. cursor_init does it for us. */
9520 mdb_cursor_init(&mc, txn, dbi, &mx);
9522 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9525 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9528 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
9530 ptr = env->me_dbxs[dbi].md_name.mv_data;
9531 /* If there was no name, this was already closed */
9533 env->me_dbxs[dbi].md_name.mv_data = NULL;
9534 env->me_dbxs[dbi].md_name.mv_size = 0;
9535 env->me_dbflags[dbi] = 0;
9536 env->me_dbiseqs[dbi]++;
9541 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9543 /* We could return the flags for the FREE_DBI too but what's the point? */
9544 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9546 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9550 /** Add all the DB's pages to the free list.
9551 * @param[in] mc Cursor on the DB to free.
9552 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9553 * @return 0 on success, non-zero on failure.
9556 mdb_drop0(MDB_cursor *mc, int subs)
9560 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9561 if (rc == MDB_SUCCESS) {
9562 MDB_txn *txn = mc->mc_txn;
9567 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
9568 * This also avoids any P_LEAF2 pages, which have no nodes.
9570 if (mc->mc_flags & C_SUB)
9573 mdb_cursor_copy(mc, &mx);
9574 while (mc->mc_snum > 0) {
9575 MDB_page *mp = mc->mc_pg[mc->mc_top];
9576 unsigned n = NUMKEYS(mp);
9578 for (i=0; i<n; i++) {
9579 ni = NODEPTR(mp, i);
9580 if (ni->mn_flags & F_BIGDATA) {
9583 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9584 rc = mdb_page_get(txn, pg, &omp, NULL);
9587 mdb_cassert(mc, IS_OVERFLOW(omp));
9588 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9592 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9593 mdb_xcursor_init1(mc, ni);
9594 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9600 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9602 for (i=0; i<n; i++) {
9604 ni = NODEPTR(mp, i);
9607 mdb_midl_xappend(txn->mt_free_pgs, pg);
9612 mc->mc_ki[mc->mc_top] = i;
9613 rc = mdb_cursor_sibling(mc, 1);
9615 if (rc != MDB_NOTFOUND)
9617 /* no more siblings, go back to beginning
9618 * of previous level.
9622 for (i=1; i<mc->mc_snum; i++) {
9624 mc->mc_pg[i] = mx.mc_pg[i];
9629 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9632 txn->mt_flags |= MDB_TXN_ERROR;
9633 } else if (rc == MDB_NOTFOUND) {
9639 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9641 MDB_cursor *mc, *m2;
9644 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9647 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9650 if (TXN_DBI_CHANGED(txn, dbi))
9653 rc = mdb_cursor_open(txn, dbi, &mc);
9657 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9658 /* Invalidate the dropped DB's cursors */
9659 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9660 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9664 /* Can't delete the main DB */
9665 if (del && dbi >= CORE_DBS) {
9666 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
9668 txn->mt_dbflags[dbi] = DB_STALE;
9669 mdb_dbi_close(txn->mt_env, dbi);
9671 txn->mt_flags |= MDB_TXN_ERROR;
9674 /* reset the DB record, mark it dirty */
9675 txn->mt_dbflags[dbi] |= DB_DIRTY;
9676 txn->mt_dbs[dbi].md_depth = 0;
9677 txn->mt_dbs[dbi].md_branch_pages = 0;
9678 txn->mt_dbs[dbi].md_leaf_pages = 0;
9679 txn->mt_dbs[dbi].md_overflow_pages = 0;
9680 txn->mt_dbs[dbi].md_entries = 0;
9681 txn->mt_dbs[dbi].md_root = P_INVALID;
9683 txn->mt_flags |= MDB_TXN_DIRTY;
9686 mdb_cursor_close(mc);
9690 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9692 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9695 txn->mt_dbxs[dbi].md_cmp = cmp;
9699 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9701 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9704 txn->mt_dbxs[dbi].md_dcmp = cmp;
9708 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9710 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9713 txn->mt_dbxs[dbi].md_rel = rel;
9717 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9719 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9722 txn->mt_dbxs[dbi].md_relctx = ctx;
9727 mdb_env_get_maxkeysize(MDB_env *env)
9729 return ENV_MAXKEY(env);
9733 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9735 unsigned int i, rdrs;
9738 int rc = 0, first = 1;
9742 if (!env->me_txns) {
9743 return func("(no reader locks)\n", ctx);
9745 rdrs = env->me_txns->mti_numreaders;
9746 mr = env->me_txns->mti_readers;
9747 for (i=0; i<rdrs; i++) {
9749 txnid_t txnid = mr[i].mr_txnid;
9750 sprintf(buf, txnid == (txnid_t)-1 ?
9751 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9752 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9755 rc = func(" pid thread txnid\n", ctx);
9759 rc = func(buf, ctx);
9765 rc = func("(no active readers)\n", ctx);
9770 /** Insert pid into list if not already present.
9771 * return -1 if already present.
9774 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9776 /* binary search of pid in list */
9778 unsigned cursor = 1;
9780 unsigned n = ids[0];
9783 unsigned pivot = n >> 1;
9784 cursor = base + pivot + 1;
9785 val = pid - ids[cursor];
9790 } else if ( val > 0 ) {
9795 /* found, so it's a duplicate */
9804 for (n = ids[0]; n > cursor; n--)
9811 mdb_reader_check(MDB_env *env, int *dead)
9817 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
9820 /** As #mdb_reader_check(). rlocked = <caller locked the reader mutex>. */
9822 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
9824 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
9825 unsigned int i, j, rdrs;
9827 MDB_PID_T *pids, pid;
9828 int rc = MDB_SUCCESS, count = 0;
9830 rdrs = env->me_txns->mti_numreaders;
9831 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
9835 mr = env->me_txns->mti_readers;
9836 for (i=0; i<rdrs; i++) {
9838 if (pid && pid != env->me_pid) {
9839 if (mdb_pid_insert(pids, pid) == 0) {
9840 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9841 /* Stale reader found */
9844 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
9845 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
9847 rdrs = 0; /* the above checked all readers */
9849 /* Recheck, a new process may have reused pid */
9850 if (mdb_reader_pid(env, Pidcheck, pid))
9855 if (mr[j].mr_pid == pid) {
9856 DPRINTF(("clear stale reader pid %u txn %"Z"d",
9857 (unsigned) pid, mr[j].mr_txnid));
9862 UNLOCK_MUTEX(rmutex);
9873 #ifdef MDB_ROBUST_SUPPORTED
9874 /** Handle #LOCK_MUTEX0() failure.
9875 * Try to repair the lock file if the mutex owner died.
9876 * @param[in] env the environment handle
9877 * @param[in] mutex LOCK_MUTEX0() mutex
9878 * @param[in] rc LOCK_MUTEX0() error (nonzero)
9879 * @return 0 on success with the mutex locked, or an error code on failure.
9882 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
9887 if (rc == MDB_OWNERDEAD) {
9888 /* We own the mutex. Clean up after dead previous owner. */
9890 rlocked = (mutex == env->me_rmutex);
9892 /* Keep mti_txnid updated, otherwise next writer can
9893 * overwrite data which latest meta page refers to.
9895 meta = mdb_env_pick_meta(env);
9896 env->me_txns->mti_txnid = meta->mm_txnid;
9897 /* env is hosed if the dead thread was ours */
9899 env->me_flags |= MDB_FATAL_ERROR;
9904 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
9905 (rc ? "this process' env is hosed" : "recovering")));
9906 rc2 = mdb_reader_check0(env, rlocked, NULL);
9908 rc2 = mdb_mutex_consistent(mutex);
9909 if (rc || (rc = rc2)) {
9910 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
9911 UNLOCK_MUTEX(mutex);
9917 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
9922 #endif /* MDB_ROBUST_SUPPORTED */