2 * @brief Lightning memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2016 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
38 #if defined(__WIN64__)
39 #define _FILE_OFFSET_BITS 64
44 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
45 * as int64 which is wrong. MSVC doesn't define it at all, so just
49 #define MDB_THR_T DWORD
50 #include <sys/types.h>
53 # include <sys/param.h>
55 # define LITTLE_ENDIAN 1234
56 # define BIG_ENDIAN 4321
57 # define BYTE_ORDER LITTLE_ENDIAN
59 # define SSIZE_MAX INT_MAX
63 #include <sys/types.h>
65 #define MDB_PID_T pid_t
66 #define MDB_THR_T pthread_t
67 #include <sys/param.h>
70 #ifdef HAVE_SYS_FILE_H
76 #if defined(__mips) && defined(__linux)
77 /* MIPS has cache coherency issues, requires explicit cache control */
78 #include <asm/cachectl.h>
79 extern int cacheflush(char *addr, int nbytes, int cache);
80 #define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
82 #define CACHEFLUSH(addr, bytes, cache)
85 #if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
86 /** fdatasync is broken on ext3/ext4fs on older kernels, see
87 * description in #mdb_env_open2 comments. You can safely
88 * define MDB_FDATASYNC_WORKS if this code will only be run
89 * on kernels 3.6 and newer.
91 #define BROKEN_FDATASYNC
105 typedef SSIZE_T ssize_t;
110 #if defined(__sun) || defined(ANDROID)
111 /* Most platforms have posix_memalign, older may only have memalign */
112 #define HAVE_MEMALIGN 1
116 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
117 #include <netinet/in.h>
118 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
121 #if defined(__APPLE__) || defined (BSD)
122 # define MDB_USE_POSIX_SEM 1
123 # define MDB_FDATASYNC fsync
124 #elif defined(ANDROID)
125 # define MDB_FDATASYNC fsync
130 #ifdef MDB_USE_POSIX_SEM
131 # define MDB_USE_HASH 1
132 #include <semaphore.h>
134 #define MDB_USE_POSIX_MUTEX 1
138 #if defined(_WIN32) + defined(MDB_USE_POSIX_SEM) \
139 + defined(MDB_USE_POSIX_MUTEX) != 1
140 # error "Ambiguous shared-lock implementation"
144 #include <valgrind/memcheck.h>
145 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
146 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
147 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
148 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
149 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
151 #define VGMEMP_CREATE(h,r,z)
152 #define VGMEMP_ALLOC(h,a,s)
153 #define VGMEMP_FREE(h,a)
154 #define VGMEMP_DESTROY(h)
155 #define VGMEMP_DEFINED(a,s)
159 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
160 /* Solaris just defines one or the other */
161 # define LITTLE_ENDIAN 1234
162 # define BIG_ENDIAN 4321
163 # ifdef _LITTLE_ENDIAN
164 # define BYTE_ORDER LITTLE_ENDIAN
166 # define BYTE_ORDER BIG_ENDIAN
169 # define BYTE_ORDER __BYTE_ORDER
173 #ifndef LITTLE_ENDIAN
174 #define LITTLE_ENDIAN __LITTLE_ENDIAN
177 #define BIG_ENDIAN __BIG_ENDIAN
180 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
181 #define MISALIGNED_OK 1
187 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
188 # error "Unknown or unsupported endianness (BYTE_ORDER)"
189 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
190 # error "Two's complement, reasonably sized integer types, please"
194 /** Put infrequently used env functions in separate section */
196 # define ESECT __attribute__ ((section("__TEXT,text_env")))
198 # define ESECT __attribute__ ((section("text_env")))
205 #define CALL_CONV WINAPI
210 /** @defgroup internal LMDB Internals
213 /** @defgroup compat Compatibility Macros
214 * A bunch of macros to minimize the amount of platform-specific ifdefs
215 * needed throughout the rest of the code. When the features this library
216 * needs are similar enough to POSIX to be hidden in a one-or-two line
217 * replacement, this macro approach is used.
221 /** Features under development */
226 /** Wrapper around __func__, which is a C99 feature */
227 #if __STDC_VERSION__ >= 199901L
228 # define mdb_func_ __func__
229 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
230 # define mdb_func_ __FUNCTION__
232 /* If a debug message says <mdb_unknown>(), update the #if statements above */
233 # define mdb_func_ "<mdb_unknown>"
236 /* Internal error codes, not exposed outside liblmdb */
237 #define MDB_NO_ROOT (MDB_LAST_ERRCODE + 10)
239 #define MDB_OWNERDEAD ((int) WAIT_ABANDONED)
240 #elif defined(MDB_USE_POSIX_MUTEX) && defined(EOWNERDEAD)
241 #define MDB_OWNERDEAD EOWNERDEAD /**< #LOCK_MUTEX0() result if dead owner */
245 #define GLIBC_VER ((__GLIBC__ << 16 )| __GLIBC_MINOR__)
247 /** Some platforms define the EOWNERDEAD error code
248 * even though they don't support Robust Mutexes.
249 * Compile with -DMDB_USE_ROBUST=0, or use some other
250 * mechanism like -DMDB_USE_POSIX_SEM instead of
251 * -DMDB_USE_POSIX_MUTEX.
252 * (Posix semaphores are not robust.)
254 #ifndef MDB_USE_ROBUST
255 /* Android currently lacks Robust Mutex support. So does glibc < 2.4. */
256 # if defined(MDB_USE_POSIX_MUTEX) && (defined(ANDROID) || \
257 (defined(__GLIBC__) && GLIBC_VER < 0x020004))
258 # define MDB_USE_ROBUST 0
260 # define MDB_USE_ROBUST 1
261 /* glibc < 2.12 only provided _np API */
262 # if (defined(__GLIBC__) && GLIBC_VER < 0x02000c) || \
263 (defined(PTHREAD_MUTEX_ROBUST_NP) && !defined(PTHREAD_MUTEX_ROBUST))
264 # define PTHREAD_MUTEX_ROBUST PTHREAD_MUTEX_ROBUST_NP
265 # define pthread_mutexattr_setrobust(attr, flag) pthread_mutexattr_setrobust_np(attr, flag)
266 # define pthread_mutex_consistent(mutex) pthread_mutex_consistent_np(mutex)
269 #endif /* MDB_USE_ROBUST */
271 #if defined(MDB_OWNERDEAD) && MDB_USE_ROBUST
272 #define MDB_ROBUST_SUPPORTED 1
276 #define MDB_USE_HASH 1
277 #define MDB_PIDLOCK 0
278 #define THREAD_RET DWORD
279 #define pthread_t HANDLE
280 #define pthread_mutex_t HANDLE
281 #define pthread_cond_t HANDLE
282 typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
283 #define pthread_key_t DWORD
284 #define pthread_self() GetCurrentThreadId()
285 #define pthread_key_create(x,y) \
286 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
287 #define pthread_key_delete(x) TlsFree(x)
288 #define pthread_getspecific(x) TlsGetValue(x)
289 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
290 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
291 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
292 #define pthread_cond_signal(x) SetEvent(*x)
293 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
294 #define THREAD_CREATE(thr,start,arg) thr=CreateThread(NULL,0,start,arg,0,NULL)
295 #define THREAD_FINISH(thr) WaitForSingleObject(thr, INFINITE)
296 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
297 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
298 #define mdb_mutex_consistent(mutex) 0
299 #define getpid() GetCurrentProcessId()
300 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
301 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
302 #define ErrCode() GetLastError()
303 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
304 #define close(fd) (CloseHandle(fd) ? 0 : -1)
305 #define munmap(ptr,len) UnmapViewOfFile(ptr)
306 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
307 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
309 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
313 #define THREAD_RET void *
314 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
315 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
316 #define Z "z" /**< printf format modifier for size_t */
318 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
319 #define MDB_PIDLOCK 1
321 #ifdef MDB_USE_POSIX_SEM
323 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
324 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
325 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
328 mdb_sem_wait(sem_t *sem)
331 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
335 #else /* MDB_USE_POSIX_MUTEX: */
336 /** Shared mutex/semaphore as it is stored (mdb_mutex_t), and as
337 * local variables keep it (mdb_mutexref_t).
339 * When #mdb_mutexref_t is a pointer declaration and #mdb_mutex_t is
340 * not, then it is array[size 1] so it can be assigned to a pointer.
343 typedef pthread_mutex_t mdb_mutex_t[1], *mdb_mutexref_t;
345 /** Lock the reader or writer mutex.
346 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
348 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
349 /** Unlock the reader or writer mutex.
351 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
352 /** Mark mutex-protected data as repaired, after death of previous owner.
354 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
355 #endif /* MDB_USE_POSIX_SEM */
357 /** Get the error code for the last failed system function.
359 #define ErrCode() errno
361 /** An abstraction for a file handle.
362 * On POSIX systems file handles are small integers. On Windows
363 * they're opaque pointers.
367 /** A value for an invalid file handle.
368 * Mainly used to initialize file variables and signify that they are
371 #define INVALID_HANDLE_VALUE (-1)
373 /** Get the size of a memory page for the system.
374 * This is the basic size that the platform's memory manager uses, and is
375 * fundamental to the use of memory-mapped files.
377 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
380 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
383 #define MNAME_LEN (sizeof(pthread_mutex_t))
388 #ifdef MDB_ROBUST_SUPPORTED
389 /** Lock mutex, handle any error, set rc = result.
390 * Return 0 on success, nonzero (not rc) on error.
392 #define LOCK_MUTEX(rc, env, mutex) \
393 (((rc) = LOCK_MUTEX0(mutex)) && \
394 ((rc) = mdb_mutex_failed(env, mutex, rc)))
395 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
397 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
398 #define mdb_mutex_failed(env, mutex, rc) (rc)
402 /** A flag for opening a file and requesting synchronous data writes.
403 * This is only used when writing a meta page. It's not strictly needed;
404 * we could just do a normal write and then immediately perform a flush.
405 * But if this flag is available it saves us an extra system call.
407 * @note If O_DSYNC is undefined but exists in /usr/include,
408 * preferably set some compiler flag to get the definition.
412 # define MDB_DSYNC O_DSYNC
414 # define MDB_DSYNC O_SYNC
419 /** Function for flushing the data of a file. Define this to fsync
420 * if fdatasync() is not supported.
422 #ifndef MDB_FDATASYNC
423 # define MDB_FDATASYNC fdatasync
427 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
438 /** A page number in the database.
439 * Note that 64 bit page numbers are overkill, since pages themselves
440 * already represent 12-13 bits of addressable memory, and the OS will
441 * always limit applications to a maximum of 63 bits of address space.
443 * @note In the #MDB_node structure, we only store 48 bits of this value,
444 * which thus limits us to only 60 bits of addressable data.
446 typedef MDB_ID pgno_t;
448 /** A transaction ID.
449 * See struct MDB_txn.mt_txnid for details.
451 typedef MDB_ID txnid_t;
453 /** @defgroup debug Debug Macros
457 /** Enable debug output. Needs variable argument macros (a C99 feature).
458 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
459 * read from and written to the database (used for free space management).
465 static int mdb_debug;
466 static txnid_t mdb_debug_start;
468 /** Print a debug message with printf formatting.
469 * Requires double parenthesis around 2 or more args.
471 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
472 # define DPRINTF0(fmt, ...) \
473 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
475 # define DPRINTF(args) ((void) 0)
477 /** Print a debug string.
478 * The string is printed literally, with no format processing.
480 #define DPUTS(arg) DPRINTF(("%s", arg))
481 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
483 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
486 /** @brief The maximum size of a database page.
488 * It is 32k or 64k, since value-PAGEBASE must fit in
489 * #MDB_page.%mp_upper.
491 * LMDB will use database pages < OS pages if needed.
492 * That causes more I/O in write transactions: The OS must
493 * know (read) the whole page before writing a partial page.
495 * Note that we don't currently support Huge pages. On Linux,
496 * regular data files cannot use Huge pages, and in general
497 * Huge pages aren't actually pageable. We rely on the OS
498 * demand-pager to read our data and page it out when memory
499 * pressure from other processes is high. So until OSs have
500 * actual paging support for Huge pages, they're not viable.
502 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
504 /** The minimum number of keys required in a database page.
505 * Setting this to a larger value will place a smaller bound on the
506 * maximum size of a data item. Data items larger than this size will
507 * be pushed into overflow pages instead of being stored directly in
508 * the B-tree node. This value used to default to 4. With a page size
509 * of 4096 bytes that meant that any item larger than 1024 bytes would
510 * go into an overflow page. That also meant that on average 2-3KB of
511 * each overflow page was wasted space. The value cannot be lower than
512 * 2 because then there would no longer be a tree structure. With this
513 * value, items larger than 2KB will go into overflow pages, and on
514 * average only 1KB will be wasted.
516 #define MDB_MINKEYS 2
518 /** A stamp that identifies a file as an LMDB file.
519 * There's nothing special about this value other than that it is easily
520 * recognizable, and it will reflect any byte order mismatches.
522 #define MDB_MAGIC 0xBEEFC0DE
524 /** The version number for a database's datafile format. */
525 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
526 /** The version number for a database's lockfile format. */
527 #define MDB_LOCK_VERSION 1
529 /** @brief The max size of a key we can write, or 0 for computed max.
531 * This macro should normally be left alone or set to 0.
532 * Note that a database with big keys or dupsort data cannot be
533 * reliably modified by a liblmdb which uses a smaller max.
534 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
536 * Other values are allowed, for backwards compat. However:
537 * A value bigger than the computed max can break if you do not
538 * know what you are doing, and liblmdb <= 0.9.10 can break when
539 * modifying a DB with keys/dupsort data bigger than its max.
541 * Data items in an #MDB_DUPSORT database are also limited to
542 * this size, since they're actually keys of a sub-DB. Keys and
543 * #MDB_DUPSORT data items must fit on a node in a regular page.
545 #ifndef MDB_MAXKEYSIZE
546 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
549 /** The maximum size of a key we can write to the environment. */
551 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
553 #define ENV_MAXKEY(env) ((env)->me_maxkey)
556 /** @brief The maximum size of a data item.
558 * We only store a 32 bit value for node sizes.
560 #define MAXDATASIZE 0xffffffffUL
563 /** Key size which fits in a #DKBUF.
566 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
569 * This is used for printing a hex dump of a key's contents.
571 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
572 /** Display a key in hex.
574 * Invoke a function to display a key in hex.
576 #define DKEY(x) mdb_dkey(x, kbuf)
582 /** An invalid page number.
583 * Mainly used to denote an empty tree.
585 #define P_INVALID (~(pgno_t)0)
587 /** Test if the flags \b f are set in a flag word \b w. */
588 #define F_ISSET(w, f) (((w) & (f)) == (f))
590 /** Round \b n up to an even number. */
591 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
593 /** Used for offsets within a single page.
594 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
597 typedef uint16_t indx_t;
599 /** Default size of memory map.
600 * This is certainly too small for any actual applications. Apps should always set
601 * the size explicitly using #mdb_env_set_mapsize().
603 #define DEFAULT_MAPSIZE 1048576
605 /** @defgroup readers Reader Lock Table
606 * Readers don't acquire any locks for their data access. Instead, they
607 * simply record their transaction ID in the reader table. The reader
608 * mutex is needed just to find an empty slot in the reader table. The
609 * slot's address is saved in thread-specific data so that subsequent read
610 * transactions started by the same thread need no further locking to proceed.
612 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
614 * No reader table is used if the database is on a read-only filesystem, or
615 * if #MDB_NOLOCK is set.
617 * Since the database uses multi-version concurrency control, readers don't
618 * actually need any locking. This table is used to keep track of which
619 * readers are using data from which old transactions, so that we'll know
620 * when a particular old transaction is no longer in use. Old transactions
621 * that have discarded any data pages can then have those pages reclaimed
622 * for use by a later write transaction.
624 * The lock table is constructed such that reader slots are aligned with the
625 * processor's cache line size. Any slot is only ever used by one thread.
626 * This alignment guarantees that there will be no contention or cache
627 * thrashing as threads update their own slot info, and also eliminates
628 * any need for locking when accessing a slot.
630 * A writer thread will scan every slot in the table to determine the oldest
631 * outstanding reader transaction. Any freed pages older than this will be
632 * reclaimed by the writer. The writer doesn't use any locks when scanning
633 * this table. This means that there's no guarantee that the writer will
634 * see the most up-to-date reader info, but that's not required for correct
635 * operation - all we need is to know the upper bound on the oldest reader,
636 * we don't care at all about the newest reader. So the only consequence of
637 * reading stale information here is that old pages might hang around a
638 * while longer before being reclaimed. That's actually good anyway, because
639 * the longer we delay reclaiming old pages, the more likely it is that a
640 * string of contiguous pages can be found after coalescing old pages from
641 * many old transactions together.
644 /** Number of slots in the reader table.
645 * This value was chosen somewhat arbitrarily. 126 readers plus a
646 * couple mutexes fit exactly into 8KB on my development machine.
647 * Applications should set the table size using #mdb_env_set_maxreaders().
649 #define DEFAULT_READERS 126
651 /** The size of a CPU cache line in bytes. We want our lock structures
652 * aligned to this size to avoid false cache line sharing in the
654 * This value works for most CPUs. For Itanium this should be 128.
660 /** The information we store in a single slot of the reader table.
661 * In addition to a transaction ID, we also record the process and
662 * thread ID that owns a slot, so that we can detect stale information,
663 * e.g. threads or processes that went away without cleaning up.
664 * @note We currently don't check for stale records. We simply re-init
665 * the table when we know that we're the only process opening the
668 typedef struct MDB_rxbody {
669 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
670 * Multiple readers that start at the same time will probably have the
671 * same ID here. Again, it's not important to exclude them from
672 * anything; all we need to know is which version of the DB they
673 * started from so we can avoid overwriting any data used in that
674 * particular version.
676 volatile txnid_t mrb_txnid;
677 /** The process ID of the process owning this reader txn. */
678 volatile MDB_PID_T mrb_pid;
679 /** The thread ID of the thread owning this txn. */
680 volatile MDB_THR_T mrb_tid;
683 /** The actual reader record, with cacheline padding. */
684 typedef struct MDB_reader {
687 /** shorthand for mrb_txnid */
688 #define mr_txnid mru.mrx.mrb_txnid
689 #define mr_pid mru.mrx.mrb_pid
690 #define mr_tid mru.mrx.mrb_tid
691 /** cache line alignment */
692 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
696 /** The header for the reader table.
697 * The table resides in a memory-mapped file. (This is a different file
698 * than is used for the main database.)
700 * For POSIX the actual mutexes reside in the shared memory of this
701 * mapped file. On Windows, mutexes are named objects allocated by the
702 * kernel; we store the mutex names in this mapped file so that other
703 * processes can grab them. This same approach is also used on
704 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
705 * process-shared POSIX mutexes. For these cases where a named object
706 * is used, the object name is derived from a 64 bit FNV hash of the
707 * environment pathname. As such, naming collisions are extremely
708 * unlikely. If a collision occurs, the results are unpredictable.
710 typedef struct MDB_txbody {
711 /** Stamp identifying this as an LMDB file. It must be set
714 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
716 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
717 char mtb_rmname[MNAME_LEN];
719 /** Mutex protecting access to this table.
720 * This is the reader table lock used with LOCK_MUTEX().
722 mdb_mutex_t mtb_rmutex;
724 /** The ID of the last transaction committed to the database.
725 * This is recorded here only for convenience; the value can always
726 * be determined by reading the main database meta pages.
728 volatile txnid_t mtb_txnid;
729 /** The number of slots that have been used in the reader table.
730 * This always records the maximum count, it is not decremented
731 * when readers release their slots.
733 volatile unsigned mtb_numreaders;
736 /** The actual reader table definition. */
737 typedef struct MDB_txninfo {
740 #define mti_magic mt1.mtb.mtb_magic
741 #define mti_format mt1.mtb.mtb_format
742 #define mti_rmutex mt1.mtb.mtb_rmutex
743 #define mti_rmname mt1.mtb.mtb_rmname
744 #define mti_txnid mt1.mtb.mtb_txnid
745 #define mti_numreaders mt1.mtb.mtb_numreaders
746 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
749 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
750 char mt2_wmname[MNAME_LEN];
751 #define mti_wmname mt2.mt2_wmname
753 mdb_mutex_t mt2_wmutex;
754 #define mti_wmutex mt2.mt2_wmutex
756 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
758 MDB_reader mti_readers[1];
761 /** Lockfile format signature: version, features and field layout */
762 #define MDB_LOCK_FORMAT \
764 ((MDB_LOCK_VERSION) \
765 /* Flags which describe functionality */ \
766 + (((MDB_PIDLOCK) != 0) << 16)))
769 /** Common header for all page types.
770 * Overflow records occupy a number of contiguous pages with no
771 * headers on any page after the first.
773 typedef struct MDB_page {
774 #define mp_pgno mp_p.p_pgno
775 #define mp_next mp_p.p_next
777 pgno_t p_pgno; /**< page number */
778 struct MDB_page *p_next; /**< for in-memory list of freed pages */
781 /** @defgroup mdb_page Page Flags
783 * Flags for the page headers.
786 #define P_BRANCH 0x01 /**< branch page */
787 #define P_LEAF 0x02 /**< leaf page */
788 #define P_OVERFLOW 0x04 /**< overflow page */
789 #define P_META 0x08 /**< meta page */
790 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
791 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
792 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
793 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
794 #define P_KEEP 0x8000 /**< leave this page alone during spill */
796 uint16_t mp_flags; /**< @ref mdb_page */
797 #define mp_lower mp_pb.pb.pb_lower
798 #define mp_upper mp_pb.pb.pb_upper
799 #define mp_pages mp_pb.pb_pages
802 indx_t pb_lower; /**< lower bound of free space */
803 indx_t pb_upper; /**< upper bound of free space */
805 uint32_t pb_pages; /**< number of overflow pages */
807 indx_t mp_ptrs[1]; /**< dynamic size */
810 /** Size of the page header, excluding dynamic data at the end */
811 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
813 /** Address of first usable data byte in a page, after the header */
814 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
816 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
817 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
819 /** Number of nodes on a page */
820 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
822 /** The amount of space remaining in the page */
823 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
825 /** The percentage of space used in the page, in tenths of a percent. */
826 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
827 ((env)->me_psize - PAGEHDRSZ))
828 /** The minimum page fill factor, in tenths of a percent.
829 * Pages emptier than this are candidates for merging.
831 #define FILL_THRESHOLD 250
833 /** Test if a page is a leaf page */
834 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
835 /** Test if a page is a LEAF2 page */
836 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
837 /** Test if a page is a branch page */
838 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
839 /** Test if a page is an overflow page */
840 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
841 /** Test if a page is a sub page */
842 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
844 /** The number of overflow pages needed to store the given size. */
845 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
847 /** Link in #MDB_txn.%mt_loose_pgs list */
848 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
850 /** Header for a single key/data pair within a page.
851 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
852 * We guarantee 2-byte alignment for 'MDB_node's.
854 typedef struct MDB_node {
855 /** lo and hi are used for data size on leaf nodes and for
856 * child pgno on branch nodes. On 64 bit platforms, flags
857 * is also used for pgno. (Branch nodes have no flags).
858 * They are in host byte order in case that lets some
859 * accesses be optimized into a 32-bit word access.
861 #if BYTE_ORDER == LITTLE_ENDIAN
862 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
864 unsigned short mn_hi, mn_lo;
866 /** @defgroup mdb_node Node Flags
868 * Flags for node headers.
871 #define F_BIGDATA 0x01 /**< data put on overflow page */
872 #define F_SUBDATA 0x02 /**< data is a sub-database */
873 #define F_DUPDATA 0x04 /**< data has duplicates */
875 /** valid flags for #mdb_node_add() */
876 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
879 unsigned short mn_flags; /**< @ref mdb_node */
880 unsigned short mn_ksize; /**< key size */
881 char mn_data[1]; /**< key and data are appended here */
884 /** Size of the node header, excluding dynamic data at the end */
885 #define NODESIZE offsetof(MDB_node, mn_data)
887 /** Bit position of top word in page number, for shifting mn_flags */
888 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
890 /** Size of a node in a branch page with a given key.
891 * This is just the node header plus the key, there is no data.
893 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
895 /** Size of a node in a leaf page with a given key and data.
896 * This is node header plus key plus data size.
898 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
900 /** Address of node \b i in page \b p */
901 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
903 /** Address of the key for the node */
904 #define NODEKEY(node) (void *)((node)->mn_data)
906 /** Address of the data for a node */
907 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
909 /** Get the page number pointed to by a branch node */
910 #define NODEPGNO(node) \
911 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
912 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
913 /** Set the page number in a branch node */
914 #define SETPGNO(node,pgno) do { \
915 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
916 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
918 /** Get the size of the data in a leaf node */
919 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
920 /** Set the size of the data for a leaf node */
921 #define SETDSZ(node,size) do { \
922 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
923 /** The size of a key in a node */
924 #define NODEKSZ(node) ((node)->mn_ksize)
926 /** Copy a page number from src to dst */
928 #define COPY_PGNO(dst,src) dst = src
930 #if SIZE_MAX > 4294967295UL
931 #define COPY_PGNO(dst,src) do { \
932 unsigned short *s, *d; \
933 s = (unsigned short *)&(src); \
934 d = (unsigned short *)&(dst); \
941 #define COPY_PGNO(dst,src) do { \
942 unsigned short *s, *d; \
943 s = (unsigned short *)&(src); \
944 d = (unsigned short *)&(dst); \
950 /** The address of a key in a LEAF2 page.
951 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
952 * There are no node headers, keys are stored contiguously.
954 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
956 /** Set the \b node's key into \b keyptr, if requested. */
957 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
958 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
960 /** Set the \b node's key into \b key. */
961 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
963 /** Information about a single database in the environment. */
964 typedef struct MDB_db {
965 uint32_t md_pad; /**< also ksize for LEAF2 pages */
966 uint16_t md_flags; /**< @ref mdb_dbi_open */
967 uint16_t md_depth; /**< depth of this tree */
968 pgno_t md_branch_pages; /**< number of internal pages */
969 pgno_t md_leaf_pages; /**< number of leaf pages */
970 pgno_t md_overflow_pages; /**< number of overflow pages */
971 size_t md_entries; /**< number of data items */
972 pgno_t md_root; /**< the root page of this tree */
975 /** mdb_dbi_open flags */
976 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
977 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
978 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
979 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
981 /** Handle for the DB used to track free pages. */
983 /** Handle for the default DB. */
985 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
988 /** Number of meta pages - also hardcoded elsewhere */
991 /** Meta page content.
992 * A meta page is the start point for accessing a database snapshot.
993 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
995 typedef struct MDB_meta {
996 /** Stamp identifying this as an LMDB file. It must be set
999 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
1000 uint32_t mm_version;
1001 void *mm_address; /**< address for fixed mapping */
1002 size_t mm_mapsize; /**< size of mmap region */
1003 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
1004 /** The size of pages used in this DB */
1005 #define mm_psize mm_dbs[FREE_DBI].md_pad
1006 /** Any persistent environment flags. @ref mdb_env */
1007 #define mm_flags mm_dbs[FREE_DBI].md_flags
1008 pgno_t mm_last_pg; /**< last used page in file */
1009 volatile txnid_t mm_txnid; /**< txnid that committed this page */
1012 /** Buffer for a stack-allocated meta page.
1013 * The members define size and alignment, and silence type
1014 * aliasing warnings. They are not used directly; that could
1015 * mean incorrectly using several union members in parallel.
1017 typedef union MDB_metabuf {
1020 char mm_pad[PAGEHDRSZ];
1025 /** Auxiliary DB info.
1026 * The information here is mostly static/read-only. There is
1027 * only a single copy of this record in the environment.
1029 typedef struct MDB_dbx {
1030 MDB_val md_name; /**< name of the database */
1031 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1032 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1033 MDB_rel_func *md_rel; /**< user relocate function */
1034 void *md_relctx; /**< user-provided context for md_rel */
1037 /** A database transaction.
1038 * Every operation requires a transaction handle.
1041 MDB_txn *mt_parent; /**< parent of a nested txn */
1042 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1044 pgno_t mt_next_pgno; /**< next unallocated page */
1045 /** The ID of this transaction. IDs are integers incrementing from 1.
1046 * Only committed write transactions increment the ID. If a transaction
1047 * aborts, the ID may be re-used by the next writer.
1050 MDB_env *mt_env; /**< the DB environment */
1051 /** The list of pages that became unused during this transaction.
1053 MDB_IDL mt_free_pgs;
1054 /** The list of loose pages that became unused and may be reused
1055 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1057 MDB_page *mt_loose_pgs;
1058 /* #Number of loose pages (#mt_loose_pgs) */
1060 /** The sorted list of dirty pages we temporarily wrote to disk
1061 * because the dirty list was full. page numbers in here are
1062 * shifted left by 1, deleted slots have the LSB set.
1064 MDB_IDL mt_spill_pgs;
1066 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1067 MDB_ID2L dirty_list;
1068 /** For read txns: This thread/txn's reader table slot, or NULL. */
1071 /** Array of records for each DB known in the environment. */
1073 /** Array of MDB_db records for each known DB */
1075 /** Array of sequence numbers for each DB handle */
1076 unsigned int *mt_dbiseqs;
1077 /** @defgroup mt_dbflag Transaction DB Flags
1081 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
1082 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1083 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1084 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1085 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1087 /** In write txns, array of cursors for each DB */
1088 MDB_cursor **mt_cursors;
1089 /** Array of flags for each DB */
1090 unsigned char *mt_dbflags;
1091 /** Number of DB records in use, or 0 when the txn is finished.
1092 * This number only ever increments until the txn finishes; we
1093 * don't decrement it when individual DB handles are closed.
1097 /** @defgroup mdb_txn Transaction Flags
1101 /** #mdb_txn_begin() flags */
1102 #define MDB_TXN_BEGIN_FLAGS MDB_RDONLY
1103 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1104 /* internal txn flags */
1105 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1106 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1107 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1108 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1109 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1110 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1111 /** most operations on the txn are currently illegal */
1112 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1114 unsigned int mt_flags; /**< @ref mdb_txn */
1115 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1116 * Includes ancestor txns' dirty pages not hidden by other txns'
1117 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1118 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1120 unsigned int mt_dirty_room;
1123 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1124 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1125 * raise this on a 64 bit machine.
1127 #define CURSOR_STACK 32
1131 /** Cursors are used for all DB operations.
1132 * A cursor holds a path of (page pointer, key index) from the DB
1133 * root to a position in the DB, plus other state. #MDB_DUPSORT
1134 * cursors include an xcursor to the current data item. Write txns
1135 * track their cursors and keep them up to date when data moves.
1136 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1137 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1140 /** Next cursor on this DB in this txn */
1141 MDB_cursor *mc_next;
1142 /** Backup of the original cursor if this cursor is a shadow */
1143 MDB_cursor *mc_backup;
1144 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1145 struct MDB_xcursor *mc_xcursor;
1146 /** The transaction that owns this cursor */
1148 /** The database handle this cursor operates on */
1150 /** The database record for this cursor */
1152 /** The database auxiliary record for this cursor */
1154 /** The @ref mt_dbflag for this database */
1155 unsigned char *mc_dbflag;
1156 unsigned short mc_snum; /**< number of pushed pages */
1157 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1158 /** @defgroup mdb_cursor Cursor Flags
1160 * Cursor state flags.
1163 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1164 #define C_EOF 0x02 /**< No more data */
1165 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1166 #define C_DEL 0x08 /**< last op was a cursor_del */
1167 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1169 unsigned int mc_flags; /**< @ref mdb_cursor */
1170 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1171 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1174 /** Context for sorted-dup records.
1175 * We could have gone to a fully recursive design, with arbitrarily
1176 * deep nesting of sub-databases. But for now we only handle these
1177 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1179 typedef struct MDB_xcursor {
1180 /** A sub-cursor for traversing the Dup DB */
1181 MDB_cursor mx_cursor;
1182 /** The database record for this Dup DB */
1184 /** The auxiliary DB record for this Dup DB */
1186 /** The @ref mt_dbflag for this Dup DB */
1187 unsigned char mx_dbflag;
1190 /** State of FreeDB old pages, stored in the MDB_env */
1191 typedef struct MDB_pgstate {
1192 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1193 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1196 /** The database environment. */
1198 HANDLE me_fd; /**< The main data file */
1199 HANDLE me_lfd; /**< The lock file */
1200 HANDLE me_mfd; /**< just for writing the meta pages */
1201 /** Failed to update the meta page. Probably an I/O error. */
1202 #define MDB_FATAL_ERROR 0x80000000U
1203 /** Some fields are initialized. */
1204 #define MDB_ENV_ACTIVE 0x20000000U
1205 /** me_txkey is set */
1206 #define MDB_ENV_TXKEY 0x10000000U
1207 /** fdatasync is unreliable */
1208 #define MDB_FSYNCONLY 0x08000000U
1209 uint32_t me_flags; /**< @ref mdb_env */
1210 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1211 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1212 unsigned int me_maxreaders; /**< size of the reader table */
1213 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1214 volatile int me_close_readers;
1215 MDB_dbi me_numdbs; /**< number of DBs opened */
1216 MDB_dbi me_maxdbs; /**< size of the DB table */
1217 MDB_PID_T me_pid; /**< process ID of this env */
1218 char *me_path; /**< path to the DB files */
1219 char *me_map; /**< the memory map of the data file */
1220 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1221 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1222 void *me_pbuf; /**< scratch area for DUPSORT put() */
1223 MDB_txn *me_txn; /**< current write transaction */
1224 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1225 size_t me_mapsize; /**< size of the data memory map */
1226 off_t me_size; /**< current file size */
1227 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1228 MDB_dbx *me_dbxs; /**< array of static DB info */
1229 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1230 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1231 pthread_key_t me_txkey; /**< thread-key for readers */
1232 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1233 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1234 # define me_pglast me_pgstate.mf_pglast
1235 # define me_pghead me_pgstate.mf_pghead
1236 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1237 /** IDL of pages that became unused in a write txn */
1238 MDB_IDL me_free_pgs;
1239 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1240 MDB_ID2L me_dirty_list;
1241 /** Max number of freelist items that can fit in a single overflow page */
1243 /** Max size of a node on a page */
1244 unsigned int me_nodemax;
1245 #if !(MDB_MAXKEYSIZE)
1246 unsigned int me_maxkey; /**< max size of a key */
1248 int me_live_reader; /**< have liveness lock in reader table */
1250 int me_pidquery; /**< Used in OpenProcess */
1252 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1253 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1254 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1256 mdb_mutex_t me_rmutex;
1257 mdb_mutex_t me_wmutex;
1259 void *me_userctx; /**< User-settable context */
1260 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1263 /** Nested transaction */
1264 typedef struct MDB_ntxn {
1265 MDB_txn mnt_txn; /**< the transaction */
1266 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1269 /** max number of pages to commit in one writev() call */
1270 #define MDB_COMMIT_PAGES 64
1271 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1272 #undef MDB_COMMIT_PAGES
1273 #define MDB_COMMIT_PAGES IOV_MAX
1276 /** max bytes to write in one call */
1277 #define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
1279 /** Check \b txn and \b dbi arguments to a function */
1280 #define TXN_DBI_EXIST(txn, dbi, validity) \
1281 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1283 /** Check for misused \b dbi handles */
1284 #define TXN_DBI_CHANGED(txn, dbi) \
1285 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1287 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1288 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1289 static int mdb_page_touch(MDB_cursor *mc);
1291 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1292 "reset-tmp", "fail-begin", "fail-beginchild"}
1294 /* mdb_txn_end operation number, for logging */
1295 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1296 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1298 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1299 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1300 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1301 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1302 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1304 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1305 static int mdb_page_search_root(MDB_cursor *mc,
1306 MDB_val *key, int modify);
1307 #define MDB_PS_MODIFY 1
1308 #define MDB_PS_ROOTONLY 2
1309 #define MDB_PS_FIRST 4
1310 #define MDB_PS_LAST 8
1311 static int mdb_page_search(MDB_cursor *mc,
1312 MDB_val *key, int flags);
1313 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1315 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1316 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1317 pgno_t newpgno, unsigned int nflags);
1319 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1320 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1321 static int mdb_env_write_meta(MDB_txn *txn);
1322 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1323 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1325 static void mdb_env_close0(MDB_env *env, int excl);
1327 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1328 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1329 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1330 static void mdb_node_del(MDB_cursor *mc, int ksize);
1331 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1332 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1333 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1334 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1335 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1337 static int mdb_rebalance(MDB_cursor *mc);
1338 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1340 static void mdb_cursor_pop(MDB_cursor *mc);
1341 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1343 static int mdb_cursor_del0(MDB_cursor *mc);
1344 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1345 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1346 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1347 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1348 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1350 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1351 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1353 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1354 static void mdb_xcursor_init0(MDB_cursor *mc);
1355 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1356 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1358 static int mdb_drop0(MDB_cursor *mc, int subs);
1359 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1360 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1363 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1366 /** Compare two items pointing at size_t's of unknown alignment. */
1367 #ifdef MISALIGNED_OK
1368 # define mdb_cmp_clong mdb_cmp_long
1370 # define mdb_cmp_clong mdb_cmp_cint
1374 static SECURITY_DESCRIPTOR mdb_null_sd;
1375 static SECURITY_ATTRIBUTES mdb_all_sa;
1376 static int mdb_sec_inited;
1378 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize);
1381 /** Return the library version info. */
1383 mdb_version(int *major, int *minor, int *patch)
1385 if (major) *major = MDB_VERSION_MAJOR;
1386 if (minor) *minor = MDB_VERSION_MINOR;
1387 if (patch) *patch = MDB_VERSION_PATCH;
1388 return MDB_VERSION_STRING;
1391 /** Table of descriptions for LMDB @ref errors */
1392 static char *const mdb_errstr[] = {
1393 "MDB_KEYEXIST: Key/data pair already exists",
1394 "MDB_NOTFOUND: No matching key/data pair found",
1395 "MDB_PAGE_NOTFOUND: Requested page not found",
1396 "MDB_CORRUPTED: Located page was wrong type",
1397 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1398 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1399 "MDB_INVALID: File is not an LMDB file",
1400 "MDB_MAP_FULL: Environment mapsize limit reached",
1401 "MDB_DBS_FULL: Environment maxdbs limit reached",
1402 "MDB_READERS_FULL: Environment maxreaders limit reached",
1403 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1404 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1405 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1406 "MDB_PAGE_FULL: Internal error - page has no more space",
1407 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1408 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1409 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1410 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1411 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1412 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1416 mdb_strerror(int err)
1419 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1420 * This works as long as no function between the call to mdb_strerror
1421 * and the actual use of the message uses more than 4K of stack.
1423 #define MSGSIZE 1024
1424 #define PADSIZE 4096
1425 char buf[MSGSIZE+PADSIZE], *ptr = buf;
1429 return ("Successful return: 0");
1431 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1432 i = err - MDB_KEYEXIST;
1433 return mdb_errstr[i];
1437 /* These are the C-runtime error codes we use. The comment indicates
1438 * their numeric value, and the Win32 error they would correspond to
1439 * if the error actually came from a Win32 API. A major mess, we should
1440 * have used LMDB-specific error codes for everything.
1443 case ENOENT: /* 2, FILE_NOT_FOUND */
1444 case EIO: /* 5, ACCESS_DENIED */
1445 case ENOMEM: /* 12, INVALID_ACCESS */
1446 case EACCES: /* 13, INVALID_DATA */
1447 case EBUSY: /* 16, CURRENT_DIRECTORY */
1448 case EINVAL: /* 22, BAD_COMMAND */
1449 case ENOSPC: /* 28, OUT_OF_PAPER */
1450 return strerror(err);
1455 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1456 FORMAT_MESSAGE_IGNORE_INSERTS,
1457 NULL, err, 0, ptr, MSGSIZE, (va_list *)buf+MSGSIZE);
1460 return strerror(err);
1464 /** assert(3) variant in cursor context */
1465 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1466 /** assert(3) variant in transaction context */
1467 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1468 /** assert(3) variant in environment context */
1469 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1472 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1473 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1476 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1477 const char *func, const char *file, int line)
1480 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1481 file, line, expr_txt, func);
1482 if (env->me_assert_func)
1483 env->me_assert_func(env, buf);
1484 fprintf(stderr, "%s\n", buf);
1488 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1492 /** Return the page number of \b mp which may be sub-page, for debug output */
1494 mdb_dbg_pgno(MDB_page *mp)
1497 COPY_PGNO(ret, mp->mp_pgno);
1501 /** Display a key in hexadecimal and return the address of the result.
1502 * @param[in] key the key to display
1503 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1504 * @return The key in hexadecimal form.
1507 mdb_dkey(MDB_val *key, char *buf)
1510 unsigned char *c = key->mv_data;
1516 if (key->mv_size > DKBUF_MAXKEYSIZE)
1517 return "MDB_MAXKEYSIZE";
1518 /* may want to make this a dynamic check: if the key is mostly
1519 * printable characters, print it as-is instead of converting to hex.
1523 for (i=0; i<key->mv_size; i++)
1524 ptr += sprintf(ptr, "%02x", *c++);
1526 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1532 mdb_leafnode_type(MDB_node *n)
1534 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1535 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1536 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1539 /** Display all the keys in the page. */
1541 mdb_page_list(MDB_page *mp)
1543 pgno_t pgno = mdb_dbg_pgno(mp);
1544 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1546 unsigned int i, nkeys, nsize, total = 0;
1550 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1551 case P_BRANCH: type = "Branch page"; break;
1552 case P_LEAF: type = "Leaf page"; break;
1553 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1554 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1555 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1557 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1558 pgno, mp->mp_pages, state);
1561 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1562 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1565 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1569 nkeys = NUMKEYS(mp);
1570 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1572 for (i=0; i<nkeys; i++) {
1573 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1574 key.mv_size = nsize = mp->mp_pad;
1575 key.mv_data = LEAF2KEY(mp, i, nsize);
1577 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1580 node = NODEPTR(mp, i);
1581 key.mv_size = node->mn_ksize;
1582 key.mv_data = node->mn_data;
1583 nsize = NODESIZE + key.mv_size;
1584 if (IS_BRANCH(mp)) {
1585 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1589 if (F_ISSET(node->mn_flags, F_BIGDATA))
1590 nsize += sizeof(pgno_t);
1592 nsize += NODEDSZ(node);
1594 nsize += sizeof(indx_t);
1595 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1596 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1598 total = EVEN(total);
1600 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1601 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1605 mdb_cursor_chk(MDB_cursor *mc)
1611 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1612 for (i=0; i<mc->mc_top; i++) {
1614 node = NODEPTR(mp, mc->mc_ki[i]);
1615 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1618 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1620 if (mc->mc_xcursor && (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
1621 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1622 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1623 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1631 /** Count all the pages in each DB and in the freelist
1632 * and make sure it matches the actual number of pages
1634 * All named DBs must be open for a correct count.
1636 static void mdb_audit(MDB_txn *txn)
1640 MDB_ID freecount, count;
1645 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1646 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1647 freecount += *(MDB_ID *)data.mv_data;
1648 mdb_tassert(txn, rc == MDB_NOTFOUND);
1651 for (i = 0; i<txn->mt_numdbs; i++) {
1653 if (!(txn->mt_dbflags[i] & DB_VALID))
1655 mdb_cursor_init(&mc, txn, i, &mx);
1656 if (txn->mt_dbs[i].md_root == P_INVALID)
1658 count += txn->mt_dbs[i].md_branch_pages +
1659 txn->mt_dbs[i].md_leaf_pages +
1660 txn->mt_dbs[i].md_overflow_pages;
1661 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1662 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1663 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1666 mp = mc.mc_pg[mc.mc_top];
1667 for (j=0; j<NUMKEYS(mp); j++) {
1668 MDB_node *leaf = NODEPTR(mp, j);
1669 if (leaf->mn_flags & F_SUBDATA) {
1671 memcpy(&db, NODEDATA(leaf), sizeof(db));
1672 count += db.md_branch_pages + db.md_leaf_pages +
1673 db.md_overflow_pages;
1677 mdb_tassert(txn, rc == MDB_NOTFOUND);
1680 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1681 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1682 txn->mt_txnid, freecount, count+NUM_METAS,
1683 freecount+count+NUM_METAS, txn->mt_next_pgno);
1689 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1691 return txn->mt_dbxs[dbi].md_cmp(a, b);
1695 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1697 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1698 #if UINT_MAX < SIZE_MAX
1699 if (dcmp == mdb_cmp_int && a->mv_size == sizeof(size_t))
1700 dcmp = mdb_cmp_clong;
1705 /** Allocate memory for a page.
1706 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1709 mdb_page_malloc(MDB_txn *txn, unsigned num)
1711 MDB_env *env = txn->mt_env;
1712 MDB_page *ret = env->me_dpages;
1713 size_t psize = env->me_psize, sz = psize, off;
1714 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1715 * For a single page alloc, we init everything after the page header.
1716 * For multi-page, we init the final page; if the caller needed that
1717 * many pages they will be filling in at least up to the last page.
1721 VGMEMP_ALLOC(env, ret, sz);
1722 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1723 env->me_dpages = ret->mp_next;
1726 psize -= off = PAGEHDRSZ;
1731 if ((ret = malloc(sz)) != NULL) {
1732 VGMEMP_ALLOC(env, ret, sz);
1733 if (!(env->me_flags & MDB_NOMEMINIT)) {
1734 memset((char *)ret + off, 0, psize);
1738 txn->mt_flags |= MDB_TXN_ERROR;
1742 /** Free a single page.
1743 * Saves single pages to a list, for future reuse.
1744 * (This is not used for multi-page overflow pages.)
1747 mdb_page_free(MDB_env *env, MDB_page *mp)
1749 mp->mp_next = env->me_dpages;
1750 VGMEMP_FREE(env, mp);
1751 env->me_dpages = mp;
1754 /** Free a dirty page */
1756 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1758 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1759 mdb_page_free(env, dp);
1761 /* large pages just get freed directly */
1762 VGMEMP_FREE(env, dp);
1767 /** Return all dirty pages to dpage list */
1769 mdb_dlist_free(MDB_txn *txn)
1771 MDB_env *env = txn->mt_env;
1772 MDB_ID2L dl = txn->mt_u.dirty_list;
1773 unsigned i, n = dl[0].mid;
1775 for (i = 1; i <= n; i++) {
1776 mdb_dpage_free(env, dl[i].mptr);
1781 /** Loosen or free a single page.
1782 * Saves single pages to a list for future reuse
1783 * in this same txn. It has been pulled from the freeDB
1784 * and already resides on the dirty list, but has been
1785 * deleted. Use these pages first before pulling again
1788 * If the page wasn't dirtied in this txn, just add it
1789 * to this txn's free list.
1792 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1795 pgno_t pgno = mp->mp_pgno;
1796 MDB_txn *txn = mc->mc_txn;
1798 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1799 if (txn->mt_parent) {
1800 MDB_ID2 *dl = txn->mt_u.dirty_list;
1801 /* If txn has a parent, make sure the page is in our
1805 unsigned x = mdb_mid2l_search(dl, pgno);
1806 if (x <= dl[0].mid && dl[x].mid == pgno) {
1807 if (mp != dl[x].mptr) { /* bad cursor? */
1808 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1809 txn->mt_flags |= MDB_TXN_ERROR;
1810 return MDB_CORRUPTED;
1817 /* no parent txn, so it's just ours */
1822 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1824 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1825 txn->mt_loose_pgs = mp;
1826 txn->mt_loose_count++;
1827 mp->mp_flags |= P_LOOSE;
1829 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1837 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1838 * @param[in] mc A cursor handle for the current operation.
1839 * @param[in] pflags Flags of the pages to update:
1840 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1841 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1842 * @return 0 on success, non-zero on failure.
1845 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1847 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1848 MDB_txn *txn = mc->mc_txn;
1854 int rc = MDB_SUCCESS, level;
1856 /* Mark pages seen by cursors */
1857 if (mc->mc_flags & C_UNTRACK)
1858 mc = NULL; /* will find mc in mt_cursors */
1859 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1860 for (; mc; mc=mc->mc_next) {
1861 if (!(mc->mc_flags & C_INITIALIZED))
1863 for (m3 = mc;; m3 = &mx->mx_cursor) {
1865 for (j=0; j<m3->mc_snum; j++) {
1867 if ((mp->mp_flags & Mask) == pflags)
1868 mp->mp_flags ^= P_KEEP;
1870 mx = m3->mc_xcursor;
1871 /* Proceed to mx if it is at a sub-database */
1872 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1874 if (! (mp && (mp->mp_flags & P_LEAF)))
1876 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1877 if (!(leaf->mn_flags & F_SUBDATA))
1886 /* Mark dirty root pages */
1887 for (i=0; i<txn->mt_numdbs; i++) {
1888 if (txn->mt_dbflags[i] & DB_DIRTY) {
1889 pgno_t pgno = txn->mt_dbs[i].md_root;
1890 if (pgno == P_INVALID)
1892 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1894 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1895 dp->mp_flags ^= P_KEEP;
1903 static int mdb_page_flush(MDB_txn *txn, int keep);
1905 /** Spill pages from the dirty list back to disk.
1906 * This is intended to prevent running into #MDB_TXN_FULL situations,
1907 * but note that they may still occur in a few cases:
1908 * 1) our estimate of the txn size could be too small. Currently this
1909 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1910 * 2) child txns may run out of space if their parents dirtied a
1911 * lot of pages and never spilled them. TODO: we probably should do
1912 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1913 * the parent's dirty_room is below a given threshold.
1915 * Otherwise, if not using nested txns, it is expected that apps will
1916 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1917 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1918 * If the txn never references them again, they can be left alone.
1919 * If the txn only reads them, they can be used without any fuss.
1920 * If the txn writes them again, they can be dirtied immediately without
1921 * going thru all of the work of #mdb_page_touch(). Such references are
1922 * handled by #mdb_page_unspill().
1924 * Also note, we never spill DB root pages, nor pages of active cursors,
1925 * because we'll need these back again soon anyway. And in nested txns,
1926 * we can't spill a page in a child txn if it was already spilled in a
1927 * parent txn. That would alter the parent txns' data even though
1928 * the child hasn't committed yet, and we'd have no way to undo it if
1929 * the child aborted.
1931 * @param[in] m0 cursor A cursor handle identifying the transaction and
1932 * database for which we are checking space.
1933 * @param[in] key For a put operation, the key being stored.
1934 * @param[in] data For a put operation, the data being stored.
1935 * @return 0 on success, non-zero on failure.
1938 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1940 MDB_txn *txn = m0->mc_txn;
1942 MDB_ID2L dl = txn->mt_u.dirty_list;
1943 unsigned int i, j, need;
1946 if (m0->mc_flags & C_SUB)
1949 /* Estimate how much space this op will take */
1950 i = m0->mc_db->md_depth;
1951 /* Named DBs also dirty the main DB */
1952 if (m0->mc_dbi >= CORE_DBS)
1953 i += txn->mt_dbs[MAIN_DBI].md_depth;
1954 /* For puts, roughly factor in the key+data size */
1956 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1957 i += i; /* double it for good measure */
1960 if (txn->mt_dirty_room > i)
1963 if (!txn->mt_spill_pgs) {
1964 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1965 if (!txn->mt_spill_pgs)
1968 /* purge deleted slots */
1969 MDB_IDL sl = txn->mt_spill_pgs;
1970 unsigned int num = sl[0];
1972 for (i=1; i<=num; i++) {
1979 /* Preserve pages which may soon be dirtied again */
1980 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1983 /* Less aggressive spill - we originally spilled the entire dirty list,
1984 * with a few exceptions for cursor pages and DB root pages. But this
1985 * turns out to be a lot of wasted effort because in a large txn many
1986 * of those pages will need to be used again. So now we spill only 1/8th
1987 * of the dirty pages. Testing revealed this to be a good tradeoff,
1988 * better than 1/2, 1/4, or 1/10.
1990 if (need < MDB_IDL_UM_MAX / 8)
1991 need = MDB_IDL_UM_MAX / 8;
1993 /* Save the page IDs of all the pages we're flushing */
1994 /* flush from the tail forward, this saves a lot of shifting later on. */
1995 for (i=dl[0].mid; i && need; i--) {
1996 MDB_ID pn = dl[i].mid << 1;
1998 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2000 /* Can't spill twice, make sure it's not already in a parent's
2003 if (txn->mt_parent) {
2005 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2006 if (tx2->mt_spill_pgs) {
2007 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2008 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2009 dp->mp_flags |= P_KEEP;
2017 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2021 mdb_midl_sort(txn->mt_spill_pgs);
2023 /* Flush the spilled part of dirty list */
2024 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2027 /* Reset any dirty pages we kept that page_flush didn't see */
2028 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2031 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2035 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2037 mdb_find_oldest(MDB_txn *txn)
2040 txnid_t mr, oldest = txn->mt_txnid - 1;
2041 if (txn->mt_env->me_txns) {
2042 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2043 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2054 /** Add a page to the txn's dirty list */
2056 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2059 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2061 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2062 insert = mdb_mid2l_append;
2064 insert = mdb_mid2l_insert;
2066 mid.mid = mp->mp_pgno;
2068 rc = insert(txn->mt_u.dirty_list, &mid);
2069 mdb_tassert(txn, rc == 0);
2070 txn->mt_dirty_room--;
2073 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2074 * me_pghead and mt_next_pgno.
2076 * If there are free pages available from older transactions, they
2077 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2078 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2079 * and move me_pglast to say which records were consumed. Only this
2080 * function can create me_pghead and move me_pglast/mt_next_pgno.
2081 * @param[in] mc cursor A cursor handle identifying the transaction and
2082 * database for which we are allocating.
2083 * @param[in] num the number of pages to allocate.
2084 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2085 * will always be satisfied by a single contiguous chunk of memory.
2086 * @return 0 on success, non-zero on failure.
2089 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2091 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2092 /* Get at most <Max_retries> more freeDB records once me_pghead
2093 * has enough pages. If not enough, use new pages from the map.
2094 * If <Paranoid> and mc is updating the freeDB, only get new
2095 * records if me_pghead is empty. Then the freelist cannot play
2096 * catch-up with itself by growing while trying to save it.
2098 enum { Paranoid = 1, Max_retries = 500 };
2100 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2102 int rc, retry = num * 60;
2103 MDB_txn *txn = mc->mc_txn;
2104 MDB_env *env = txn->mt_env;
2105 pgno_t pgno, *mop = env->me_pghead;
2106 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2108 txnid_t oldest = 0, last;
2113 /* If there are any loose pages, just use them */
2114 if (num == 1 && txn->mt_loose_pgs) {
2115 np = txn->mt_loose_pgs;
2116 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2117 txn->mt_loose_count--;
2118 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
2126 /* If our dirty list is already full, we can't do anything */
2127 if (txn->mt_dirty_room == 0) {
2132 for (op = MDB_FIRST;; op = MDB_NEXT) {
2137 /* Seek a big enough contiguous page range. Prefer
2138 * pages at the tail, just truncating the list.
2144 if (mop[i-n2] == pgno+n2)
2151 if (op == MDB_FIRST) { /* 1st iteration */
2152 /* Prepare to fetch more and coalesce */
2153 last = env->me_pglast;
2154 oldest = env->me_pgoldest;
2155 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2158 key.mv_data = &last; /* will look up last+1 */
2159 key.mv_size = sizeof(last);
2161 if (Paranoid && mc->mc_dbi == FREE_DBI)
2164 if (Paranoid && retry < 0 && mop_len)
2168 /* Do not fetch more if the record will be too recent */
2169 if (oldest <= last) {
2171 oldest = mdb_find_oldest(txn);
2172 env->me_pgoldest = oldest;
2178 rc = mdb_cursor_get(&m2, &key, NULL, op);
2180 if (rc == MDB_NOTFOUND)
2184 last = *(txnid_t*)key.mv_data;
2185 if (oldest <= last) {
2187 oldest = mdb_find_oldest(txn);
2188 env->me_pgoldest = oldest;
2194 np = m2.mc_pg[m2.mc_top];
2195 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2196 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
2199 idl = (MDB_ID *) data.mv_data;
2202 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2207 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2209 mop = env->me_pghead;
2211 env->me_pglast = last;
2213 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2214 last, txn->mt_dbs[FREE_DBI].md_root, i));
2216 DPRINTF(("IDL %"Z"u", idl[j]));
2218 /* Merge in descending sorted order */
2219 mdb_midl_xmerge(mop, idl);
2223 /* Use new pages from the map when nothing suitable in the freeDB */
2225 pgno = txn->mt_next_pgno;
2226 if (pgno + num >= env->me_maxpg) {
2227 DPUTS("DB size maxed out");
2233 if (env->me_flags & MDB_WRITEMAP) {
2234 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2236 if (!(np = mdb_page_malloc(txn, num))) {
2242 mop[0] = mop_len -= num;
2243 /* Move any stragglers down */
2244 for (j = i-num; j < mop_len; )
2245 mop[++j] = mop[++i];
2247 txn->mt_next_pgno = pgno + num;
2250 mdb_page_dirty(txn, np);
2256 txn->mt_flags |= MDB_TXN_ERROR;
2260 /** Copy the used portions of a non-overflow page.
2261 * @param[in] dst page to copy into
2262 * @param[in] src page to copy from
2263 * @param[in] psize size of a page
2266 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2268 enum { Align = sizeof(pgno_t) };
2269 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2271 /* If page isn't full, just copy the used portion. Adjust
2272 * alignment so memcpy may copy words instead of bytes.
2274 if ((unused &= -Align) && !IS_LEAF2(src)) {
2275 upper = (upper + PAGEBASE) & -Align;
2276 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2277 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2280 memcpy(dst, src, psize - unused);
2284 /** Pull a page off the txn's spill list, if present.
2285 * If a page being referenced was spilled to disk in this txn, bring
2286 * it back and make it dirty/writable again.
2287 * @param[in] txn the transaction handle.
2288 * @param[in] mp the page being referenced. It must not be dirty.
2289 * @param[out] ret the writable page, if any. ret is unchanged if
2290 * mp wasn't spilled.
2293 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2295 MDB_env *env = txn->mt_env;
2298 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2300 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2301 if (!tx2->mt_spill_pgs)
2303 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2304 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2307 if (txn->mt_dirty_room == 0)
2308 return MDB_TXN_FULL;
2309 if (IS_OVERFLOW(mp))
2313 if (env->me_flags & MDB_WRITEMAP) {
2316 np = mdb_page_malloc(txn, num);
2320 memcpy(np, mp, num * env->me_psize);
2322 mdb_page_copy(np, mp, env->me_psize);
2325 /* If in current txn, this page is no longer spilled.
2326 * If it happens to be the last page, truncate the spill list.
2327 * Otherwise mark it as deleted by setting the LSB.
2329 if (x == txn->mt_spill_pgs[0])
2330 txn->mt_spill_pgs[0]--;
2332 txn->mt_spill_pgs[x] |= 1;
2333 } /* otherwise, if belonging to a parent txn, the
2334 * page remains spilled until child commits
2337 mdb_page_dirty(txn, np);
2338 np->mp_flags |= P_DIRTY;
2346 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2347 * @param[in] mc cursor pointing to the page to be touched
2348 * @return 0 on success, non-zero on failure.
2351 mdb_page_touch(MDB_cursor *mc)
2353 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2354 MDB_txn *txn = mc->mc_txn;
2355 MDB_cursor *m2, *m3;
2359 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2360 if (txn->mt_flags & MDB_TXN_SPILLS) {
2362 rc = mdb_page_unspill(txn, mp, &np);
2368 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2369 (rc = mdb_page_alloc(mc, 1, &np)))
2372 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2373 mp->mp_pgno, pgno));
2374 mdb_cassert(mc, mp->mp_pgno != pgno);
2375 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2376 /* Update the parent page, if any, to point to the new page */
2378 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2379 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2380 SETPGNO(node, pgno);
2382 mc->mc_db->md_root = pgno;
2384 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2385 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2387 /* If txn has a parent, make sure the page is in our
2391 unsigned x = mdb_mid2l_search(dl, pgno);
2392 if (x <= dl[0].mid && dl[x].mid == pgno) {
2393 if (mp != dl[x].mptr) { /* bad cursor? */
2394 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2395 txn->mt_flags |= MDB_TXN_ERROR;
2396 return MDB_CORRUPTED;
2401 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2403 np = mdb_page_malloc(txn, 1);
2408 rc = mdb_mid2l_insert(dl, &mid);
2409 mdb_cassert(mc, rc == 0);
2414 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2416 np->mp_flags |= P_DIRTY;
2419 /* Adjust cursors pointing to mp */
2420 mc->mc_pg[mc->mc_top] = np;
2421 m2 = txn->mt_cursors[mc->mc_dbi];
2422 if (mc->mc_flags & C_SUB) {
2423 for (; m2; m2=m2->mc_next) {
2424 m3 = &m2->mc_xcursor->mx_cursor;
2425 if (m3->mc_snum < mc->mc_snum) continue;
2426 if (m3->mc_pg[mc->mc_top] == mp)
2427 m3->mc_pg[mc->mc_top] = np;
2430 for (; m2; m2=m2->mc_next) {
2431 if (m2->mc_snum < mc->mc_snum) continue;
2432 if (m2 == mc) continue;
2433 if (m2->mc_pg[mc->mc_top] == mp) {
2434 m2->mc_pg[mc->mc_top] = np;
2435 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2437 (m2->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
2439 MDB_node *leaf = NODEPTR(np, m2->mc_ki[mc->mc_top]);
2440 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
2441 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2449 txn->mt_flags |= MDB_TXN_ERROR;
2454 mdb_env_sync(MDB_env *env, int force)
2457 if (env->me_flags & MDB_RDONLY)
2459 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2460 if (env->me_flags & MDB_WRITEMAP) {
2461 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2462 ? MS_ASYNC : MS_SYNC;
2463 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2466 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2470 #ifdef BROKEN_FDATASYNC
2471 if (env->me_flags & MDB_FSYNCONLY) {
2472 if (fsync(env->me_fd))
2476 if (MDB_FDATASYNC(env->me_fd))
2483 /** Back up parent txn's cursors, then grab the originals for tracking */
2485 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2487 MDB_cursor *mc, *bk;
2492 for (i = src->mt_numdbs; --i >= 0; ) {
2493 if ((mc = src->mt_cursors[i]) != NULL) {
2494 size = sizeof(MDB_cursor);
2496 size += sizeof(MDB_xcursor);
2497 for (; mc; mc = bk->mc_next) {
2503 mc->mc_db = &dst->mt_dbs[i];
2504 /* Kill pointers into src to reduce abuse: The
2505 * user may not use mc until dst ends. But we need a valid
2506 * txn pointer here for cursor fixups to keep working.
2509 mc->mc_dbflag = &dst->mt_dbflags[i];
2510 if ((mx = mc->mc_xcursor) != NULL) {
2511 *(MDB_xcursor *)(bk+1) = *mx;
2512 mx->mx_cursor.mc_txn = dst;
2514 mc->mc_next = dst->mt_cursors[i];
2515 dst->mt_cursors[i] = mc;
2522 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2523 * @param[in] txn the transaction handle.
2524 * @param[in] merge true to keep changes to parent cursors, false to revert.
2525 * @return 0 on success, non-zero on failure.
2528 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2530 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2534 for (i = txn->mt_numdbs; --i >= 0; ) {
2535 for (mc = cursors[i]; mc; mc = next) {
2537 if ((bk = mc->mc_backup) != NULL) {
2539 /* Commit changes to parent txn */
2540 mc->mc_next = bk->mc_next;
2541 mc->mc_backup = bk->mc_backup;
2542 mc->mc_txn = bk->mc_txn;
2543 mc->mc_db = bk->mc_db;
2544 mc->mc_dbflag = bk->mc_dbflag;
2545 if ((mx = mc->mc_xcursor) != NULL)
2546 mx->mx_cursor.mc_txn = bk->mc_txn;
2548 /* Abort nested txn */
2550 if ((mx = mc->mc_xcursor) != NULL)
2551 *mx = *(MDB_xcursor *)(bk+1);
2555 /* Only malloced cursors are permanently tracked. */
2562 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2568 Pidset = F_SETLK, Pidcheck = F_GETLK
2572 /** Set or check a pid lock. Set returns 0 on success.
2573 * Check returns 0 if the process is certainly dead, nonzero if it may
2574 * be alive (the lock exists or an error happened so we do not know).
2576 * On Windows Pidset is a no-op, we merely check for the existence
2577 * of the process with the given pid. On POSIX we use a single byte
2578 * lock on the lockfile, set at an offset equal to the pid.
2581 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2583 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2586 if (op == Pidcheck) {
2587 h = OpenProcess(env->me_pidquery, FALSE, pid);
2588 /* No documented "no such process" code, but other program use this: */
2590 return ErrCode() != ERROR_INVALID_PARAMETER;
2591 /* A process exists until all handles to it close. Has it exited? */
2592 ret = WaitForSingleObject(h, 0) != 0;
2599 struct flock lock_info;
2600 memset(&lock_info, 0, sizeof(lock_info));
2601 lock_info.l_type = F_WRLCK;
2602 lock_info.l_whence = SEEK_SET;
2603 lock_info.l_start = pid;
2604 lock_info.l_len = 1;
2605 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2606 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2608 } else if ((rc = ErrCode()) == EINTR) {
2616 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2617 * @param[in] txn the transaction handle to initialize
2618 * @return 0 on success, non-zero on failure.
2621 mdb_txn_renew0(MDB_txn *txn)
2623 MDB_env *env = txn->mt_env;
2624 MDB_txninfo *ti = env->me_txns;
2626 unsigned int i, nr, flags = txn->mt_flags;
2628 int rc, new_notls = 0;
2630 if ((flags &= MDB_TXN_RDONLY) != 0) {
2632 meta = mdb_env_pick_meta(env);
2633 txn->mt_txnid = meta->mm_txnid;
2634 txn->mt_u.reader = NULL;
2636 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2637 pthread_getspecific(env->me_txkey);
2639 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2640 return MDB_BAD_RSLOT;
2642 MDB_PID_T pid = env->me_pid;
2643 MDB_THR_T tid = pthread_self();
2644 mdb_mutexref_t rmutex = env->me_rmutex;
2646 if (!env->me_live_reader) {
2647 rc = mdb_reader_pid(env, Pidset, pid);
2650 env->me_live_reader = 1;
2653 if (LOCK_MUTEX(rc, env, rmutex))
2655 nr = ti->mti_numreaders;
2656 for (i=0; i<nr; i++)
2657 if (ti->mti_readers[i].mr_pid == 0)
2659 if (i == env->me_maxreaders) {
2660 UNLOCK_MUTEX(rmutex);
2661 return MDB_READERS_FULL;
2663 r = &ti->mti_readers[i];
2664 /* Claim the reader slot, carefully since other code
2665 * uses the reader table un-mutexed: First reset the
2666 * slot, next publish it in mti_numreaders. After
2667 * that, it is safe for mdb_env_close() to touch it.
2668 * When it will be closed, we can finally claim it.
2671 r->mr_txnid = (txnid_t)-1;
2674 ti->mti_numreaders = ++nr;
2675 env->me_close_readers = nr;
2677 UNLOCK_MUTEX(rmutex);
2679 new_notls = (env->me_flags & MDB_NOTLS);
2680 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2685 do /* LY: Retry on a race, ITS#7970. */
2686 r->mr_txnid = ti->mti_txnid;
2687 while(r->mr_txnid != ti->mti_txnid);
2688 txn->mt_txnid = r->mr_txnid;
2689 txn->mt_u.reader = r;
2690 meta = env->me_metas[txn->mt_txnid & 1];
2694 /* Not yet touching txn == env->me_txn0, it may be active */
2696 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2698 txn->mt_txnid = ti->mti_txnid;
2699 meta = env->me_metas[txn->mt_txnid & 1];
2701 meta = mdb_env_pick_meta(env);
2702 txn->mt_txnid = meta->mm_txnid;
2706 if (txn->mt_txnid == mdb_debug_start)
2709 txn->mt_child = NULL;
2710 txn->mt_loose_pgs = NULL;
2711 txn->mt_loose_count = 0;
2712 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2713 txn->mt_u.dirty_list = env->me_dirty_list;
2714 txn->mt_u.dirty_list[0].mid = 0;
2715 txn->mt_free_pgs = env->me_free_pgs;
2716 txn->mt_free_pgs[0] = 0;
2717 txn->mt_spill_pgs = NULL;
2719 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2722 /* Copy the DB info and flags */
2723 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
2725 /* Moved to here to avoid a data race in read TXNs */
2726 txn->mt_next_pgno = meta->mm_last_pg+1;
2728 txn->mt_flags = flags;
2731 txn->mt_numdbs = env->me_numdbs;
2732 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
2733 x = env->me_dbflags[i];
2734 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2735 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
2737 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
2738 txn->mt_dbflags[FREE_DBI] = DB_VALID;
2740 if (env->me_flags & MDB_FATAL_ERROR) {
2741 DPUTS("environment had fatal error, must shutdown!");
2743 } else if (env->me_maxpg < txn->mt_next_pgno) {
2744 rc = MDB_MAP_RESIZED;
2748 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
2753 mdb_txn_renew(MDB_txn *txn)
2757 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
2760 rc = mdb_txn_renew0(txn);
2761 if (rc == MDB_SUCCESS) {
2762 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2763 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2764 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2770 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2774 int rc, size, tsize;
2776 flags &= MDB_TXN_BEGIN_FLAGS;
2777 flags |= env->me_flags & MDB_WRITEMAP;
2779 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
2783 /* Nested transactions: Max 1 child, write txns only, no writemap */
2784 flags |= parent->mt_flags;
2785 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
2786 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2788 /* Child txns save MDB_pgstate and use own copy of cursors */
2789 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
2790 size += tsize = sizeof(MDB_ntxn);
2791 } else if (flags & MDB_RDONLY) {
2792 size = env->me_maxdbs * (sizeof(MDB_db)+1);
2793 size += tsize = sizeof(MDB_txn);
2795 /* Reuse preallocated write txn. However, do not touch it until
2796 * mdb_txn_renew0() succeeds, since it currently may be active.
2801 if ((txn = calloc(1, size)) == NULL) {
2802 DPRINTF(("calloc: %s", strerror(errno)));
2805 txn->mt_dbxs = env->me_dbxs; /* static */
2806 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2807 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
2808 txn->mt_flags = flags;
2813 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2814 txn->mt_dbiseqs = parent->mt_dbiseqs;
2815 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2816 if (!txn->mt_u.dirty_list ||
2817 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2819 free(txn->mt_u.dirty_list);
2823 txn->mt_txnid = parent->mt_txnid;
2824 txn->mt_dirty_room = parent->mt_dirty_room;
2825 txn->mt_u.dirty_list[0].mid = 0;
2826 txn->mt_spill_pgs = NULL;
2827 txn->mt_next_pgno = parent->mt_next_pgno;
2828 parent->mt_flags |= MDB_TXN_HAS_CHILD;
2829 parent->mt_child = txn;
2830 txn->mt_parent = parent;
2831 txn->mt_numdbs = parent->mt_numdbs;
2832 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2833 /* Copy parent's mt_dbflags, but clear DB_NEW */
2834 for (i=0; i<txn->mt_numdbs; i++)
2835 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2837 ntxn = (MDB_ntxn *)txn;
2838 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2839 if (env->me_pghead) {
2840 size = MDB_IDL_SIZEOF(env->me_pghead);
2841 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2843 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2848 rc = mdb_cursor_shadow(parent, txn);
2850 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
2851 } else { /* MDB_RDONLY */
2852 txn->mt_dbiseqs = env->me_dbiseqs;
2854 rc = mdb_txn_renew0(txn);
2857 if (txn != env->me_txn0)
2860 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
2862 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2863 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
2864 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2871 mdb_txn_env(MDB_txn *txn)
2873 if(!txn) return NULL;
2878 mdb_txn_id(MDB_txn *txn)
2881 return txn->mt_txnid;
2884 /** Export or close DBI handles opened in this txn. */
2886 mdb_dbis_update(MDB_txn *txn, int keep)
2889 MDB_dbi n = txn->mt_numdbs;
2890 MDB_env *env = txn->mt_env;
2891 unsigned char *tdbflags = txn->mt_dbflags;
2893 for (i = n; --i >= CORE_DBS;) {
2894 if (tdbflags[i] & DB_NEW) {
2896 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2898 char *ptr = env->me_dbxs[i].md_name.mv_data;
2900 env->me_dbxs[i].md_name.mv_data = NULL;
2901 env->me_dbxs[i].md_name.mv_size = 0;
2902 env->me_dbflags[i] = 0;
2903 env->me_dbiseqs[i]++;
2909 if (keep && env->me_numdbs < n)
2913 /** End a transaction, except successful commit of a nested transaction.
2914 * May be called twice for readonly txns: First reset it, then abort.
2915 * @param[in] txn the transaction handle to end
2916 * @param[in] mode why and how to end the transaction
2919 mdb_txn_end(MDB_txn *txn, unsigned mode)
2921 MDB_env *env = txn->mt_env;
2923 static const char *const names[] = MDB_END_NAMES;
2926 /* Export or close DBI handles opened in this txn */
2927 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
2929 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2930 names[mode & MDB_END_OPMASK],
2931 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2932 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2934 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2935 if (txn->mt_u.reader) {
2936 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2937 if (!(env->me_flags & MDB_NOTLS)) {
2938 txn->mt_u.reader = NULL; /* txn does not own reader */
2939 } else if (mode & MDB_END_SLOT) {
2940 txn->mt_u.reader->mr_pid = 0;
2941 txn->mt_u.reader = NULL;
2942 } /* else txn owns the slot until it does MDB_END_SLOT */
2944 txn->mt_numdbs = 0; /* prevent further DBI activity */
2945 txn->mt_flags |= MDB_TXN_FINISHED;
2947 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
2948 pgno_t *pghead = env->me_pghead;
2950 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
2951 mdb_cursors_close(txn, 0);
2952 if (!(env->me_flags & MDB_WRITEMAP)) {
2953 mdb_dlist_free(txn);
2957 txn->mt_flags = MDB_TXN_FINISHED;
2959 if (!txn->mt_parent) {
2960 mdb_midl_shrink(&txn->mt_free_pgs);
2961 env->me_free_pgs = txn->mt_free_pgs;
2963 env->me_pghead = NULL;
2967 mode = 0; /* txn == env->me_txn0, do not free() it */
2969 /* The writer mutex was locked in mdb_txn_begin. */
2971 UNLOCK_MUTEX(env->me_wmutex);
2973 txn->mt_parent->mt_child = NULL;
2974 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
2975 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2976 mdb_midl_free(txn->mt_free_pgs);
2977 mdb_midl_free(txn->mt_spill_pgs);
2978 free(txn->mt_u.dirty_list);
2981 mdb_midl_free(pghead);
2984 if (mode & MDB_END_FREE)
2989 mdb_txn_reset(MDB_txn *txn)
2994 /* This call is only valid for read-only txns */
2995 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2998 mdb_txn_end(txn, MDB_END_RESET);
3002 mdb_txn_abort(MDB_txn *txn)
3008 mdb_txn_abort(txn->mt_child);
3010 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3013 /** Save the freelist as of this transaction to the freeDB.
3014 * This changes the freelist. Keep trying until it stabilizes.
3017 mdb_freelist_save(MDB_txn *txn)
3019 /* env->me_pghead[] can grow and shrink during this call.
3020 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3021 * Page numbers cannot disappear from txn->mt_free_pgs[].
3024 MDB_env *env = txn->mt_env;
3025 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3026 txnid_t pglast = 0, head_id = 0;
3027 pgno_t freecnt = 0, *free_pgs, *mop;
3028 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3030 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3032 if (env->me_pghead) {
3033 /* Make sure first page of freeDB is touched and on freelist */
3034 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3035 if (rc && rc != MDB_NOTFOUND)
3039 if (!env->me_pghead && txn->mt_loose_pgs) {
3040 /* Put loose page numbers in mt_free_pgs, since
3041 * we may be unable to return them to me_pghead.
3043 MDB_page *mp = txn->mt_loose_pgs;
3044 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3046 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3047 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3048 txn->mt_loose_pgs = NULL;
3049 txn->mt_loose_count = 0;
3052 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3053 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3054 ? SSIZE_MAX : maxfree_1pg;
3057 /* Come back here after each Put() in case freelist changed */
3062 /* If using records from freeDB which we have not yet
3063 * deleted, delete them and any we reserved for me_pghead.
3065 while (pglast < env->me_pglast) {
3066 rc = mdb_cursor_first(&mc, &key, NULL);
3069 pglast = head_id = *(txnid_t *)key.mv_data;
3070 total_room = head_room = 0;
3071 mdb_tassert(txn, pglast <= env->me_pglast);
3072 rc = mdb_cursor_del(&mc, 0);
3077 /* Save the IDL of pages freed by this txn, to a single record */
3078 if (freecnt < txn->mt_free_pgs[0]) {
3080 /* Make sure last page of freeDB is touched and on freelist */
3081 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3082 if (rc && rc != MDB_NOTFOUND)
3085 free_pgs = txn->mt_free_pgs;
3086 /* Write to last page of freeDB */
3087 key.mv_size = sizeof(txn->mt_txnid);
3088 key.mv_data = &txn->mt_txnid;
3090 freecnt = free_pgs[0];
3091 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3092 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3095 /* Retry if mt_free_pgs[] grew during the Put() */
3096 free_pgs = txn->mt_free_pgs;
3097 } while (freecnt < free_pgs[0]);
3098 mdb_midl_sort(free_pgs);
3099 memcpy(data.mv_data, free_pgs, data.mv_size);
3102 unsigned int i = free_pgs[0];
3103 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
3104 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3106 DPRINTF(("IDL %"Z"u", free_pgs[i]));
3112 mop = env->me_pghead;
3113 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3115 /* Reserve records for me_pghead[]. Split it if multi-page,
3116 * to avoid searching freeDB for a page range. Use keys in
3117 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3119 if (total_room >= mop_len) {
3120 if (total_room == mop_len || --more < 0)
3122 } else if (head_room >= maxfree_1pg && head_id > 1) {
3123 /* Keep current record (overflow page), add a new one */
3127 /* (Re)write {key = head_id, IDL length = head_room} */
3128 total_room -= head_room;
3129 head_room = mop_len - total_room;
3130 if (head_room > maxfree_1pg && head_id > 1) {
3131 /* Overflow multi-page for part of me_pghead */
3132 head_room /= head_id; /* amortize page sizes */
3133 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3134 } else if (head_room < 0) {
3135 /* Rare case, not bothering to delete this record */
3138 key.mv_size = sizeof(head_id);
3139 key.mv_data = &head_id;
3140 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3141 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3144 /* IDL is initially empty, zero out at least the length */
3145 pgs = (pgno_t *)data.mv_data;
3146 j = head_room > clean_limit ? head_room : 0;
3150 total_room += head_room;
3153 /* Return loose page numbers to me_pghead, though usually none are
3154 * left at this point. The pages themselves remain in dirty_list.
3156 if (txn->mt_loose_pgs) {
3157 MDB_page *mp = txn->mt_loose_pgs;
3158 unsigned count = txn->mt_loose_count;
3160 /* Room for loose pages + temp IDL with same */
3161 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3163 mop = env->me_pghead;
3164 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3165 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3166 loose[ ++count ] = mp->mp_pgno;
3168 mdb_midl_sort(loose);
3169 mdb_midl_xmerge(mop, loose);
3170 txn->mt_loose_pgs = NULL;
3171 txn->mt_loose_count = 0;
3175 /* Fill in the reserved me_pghead records */
3181 rc = mdb_cursor_first(&mc, &key, &data);
3182 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3183 txnid_t id = *(txnid_t *)key.mv_data;
3184 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3187 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3189 if (len > mop_len) {
3191 data.mv_size = (len + 1) * sizeof(MDB_ID);
3193 data.mv_data = mop -= len;
3196 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3198 if (rc || !(mop_len -= len))
3205 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3206 * @param[in] txn the transaction that's being committed
3207 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3208 * @return 0 on success, non-zero on failure.
3211 mdb_page_flush(MDB_txn *txn, int keep)
3213 MDB_env *env = txn->mt_env;
3214 MDB_ID2L dl = txn->mt_u.dirty_list;
3215 unsigned psize = env->me_psize, j;
3216 int i, pagecount = dl[0].mid, rc;
3217 size_t size = 0, pos = 0;
3219 MDB_page *dp = NULL;
3223 struct iovec iov[MDB_COMMIT_PAGES];
3224 ssize_t wpos = 0, wsize = 0, wres;
3225 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3231 if (env->me_flags & MDB_WRITEMAP) {
3232 /* Clear dirty flags */
3233 while (++i <= pagecount) {
3235 /* Don't flush this page yet */
3236 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3237 dp->mp_flags &= ~P_KEEP;
3241 dp->mp_flags &= ~P_DIRTY;
3246 /* Write the pages */
3248 if (++i <= pagecount) {
3250 /* Don't flush this page yet */
3251 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3252 dp->mp_flags &= ~P_KEEP;
3257 /* clear dirty flag */
3258 dp->mp_flags &= ~P_DIRTY;
3261 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3266 /* Windows actually supports scatter/gather I/O, but only on
3267 * unbuffered file handles. Since we're relying on the OS page
3268 * cache for all our data, that's self-defeating. So we just
3269 * write pages one at a time. We use the ov structure to set
3270 * the write offset, to at least save the overhead of a Seek
3273 DPRINTF(("committing page %"Z"u", pgno));
3274 memset(&ov, 0, sizeof(ov));
3275 ov.Offset = pos & 0xffffffff;
3276 ov.OffsetHigh = pos >> 16 >> 16;
3277 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3279 DPRINTF(("WriteFile: %d", rc));
3283 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3284 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3287 /* Write previous page(s) */
3288 #ifdef MDB_USE_PWRITEV
3289 wres = pwritev(env->me_fd, iov, n, wpos);
3292 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3295 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3299 DPRINTF(("lseek: %s", strerror(rc)));
3302 wres = writev(env->me_fd, iov, n);
3305 if (wres != wsize) {
3310 DPRINTF(("Write error: %s", strerror(rc)));
3312 rc = EIO; /* TODO: Use which error code? */
3313 DPUTS("short write, filesystem full?");
3324 DPRINTF(("committing page %"Z"u", pgno));
3325 next_pos = pos + size;
3326 iov[n].iov_len = size;
3327 iov[n].iov_base = (char *)dp;
3333 /* MIPS has cache coherency issues, this is a no-op everywhere else
3334 * Note: for any size >= on-chip cache size, entire on-chip cache is
3337 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3339 for (i = keep; ++i <= pagecount; ) {
3341 /* This is a page we skipped above */
3344 dl[j].mid = dp->mp_pgno;
3347 mdb_dpage_free(env, dp);
3352 txn->mt_dirty_room += i - j;
3358 mdb_txn_commit(MDB_txn *txn)
3361 unsigned int i, end_mode;
3367 /* mdb_txn_end() mode for a commit which writes nothing */
3368 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3370 if (txn->mt_child) {
3371 rc = mdb_txn_commit(txn->mt_child);
3378 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3382 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3383 DPUTS("txn has failed/finished, can't commit");
3385 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3390 if (txn->mt_parent) {
3391 MDB_txn *parent = txn->mt_parent;
3395 unsigned x, y, len, ps_len;
3397 /* Append our free list to parent's */
3398 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3401 mdb_midl_free(txn->mt_free_pgs);
3402 /* Failures after this must either undo the changes
3403 * to the parent or set MDB_TXN_ERROR in the parent.
3406 parent->mt_next_pgno = txn->mt_next_pgno;
3407 parent->mt_flags = txn->mt_flags;
3409 /* Merge our cursors into parent's and close them */
3410 mdb_cursors_close(txn, 1);
3412 /* Update parent's DB table. */
3413 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3414 parent->mt_numdbs = txn->mt_numdbs;
3415 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3416 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3417 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3418 /* preserve parent's DB_NEW status */
3419 x = parent->mt_dbflags[i] & DB_NEW;
3420 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3423 dst = parent->mt_u.dirty_list;
3424 src = txn->mt_u.dirty_list;
3425 /* Remove anything in our dirty list from parent's spill list */
3426 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3428 pspill[0] = (pgno_t)-1;
3429 /* Mark our dirty pages as deleted in parent spill list */
3430 for (i=0, len=src[0].mid; ++i <= len; ) {
3431 MDB_ID pn = src[i].mid << 1;
3432 while (pn > pspill[x])
3434 if (pn == pspill[x]) {
3439 /* Squash deleted pagenums if we deleted any */
3440 for (x=y; ++x <= ps_len; )
3441 if (!(pspill[x] & 1))
3442 pspill[++y] = pspill[x];
3446 /* Remove anything in our spill list from parent's dirty list */
3447 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3448 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3449 MDB_ID pn = txn->mt_spill_pgs[i];
3451 continue; /* deleted spillpg */
3453 y = mdb_mid2l_search(dst, pn);
3454 if (y <= dst[0].mid && dst[y].mid == pn) {
3456 while (y < dst[0].mid) {
3465 /* Find len = length of merging our dirty list with parent's */
3467 dst[0].mid = 0; /* simplify loops */
3468 if (parent->mt_parent) {
3469 len = x + src[0].mid;
3470 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3471 for (i = x; y && i; y--) {
3472 pgno_t yp = src[y].mid;
3473 while (yp < dst[i].mid)
3475 if (yp == dst[i].mid) {
3480 } else { /* Simplify the above for single-ancestor case */
3481 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3483 /* Merge our dirty list with parent's */
3485 for (i = len; y; dst[i--] = src[y--]) {
3486 pgno_t yp = src[y].mid;
3487 while (yp < dst[x].mid)
3488 dst[i--] = dst[x--];
3489 if (yp == dst[x].mid)
3490 free(dst[x--].mptr);
3492 mdb_tassert(txn, i == x);
3494 free(txn->mt_u.dirty_list);
3495 parent->mt_dirty_room = txn->mt_dirty_room;
3496 if (txn->mt_spill_pgs) {
3497 if (parent->mt_spill_pgs) {
3498 /* TODO: Prevent failure here, so parent does not fail */
3499 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3501 parent->mt_flags |= MDB_TXN_ERROR;
3502 mdb_midl_free(txn->mt_spill_pgs);
3503 mdb_midl_sort(parent->mt_spill_pgs);
3505 parent->mt_spill_pgs = txn->mt_spill_pgs;
3509 /* Append our loose page list to parent's */
3510 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3512 *lp = txn->mt_loose_pgs;
3513 parent->mt_loose_count += txn->mt_loose_count;
3515 parent->mt_child = NULL;
3516 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3521 if (txn != env->me_txn) {
3522 DPUTS("attempt to commit unknown transaction");
3527 mdb_cursors_close(txn, 0);
3529 if (!txn->mt_u.dirty_list[0].mid &&
3530 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3533 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3534 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3536 /* Update DB root pointers */
3537 if (txn->mt_numdbs > CORE_DBS) {
3541 data.mv_size = sizeof(MDB_db);
3543 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3544 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3545 if (txn->mt_dbflags[i] & DB_DIRTY) {
3546 if (TXN_DBI_CHANGED(txn, i)) {
3550 data.mv_data = &txn->mt_dbs[i];
3551 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3559 rc = mdb_freelist_save(txn);
3563 mdb_midl_free(env->me_pghead);
3564 env->me_pghead = NULL;
3565 mdb_midl_shrink(&txn->mt_free_pgs);
3571 if ((rc = mdb_page_flush(txn, 0)) ||
3572 (rc = mdb_env_sync(env, 0)) ||
3573 (rc = mdb_env_write_meta(txn)))
3575 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3578 mdb_txn_end(txn, end_mode);
3586 /** Read the environment parameters of a DB environment before
3587 * mapping it into memory.
3588 * @param[in] env the environment handle
3589 * @param[out] meta address of where to store the meta information
3590 * @return 0 on success, non-zero on failure.
3593 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3599 enum { Size = sizeof(pbuf) };
3601 /* We don't know the page size yet, so use a minimum value.
3602 * Read both meta pages so we can use the latest one.
3605 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3609 memset(&ov, 0, sizeof(ov));
3611 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3612 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3615 rc = pread(env->me_fd, &pbuf, Size, off);
3618 if (rc == 0 && off == 0)
3620 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3621 DPRINTF(("read: %s", mdb_strerror(rc)));
3625 p = (MDB_page *)&pbuf;
3627 if (!F_ISSET(p->mp_flags, P_META)) {
3628 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3633 if (m->mm_magic != MDB_MAGIC) {
3634 DPUTS("meta has invalid magic");
3638 if (m->mm_version != MDB_DATA_VERSION) {
3639 DPRINTF(("database is version %u, expected version %u",
3640 m->mm_version, MDB_DATA_VERSION));
3641 return MDB_VERSION_MISMATCH;
3644 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3650 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3652 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3654 meta->mm_magic = MDB_MAGIC;
3655 meta->mm_version = MDB_DATA_VERSION;
3656 meta->mm_mapsize = env->me_mapsize;
3657 meta->mm_psize = env->me_psize;
3658 meta->mm_last_pg = NUM_METAS-1;
3659 meta->mm_flags = env->me_flags & 0xffff;
3660 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3661 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3662 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3665 /** Write the environment parameters of a freshly created DB environment.
3666 * @param[in] env the environment handle
3667 * @param[in] meta the #MDB_meta to write
3668 * @return 0 on success, non-zero on failure.
3671 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3679 memset(&ov, 0, sizeof(ov));
3680 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3682 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3685 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3686 len = pwrite(fd, ptr, size, pos); \
3687 if (len == -1 && ErrCode() == EINTR) continue; \
3688 rc = (len >= 0); break; } while(1)
3691 DPUTS("writing new meta page");
3693 psize = env->me_psize;
3695 p = calloc(NUM_METAS, psize);
3700 p->mp_flags = P_META;
3701 *(MDB_meta *)METADATA(p) = *meta;
3703 q = (MDB_page *)((char *)p + psize);
3705 q->mp_flags = P_META;
3706 *(MDB_meta *)METADATA(q) = *meta;
3708 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
3711 else if ((unsigned) len == psize * NUM_METAS)
3719 /** Update the environment info to commit a transaction.
3720 * @param[in] txn the transaction that's being committed
3721 * @return 0 on success, non-zero on failure.
3724 mdb_env_write_meta(MDB_txn *txn)
3727 MDB_meta meta, metab, *mp;
3731 int rc, len, toggle;
3740 toggle = txn->mt_txnid & 1;
3741 DPRINTF(("writing meta page %d for root page %"Z"u",
3742 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3745 flags = env->me_flags;
3746 mp = env->me_metas[toggle];
3747 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3748 /* Persist any increases of mapsize config */
3749 if (mapsize < env->me_mapsize)
3750 mapsize = env->me_mapsize;
3752 if (flags & MDB_WRITEMAP) {
3753 mp->mm_mapsize = mapsize;
3754 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3755 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3756 mp->mm_last_pg = txn->mt_next_pgno - 1;
3757 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
3758 !(defined(__i386__) || defined(__x86_64__))
3759 /* LY: issue a memory barrier, if not x86. ITS#7969 */
3760 __sync_synchronize();
3762 mp->mm_txnid = txn->mt_txnid;
3763 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3764 unsigned meta_size = env->me_psize;
3765 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3766 ptr = (char *)mp - PAGEHDRSZ;
3767 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3768 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
3772 if (MDB_MSYNC(ptr, meta_size, rc)) {
3779 metab.mm_txnid = mp->mm_txnid;
3780 metab.mm_last_pg = mp->mm_last_pg;
3782 meta.mm_mapsize = mapsize;
3783 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3784 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3785 meta.mm_last_pg = txn->mt_next_pgno - 1;
3786 meta.mm_txnid = txn->mt_txnid;
3788 off = offsetof(MDB_meta, mm_mapsize);
3789 ptr = (char *)&meta + off;
3790 len = sizeof(MDB_meta) - off;
3791 off += (char *)mp - env->me_map;
3793 /* Write to the SYNC fd */
3794 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
3797 memset(&ov, 0, sizeof(ov));
3799 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3804 rc = pwrite(mfd, ptr, len, off);
3807 rc = rc < 0 ? ErrCode() : EIO;
3812 DPUTS("write failed, disk error?");
3813 /* On a failure, the pagecache still contains the new data.
3814 * Write some old data back, to prevent it from being used.
3815 * Use the non-SYNC fd; we know it will fail anyway.
3817 meta.mm_last_pg = metab.mm_last_pg;
3818 meta.mm_txnid = metab.mm_txnid;
3820 memset(&ov, 0, sizeof(ov));
3822 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3824 r2 = pwrite(env->me_fd, ptr, len, off);
3825 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3828 env->me_flags |= MDB_FATAL_ERROR;
3831 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3832 CACHEFLUSH(env->me_map + off, len, DCACHE);
3834 /* Memory ordering issues are irrelevant; since the entire writer
3835 * is wrapped by wmutex, all of these changes will become visible
3836 * after the wmutex is unlocked. Since the DB is multi-version,
3837 * readers will get consistent data regardless of how fresh or
3838 * how stale their view of these values is.
3841 env->me_txns->mti_txnid = txn->mt_txnid;
3846 /** Check both meta pages to see which one is newer.
3847 * @param[in] env the environment handle
3848 * @return newest #MDB_meta.
3851 mdb_env_pick_meta(const MDB_env *env)
3853 MDB_meta *const *metas = env->me_metas;
3854 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
3858 mdb_env_create(MDB_env **env)
3862 e = calloc(1, sizeof(MDB_env));
3866 e->me_maxreaders = DEFAULT_READERS;
3867 e->me_maxdbs = e->me_numdbs = CORE_DBS;
3868 e->me_fd = INVALID_HANDLE_VALUE;
3869 e->me_lfd = INVALID_HANDLE_VALUE;
3870 e->me_mfd = INVALID_HANDLE_VALUE;
3871 #ifdef MDB_USE_POSIX_SEM
3872 e->me_rmutex = SEM_FAILED;
3873 e->me_wmutex = SEM_FAILED;
3875 e->me_pid = getpid();
3876 GET_PAGESIZE(e->me_os_psize);
3877 VGMEMP_CREATE(e,0,0);
3883 mdb_env_map(MDB_env *env, void *addr)
3886 unsigned int flags = env->me_flags;
3890 LONG sizelo, sizehi;
3893 if (flags & MDB_RDONLY) {
3894 /* Don't set explicit map size, use whatever exists */
3899 msize = env->me_mapsize;
3900 sizelo = msize & 0xffffffff;
3901 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3903 /* Windows won't create mappings for zero length files.
3904 * and won't map more than the file size.
3905 * Just set the maxsize right now.
3907 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3908 || !SetEndOfFile(env->me_fd)
3909 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3913 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3914 PAGE_READWRITE : PAGE_READONLY,
3915 sizehi, sizelo, NULL);
3918 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3919 FILE_MAP_WRITE : FILE_MAP_READ,
3921 rc = env->me_map ? 0 : ErrCode();
3926 int prot = PROT_READ;
3927 if (flags & MDB_WRITEMAP) {
3929 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3932 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3934 if (env->me_map == MAP_FAILED) {
3939 if (flags & MDB_NORDAHEAD) {
3940 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3942 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3944 #ifdef POSIX_MADV_RANDOM
3945 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3946 #endif /* POSIX_MADV_RANDOM */
3947 #endif /* MADV_RANDOM */
3951 /* Can happen because the address argument to mmap() is just a
3952 * hint. mmap() can pick another, e.g. if the range is in use.
3953 * The MAP_FIXED flag would prevent that, but then mmap could
3954 * instead unmap existing pages to make room for the new map.
3956 if (addr && env->me_map != addr)
3957 return EBUSY; /* TODO: Make a new MDB_* error code? */
3959 p = (MDB_page *)env->me_map;
3960 env->me_metas[0] = METADATA(p);
3961 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3967 mdb_env_set_mapsize(MDB_env *env, size_t size)
3969 /* If env is already open, caller is responsible for making
3970 * sure there are no active txns.
3978 meta = mdb_env_pick_meta(env);
3980 size = meta->mm_mapsize;
3982 /* Silently round up to minimum if the size is too small */
3983 size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
3987 munmap(env->me_map, env->me_mapsize);
3988 env->me_mapsize = size;
3989 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3990 rc = mdb_env_map(env, old);
3994 env->me_mapsize = size;
3996 env->me_maxpg = env->me_mapsize / env->me_psize;
4001 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4005 env->me_maxdbs = dbs + CORE_DBS;
4010 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4012 if (env->me_map || readers < 1)
4014 env->me_maxreaders = readers;
4019 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4021 if (!env || !readers)
4023 *readers = env->me_maxreaders;
4028 mdb_fsize(HANDLE fd, size_t *size)
4031 LARGE_INTEGER fsize;
4033 if (!GetFileSizeEx(fd, &fsize))
4036 *size = fsize.QuadPart;
4048 #ifdef BROKEN_FDATASYNC
4049 #include <sys/utsname.h>
4050 #include <sys/vfs.h>
4053 /** Further setup required for opening an LMDB environment
4056 mdb_env_open2(MDB_env *env)
4058 unsigned int flags = env->me_flags;
4059 int i, newenv = 0, rc;
4063 /* See if we should use QueryLimited */
4065 if ((rc & 0xff) > 5)
4066 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4068 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4071 #ifdef BROKEN_FDATASYNC
4072 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4073 * https://lkml.org/lkml/2012/9/3/83
4074 * Kernels after 3.6-rc6 are known good.
4075 * https://lkml.org/lkml/2012/9/10/556
4076 * See if the DB is on ext3/ext4, then check for new enough kernel
4077 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4082 fstatfs(env->me_fd, &st);
4083 while (st.f_type == 0xEF53) {
4087 if (uts.release[0] < '3') {
4088 if (!strncmp(uts.release, "2.6.32.", 7)) {
4089 i = atoi(uts.release+7);
4091 break; /* 2.6.32.60 and newer is OK */
4092 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4093 i = atoi(uts.release+7);
4095 break; /* 2.6.34.15 and newer is OK */
4097 } else if (uts.release[0] == '3') {
4098 i = atoi(uts.release+2);
4100 break; /* 3.6 and newer is OK */
4102 i = atoi(uts.release+4);
4104 break; /* 3.5.4 and newer is OK */
4105 } else if (i == 2) {
4106 i = atoi(uts.release+4);
4108 break; /* 3.2.30 and newer is OK */
4110 } else { /* 4.x and newer is OK */
4113 env->me_flags |= MDB_FSYNCONLY;
4119 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4122 DPUTS("new mdbenv");
4124 env->me_psize = env->me_os_psize;
4125 if (env->me_psize > MAX_PAGESIZE)
4126 env->me_psize = MAX_PAGESIZE;
4127 memset(&meta, 0, sizeof(meta));
4128 mdb_env_init_meta0(env, &meta);
4129 meta.mm_mapsize = DEFAULT_MAPSIZE;
4131 env->me_psize = meta.mm_psize;
4134 /* Was a mapsize configured? */
4135 if (!env->me_mapsize) {
4136 env->me_mapsize = meta.mm_mapsize;
4139 /* Make sure mapsize >= committed data size. Even when using
4140 * mm_mapsize, which could be broken in old files (ITS#7789).
4142 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4143 if (env->me_mapsize < minsize)
4144 env->me_mapsize = minsize;
4146 meta.mm_mapsize = env->me_mapsize;
4148 if (newenv && !(flags & MDB_FIXEDMAP)) {
4149 /* mdb_env_map() may grow the datafile. Write the metapages
4150 * first, so the file will be valid if initialization fails.
4151 * Except with FIXEDMAP, since we do not yet know mm_address.
4152 * We could fill in mm_address later, but then a different
4153 * program might end up doing that - one with a memory layout
4154 * and map address which does not suit the main program.
4156 rc = mdb_env_init_meta(env, &meta);
4162 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4167 if (flags & MDB_FIXEDMAP)
4168 meta.mm_address = env->me_map;
4169 i = mdb_env_init_meta(env, &meta);
4170 if (i != MDB_SUCCESS) {
4175 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4176 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4178 #if !(MDB_MAXKEYSIZE)
4179 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4181 env->me_maxpg = env->me_mapsize / env->me_psize;
4185 MDB_meta *meta = mdb_env_pick_meta(env);
4186 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4188 DPRINTF(("opened database version %u, pagesize %u",
4189 meta->mm_version, env->me_psize));
4190 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4191 DPRINTF(("depth: %u", db->md_depth));
4192 DPRINTF(("entries: %"Z"u", db->md_entries));
4193 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
4194 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
4195 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
4196 DPRINTF(("root: %"Z"u", db->md_root));
4204 /** Release a reader thread's slot in the reader lock table.
4205 * This function is called automatically when a thread exits.
4206 * @param[in] ptr This points to the slot in the reader lock table.
4209 mdb_env_reader_dest(void *ptr)
4211 MDB_reader *reader = ptr;
4217 /** Junk for arranging thread-specific callbacks on Windows. This is
4218 * necessarily platform and compiler-specific. Windows supports up
4219 * to 1088 keys. Let's assume nobody opens more than 64 environments
4220 * in a single process, for now. They can override this if needed.
4222 #ifndef MAX_TLS_KEYS
4223 #define MAX_TLS_KEYS 64
4225 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4226 static int mdb_tls_nkeys;
4228 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4232 case DLL_PROCESS_ATTACH: break;
4233 case DLL_THREAD_ATTACH: break;
4234 case DLL_THREAD_DETACH:
4235 for (i=0; i<mdb_tls_nkeys; i++) {
4236 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4238 mdb_env_reader_dest(r);
4242 case DLL_PROCESS_DETACH: break;
4247 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4249 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4253 /* Force some symbol references.
4254 * _tls_used forces the linker to create the TLS directory if not already done
4255 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4257 #pragma comment(linker, "/INCLUDE:_tls_used")
4258 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4259 #pragma const_seg(".CRT$XLB")
4260 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4261 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4264 #pragma comment(linker, "/INCLUDE:__tls_used")
4265 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4266 #pragma data_seg(".CRT$XLB")
4267 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4269 #endif /* WIN 32/64 */
4270 #endif /* !__GNUC__ */
4273 /** Downgrade the exclusive lock on the region back to shared */
4275 mdb_env_share_locks(MDB_env *env, int *excl)
4278 MDB_meta *meta = mdb_env_pick_meta(env);
4280 env->me_txns->mti_txnid = meta->mm_txnid;
4285 /* First acquire a shared lock. The Unlock will
4286 * then release the existing exclusive lock.
4288 memset(&ov, 0, sizeof(ov));
4289 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4292 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4298 struct flock lock_info;
4299 /* The shared lock replaces the existing lock */
4300 memset((void *)&lock_info, 0, sizeof(lock_info));
4301 lock_info.l_type = F_RDLCK;
4302 lock_info.l_whence = SEEK_SET;
4303 lock_info.l_start = 0;
4304 lock_info.l_len = 1;
4305 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4306 (rc = ErrCode()) == EINTR) ;
4307 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4314 /** Try to get exclusive lock, otherwise shared.
4315 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4318 mdb_env_excl_lock(MDB_env *env, int *excl)
4322 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4326 memset(&ov, 0, sizeof(ov));
4327 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4334 struct flock lock_info;
4335 memset((void *)&lock_info, 0, sizeof(lock_info));
4336 lock_info.l_type = F_WRLCK;
4337 lock_info.l_whence = SEEK_SET;
4338 lock_info.l_start = 0;
4339 lock_info.l_len = 1;
4340 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4341 (rc = ErrCode()) == EINTR) ;
4345 # ifndef MDB_USE_POSIX_MUTEX
4346 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4349 lock_info.l_type = F_RDLCK;
4350 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4351 (rc = ErrCode()) == EINTR) ;
4361 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4363 * @(#) $Revision: 5.1 $
4364 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4365 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4367 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4371 * Please do not copyright this code. This code is in the public domain.
4373 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4374 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4375 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4376 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4377 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4378 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4379 * PERFORMANCE OF THIS SOFTWARE.
4382 * chongo <Landon Curt Noll> /\oo/\
4383 * http://www.isthe.com/chongo/
4385 * Share and Enjoy! :-)
4388 typedef unsigned long long mdb_hash_t;
4389 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4391 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4392 * @param[in] val value to hash
4393 * @param[in] hval initial value for hash
4394 * @return 64 bit hash
4396 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4397 * hval arg on the first call.
4400 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4402 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4403 unsigned char *end = s + val->mv_size;
4405 * FNV-1a hash each octet of the string
4408 /* xor the bottom with the current octet */
4409 hval ^= (mdb_hash_t)*s++;
4411 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4412 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4413 (hval << 7) + (hval << 8) + (hval << 40);
4415 /* return our new hash value */
4419 /** Hash the string and output the encoded hash.
4420 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4421 * very short name limits. We don't care about the encoding being reversible,
4422 * we just want to preserve as many bits of the input as possible in a
4423 * small printable string.
4424 * @param[in] str string to hash
4425 * @param[out] encbuf an array of 11 chars to hold the hash
4427 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4430 mdb_pack85(unsigned long l, char *out)
4434 for (i=0; i<5; i++) {
4435 *out++ = mdb_a85[l % 85];
4441 mdb_hash_enc(MDB_val *val, char *encbuf)
4443 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4445 mdb_pack85(h, encbuf);
4446 mdb_pack85(h>>32, encbuf+5);
4451 /** Open and/or initialize the lock region for the environment.
4452 * @param[in] env The LMDB environment.
4453 * @param[in] lpath The pathname of the file used for the lock region.
4454 * @param[in] mode The Unix permissions for the file, if we create it.
4455 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4456 * @return 0 on success, non-zero on failure.
4459 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4462 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4464 # define MDB_ERRCODE_ROFS EROFS
4465 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4466 # define MDB_CLOEXEC O_CLOEXEC
4469 # define MDB_CLOEXEC 0
4477 rc = utf8_to_utf16(lpath, -1, &wlpath, NULL);
4480 env->me_lfd = CreateFileW(wlpath, GENERIC_READ|GENERIC_WRITE,
4481 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4482 FILE_ATTRIBUTE_NORMAL, NULL);
4485 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4487 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4489 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4494 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4495 /* Lose record locks when exec*() */
4496 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4497 fcntl(env->me_lfd, F_SETFD, fdflags);
4500 if (!(env->me_flags & MDB_NOTLS)) {
4501 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4504 env->me_flags |= MDB_ENV_TXKEY;
4506 /* Windows TLS callbacks need help finding their TLS info. */
4507 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4511 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4515 /* Try to get exclusive lock. If we succeed, then
4516 * nobody is using the lock region and we should initialize it.
4518 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4521 size = GetFileSize(env->me_lfd, NULL);
4523 size = lseek(env->me_lfd, 0, SEEK_END);
4524 if (size == -1) goto fail_errno;
4526 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4527 if (size < rsize && *excl > 0) {
4529 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4530 || !SetEndOfFile(env->me_lfd))
4533 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4537 size = rsize - sizeof(MDB_txninfo);
4538 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4543 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4545 if (!mh) goto fail_errno;
4546 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4548 if (!env->me_txns) goto fail_errno;
4550 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4552 if (m == MAP_FAILED) goto fail_errno;
4558 BY_HANDLE_FILE_INFORMATION stbuf;
4567 if (!mdb_sec_inited) {
4568 InitializeSecurityDescriptor(&mdb_null_sd,
4569 SECURITY_DESCRIPTOR_REVISION);
4570 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4571 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4572 mdb_all_sa.bInheritHandle = FALSE;
4573 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4576 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4577 idbuf.volume = stbuf.dwVolumeSerialNumber;
4578 idbuf.nhigh = stbuf.nFileIndexHigh;
4579 idbuf.nlow = stbuf.nFileIndexLow;
4580 val.mv_data = &idbuf;
4581 val.mv_size = sizeof(idbuf);
4582 mdb_hash_enc(&val, encbuf);
4583 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4584 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4585 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4586 if (!env->me_rmutex) goto fail_errno;
4587 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4588 if (!env->me_wmutex) goto fail_errno;
4589 #elif defined(MDB_USE_POSIX_SEM)
4598 #if defined(__NetBSD__)
4599 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4601 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4602 idbuf.dev = stbuf.st_dev;
4603 idbuf.ino = stbuf.st_ino;
4604 val.mv_data = &idbuf;
4605 val.mv_size = sizeof(idbuf);
4606 mdb_hash_enc(&val, encbuf);
4607 #ifdef MDB_SHORT_SEMNAMES
4608 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4610 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4611 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4612 /* Clean up after a previous run, if needed: Try to
4613 * remove both semaphores before doing anything else.
4615 sem_unlink(env->me_txns->mti_rmname);
4616 sem_unlink(env->me_txns->mti_wmname);
4617 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4618 O_CREAT|O_EXCL, mode, 1);
4619 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4620 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4621 O_CREAT|O_EXCL, mode, 1);
4622 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4623 #else /* MDB_USE_POSIX_MUTEX: */
4624 pthread_mutexattr_t mattr;
4626 /* Solaris needs this before initing a robust mutex. Otherwise
4627 * it may skip the init and return EBUSY "seems someone already
4628 * inited" or EINVAL "it was inited differently".
4630 memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
4631 memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
4633 if ((rc = pthread_mutexattr_init(&mattr)))
4636 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
4637 #ifdef MDB_ROBUST_SUPPORTED
4638 if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
4640 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
4641 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
4642 pthread_mutexattr_destroy(&mattr);
4645 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4647 env->me_txns->mti_magic = MDB_MAGIC;
4648 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4649 env->me_txns->mti_txnid = 0;
4650 env->me_txns->mti_numreaders = 0;
4653 if (env->me_txns->mti_magic != MDB_MAGIC) {
4654 DPUTS("lock region has invalid magic");
4658 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4659 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4660 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4661 rc = MDB_VERSION_MISMATCH;
4665 if (rc && rc != EACCES && rc != EAGAIN) {
4669 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4670 if (!env->me_rmutex) goto fail_errno;
4671 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4672 if (!env->me_wmutex) goto fail_errno;
4673 #elif defined(MDB_USE_POSIX_SEM)
4674 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4675 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4676 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4677 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4688 /** The name of the lock file in the DB environment */
4689 #define LOCKNAME "/lock.mdb"
4690 /** The name of the data file in the DB environment */
4691 #define DATANAME "/data.mdb"
4692 /** The suffix of the lock file when no subdir is used */
4693 #define LOCKSUFF "-lock"
4694 /** Only a subset of the @ref mdb_env flags can be changed
4695 * at runtime. Changing other flags requires closing the
4696 * environment and re-opening it with the new flags.
4698 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4699 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
4700 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4702 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4703 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4707 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4709 int oflags, rc, len, excl = -1;
4710 char *lpath, *dpath;
4715 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4719 if (flags & MDB_NOSUBDIR) {
4720 rc = len + sizeof(LOCKSUFF) + len + 1;
4722 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4727 if (flags & MDB_NOSUBDIR) {
4728 dpath = lpath + len + sizeof(LOCKSUFF);
4729 sprintf(lpath, "%s" LOCKSUFF, path);
4730 strcpy(dpath, path);
4732 dpath = lpath + len + sizeof(LOCKNAME);
4733 sprintf(lpath, "%s" LOCKNAME, path);
4734 sprintf(dpath, "%s" DATANAME, path);
4738 flags |= env->me_flags;
4739 if (flags & MDB_RDONLY) {
4740 /* silently ignore WRITEMAP when we're only getting read access */
4741 flags &= ~MDB_WRITEMAP;
4743 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4744 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4747 env->me_flags = flags |= MDB_ENV_ACTIVE;
4751 env->me_path = strdup(path);
4752 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4753 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4754 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4755 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4759 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
4761 /* For RDONLY, get lockfile after we know datafile exists */
4762 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4763 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4769 if (F_ISSET(flags, MDB_RDONLY)) {
4770 oflags = GENERIC_READ;
4771 len = OPEN_EXISTING;
4773 oflags = GENERIC_READ|GENERIC_WRITE;
4776 mode = FILE_ATTRIBUTE_NORMAL;
4777 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
4780 env->me_fd = CreateFileW(wpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4781 NULL, len, mode, NULL);
4784 if (F_ISSET(flags, MDB_RDONLY))
4787 oflags = O_RDWR | O_CREAT;
4789 env->me_fd = open(dpath, oflags, mode);
4791 if (env->me_fd == INVALID_HANDLE_VALUE) {
4796 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4797 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4802 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4803 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4804 env->me_mfd = env->me_fd;
4806 /* Synchronous fd for meta writes. Needed even with
4807 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4810 len = OPEN_EXISTING;
4811 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
4814 env->me_mfd = CreateFileW(wpath, oflags,
4815 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4816 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4820 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4822 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4827 DPRINTF(("opened dbenv %p", (void *) env));
4829 rc = mdb_env_share_locks(env, &excl);
4833 if (!(flags & MDB_RDONLY)) {
4835 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
4836 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
4837 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
4838 (txn = calloc(1, size)))
4840 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
4841 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
4842 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
4843 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
4845 txn->mt_dbxs = env->me_dbxs;
4846 txn->mt_flags = MDB_TXN_FINISHED;
4856 mdb_env_close0(env, excl);
4862 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4864 mdb_env_close0(MDB_env *env, int excl)
4868 if (!(env->me_flags & MDB_ENV_ACTIVE))
4871 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4873 for (i = env->me_maxdbs; --i >= CORE_DBS; )
4874 free(env->me_dbxs[i].md_name.mv_data);
4879 free(env->me_dbiseqs);
4880 free(env->me_dbflags);
4882 free(env->me_dirty_list);
4884 mdb_midl_free(env->me_free_pgs);
4886 if (env->me_flags & MDB_ENV_TXKEY) {
4887 pthread_key_delete(env->me_txkey);
4889 /* Delete our key from the global list */
4890 for (i=0; i<mdb_tls_nkeys; i++)
4891 if (mdb_tls_keys[i] == env->me_txkey) {
4892 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4900 munmap(env->me_map, env->me_mapsize);
4902 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4903 (void) close(env->me_mfd);
4904 if (env->me_fd != INVALID_HANDLE_VALUE)
4905 (void) close(env->me_fd);
4907 MDB_PID_T pid = env->me_pid;
4908 /* Clearing readers is done in this function because
4909 * me_txkey with its destructor must be disabled first.
4911 * We skip the the reader mutex, so we touch only
4912 * data owned by this process (me_close_readers and
4913 * our readers), and clear each reader atomically.
4915 for (i = env->me_close_readers; --i >= 0; )
4916 if (env->me_txns->mti_readers[i].mr_pid == pid)
4917 env->me_txns->mti_readers[i].mr_pid = 0;
4919 if (env->me_rmutex) {
4920 CloseHandle(env->me_rmutex);
4921 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4923 /* Windows automatically destroys the mutexes when
4924 * the last handle closes.
4926 #elif defined(MDB_USE_POSIX_SEM)
4927 if (env->me_rmutex != SEM_FAILED) {
4928 sem_close(env->me_rmutex);
4929 if (env->me_wmutex != SEM_FAILED)
4930 sem_close(env->me_wmutex);
4931 /* If we have the filelock: If we are the
4932 * only remaining user, clean up semaphores.
4935 mdb_env_excl_lock(env, &excl);
4937 sem_unlink(env->me_txns->mti_rmname);
4938 sem_unlink(env->me_txns->mti_wmname);
4942 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4944 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4947 /* Unlock the lockfile. Windows would have unlocked it
4948 * after closing anyway, but not necessarily at once.
4950 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4953 (void) close(env->me_lfd);
4956 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4960 mdb_env_close(MDB_env *env)
4967 VGMEMP_DESTROY(env);
4968 while ((dp = env->me_dpages) != NULL) {
4969 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4970 env->me_dpages = dp->mp_next;
4974 mdb_env_close0(env, 0);
4978 /** Compare two items pointing at aligned size_t's */
4980 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4982 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4983 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4986 /** Compare two items pointing at aligned unsigned int's.
4988 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
4989 * but #mdb_cmp_clong() is called instead if the data type is size_t.
4992 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4994 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4995 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4998 /** Compare two items pointing at unsigned ints of unknown alignment.
4999 * Nodes and keys are guaranteed to be 2-byte aligned.
5002 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5004 #if BYTE_ORDER == LITTLE_ENDIAN
5005 unsigned short *u, *c;
5008 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5009 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5012 } while(!x && u > (unsigned short *)a->mv_data);
5015 unsigned short *u, *c, *end;
5018 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5019 u = (unsigned short *)a->mv_data;
5020 c = (unsigned short *)b->mv_data;
5023 } while(!x && u < end);
5028 /** Compare two items lexically */
5030 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5037 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5043 diff = memcmp(a->mv_data, b->mv_data, len);
5044 return diff ? diff : len_diff<0 ? -1 : len_diff;
5047 /** Compare two items in reverse byte order */
5049 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5051 const unsigned char *p1, *p2, *p1_lim;
5055 p1_lim = (const unsigned char *)a->mv_data;
5056 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5057 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5059 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5065 while (p1 > p1_lim) {
5066 diff = *--p1 - *--p2;
5070 return len_diff<0 ? -1 : len_diff;
5073 /** Search for key within a page, using binary search.
5074 * Returns the smallest entry larger or equal to the key.
5075 * If exactp is non-null, stores whether the found entry was an exact match
5076 * in *exactp (1 or 0).
5077 * Updates the cursor index with the index of the found entry.
5078 * If no entry larger or equal to the key is found, returns NULL.
5081 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5083 unsigned int i = 0, nkeys;
5086 MDB_page *mp = mc->mc_pg[mc->mc_top];
5087 MDB_node *node = NULL;
5092 nkeys = NUMKEYS(mp);
5094 DPRINTF(("searching %u keys in %s %spage %"Z"u",
5095 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5098 low = IS_LEAF(mp) ? 0 : 1;
5100 cmp = mc->mc_dbx->md_cmp;
5102 /* Branch pages have no data, so if using integer keys,
5103 * alignment is guaranteed. Use faster mdb_cmp_int.
5105 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5106 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
5113 nodekey.mv_size = mc->mc_db->md_pad;
5114 node = NODEPTR(mp, 0); /* fake */
5115 while (low <= high) {
5116 i = (low + high) >> 1;
5117 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5118 rc = cmp(key, &nodekey);
5119 DPRINTF(("found leaf index %u [%s], rc = %i",
5120 i, DKEY(&nodekey), rc));
5129 while (low <= high) {
5130 i = (low + high) >> 1;
5132 node = NODEPTR(mp, i);
5133 nodekey.mv_size = NODEKSZ(node);
5134 nodekey.mv_data = NODEKEY(node);
5136 rc = cmp(key, &nodekey);
5139 DPRINTF(("found leaf index %u [%s], rc = %i",
5140 i, DKEY(&nodekey), rc));
5142 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
5143 i, DKEY(&nodekey), NODEPGNO(node), rc));
5154 if (rc > 0) { /* Found entry is less than the key. */
5155 i++; /* Skip to get the smallest entry larger than key. */
5157 node = NODEPTR(mp, i);
5160 *exactp = (rc == 0 && nkeys > 0);
5161 /* store the key index */
5162 mc->mc_ki[mc->mc_top] = i;
5164 /* There is no entry larger or equal to the key. */
5167 /* nodeptr is fake for LEAF2 */
5173 mdb_cursor_adjust(MDB_cursor *mc, func)
5177 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5178 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5185 /** Pop a page off the top of the cursor's stack. */
5187 mdb_cursor_pop(MDB_cursor *mc)
5190 DPRINTF(("popping page %"Z"u off db %d cursor %p",
5191 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5197 mc->mc_flags &= ~C_INITIALIZED;
5202 /** Push a page onto the top of the cursor's stack. */
5204 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5206 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
5207 DDBI(mc), (void *) mc));
5209 if (mc->mc_snum >= CURSOR_STACK) {
5210 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5211 return MDB_CURSOR_FULL;
5214 mc->mc_top = mc->mc_snum++;
5215 mc->mc_pg[mc->mc_top] = mp;
5216 mc->mc_ki[mc->mc_top] = 0;
5221 /** Find the address of the page corresponding to a given page number.
5222 * @param[in] txn the transaction for this access.
5223 * @param[in] pgno the page number for the page to retrieve.
5224 * @param[out] ret address of a pointer where the page's address will be stored.
5225 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5226 * @return 0 on success, non-zero on failure.
5229 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
5231 MDB_env *env = txn->mt_env;
5235 if (! (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_WRITEMAP))) {
5239 MDB_ID2L dl = tx2->mt_u.dirty_list;
5241 /* Spilled pages were dirtied in this txn and flushed
5242 * because the dirty list got full. Bring this page
5243 * back in from the map (but don't unspill it here,
5244 * leave that unless page_touch happens again).
5246 if (tx2->mt_spill_pgs) {
5247 MDB_ID pn = pgno << 1;
5248 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5249 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5250 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5255 unsigned x = mdb_mid2l_search(dl, pgno);
5256 if (x <= dl[0].mid && dl[x].mid == pgno) {
5262 } while ((tx2 = tx2->mt_parent) != NULL);
5265 if (pgno < txn->mt_next_pgno) {
5267 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5269 DPRINTF(("page %"Z"u not found", pgno));
5270 txn->mt_flags |= MDB_TXN_ERROR;
5271 return MDB_PAGE_NOTFOUND;
5281 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
5282 * The cursor is at the root page, set up the rest of it.
5285 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
5287 MDB_page *mp = mc->mc_pg[mc->mc_top];
5291 while (IS_BRANCH(mp)) {
5295 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
5296 /* Don't assert on branch pages in the FreeDB. We can get here
5297 * while in the process of rebalancing a FreeDB branch page; we must
5298 * let that proceed. ITS#8336
5300 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
5301 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
5303 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
5305 if (flags & MDB_PS_LAST)
5306 i = NUMKEYS(mp) - 1;
5309 node = mdb_node_search(mc, key, &exact);
5311 i = NUMKEYS(mp) - 1;
5313 i = mc->mc_ki[mc->mc_top];
5315 mdb_cassert(mc, i > 0);
5319 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
5322 mdb_cassert(mc, i < NUMKEYS(mp));
5323 node = NODEPTR(mp, i);
5325 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5328 mc->mc_ki[mc->mc_top] = i;
5329 if ((rc = mdb_cursor_push(mc, mp)))
5332 if (flags & MDB_PS_MODIFY) {
5333 if ((rc = mdb_page_touch(mc)) != 0)
5335 mp = mc->mc_pg[mc->mc_top];
5340 DPRINTF(("internal error, index points to a %02X page!?",
5342 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5343 return MDB_CORRUPTED;
5346 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
5347 key ? DKEY(key) : "null"));
5348 mc->mc_flags |= C_INITIALIZED;
5349 mc->mc_flags &= ~C_EOF;
5354 /** Search for the lowest key under the current branch page.
5355 * This just bypasses a NUMKEYS check in the current page
5356 * before calling mdb_page_search_root(), because the callers
5357 * are all in situations where the current page is known to
5361 mdb_page_search_lowest(MDB_cursor *mc)
5363 MDB_page *mp = mc->mc_pg[mc->mc_top];
5364 MDB_node *node = NODEPTR(mp, 0);
5367 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5370 mc->mc_ki[mc->mc_top] = 0;
5371 if ((rc = mdb_cursor_push(mc, mp)))
5373 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5376 /** Search for the page a given key should be in.
5377 * Push it and its parent pages on the cursor stack.
5378 * @param[in,out] mc the cursor for this operation.
5379 * @param[in] key the key to search for, or NULL for first/last page.
5380 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5381 * are touched (updated with new page numbers).
5382 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5383 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5384 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5385 * @return 0 on success, non-zero on failure.
5388 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5393 /* Make sure the txn is still viable, then find the root from
5394 * the txn's db table and set it as the root of the cursor's stack.
5396 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
5397 DPUTS("transaction may not be used now");
5400 /* Make sure we're using an up-to-date root */
5401 if (*mc->mc_dbflag & DB_STALE) {
5403 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5405 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5406 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5413 MDB_node *leaf = mdb_node_search(&mc2,
5414 &mc->mc_dbx->md_name, &exact);
5416 return MDB_NOTFOUND;
5417 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
5418 return MDB_INCOMPATIBLE; /* not a named DB */
5419 rc = mdb_node_read(mc->mc_txn, leaf, &data);
5422 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5424 /* The txn may not know this DBI, or another process may
5425 * have dropped and recreated the DB with other flags.
5427 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5428 return MDB_INCOMPATIBLE;
5429 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5431 *mc->mc_dbflag &= ~DB_STALE;
5433 root = mc->mc_db->md_root;
5435 if (root == P_INVALID) { /* Tree is empty. */
5436 DPUTS("tree is empty");
5437 return MDB_NOTFOUND;
5441 mdb_cassert(mc, root > 1);
5442 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5443 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
5449 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5450 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5452 if (flags & MDB_PS_MODIFY) {
5453 if ((rc = mdb_page_touch(mc)))
5457 if (flags & MDB_PS_ROOTONLY)
5460 return mdb_page_search_root(mc, key, flags);
5464 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5466 MDB_txn *txn = mc->mc_txn;
5467 pgno_t pg = mp->mp_pgno;
5468 unsigned x = 0, ovpages = mp->mp_pages;
5469 MDB_env *env = txn->mt_env;
5470 MDB_IDL sl = txn->mt_spill_pgs;
5471 MDB_ID pn = pg << 1;
5474 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5475 /* If the page is dirty or on the spill list we just acquired it,
5476 * so we should give it back to our current free list, if any.
5477 * Otherwise put it onto the list of pages we freed in this txn.
5479 * Won't create me_pghead: me_pglast must be inited along with it.
5480 * Unsupported in nested txns: They would need to hide the page
5481 * range in ancestor txns' dirty and spilled lists.
5483 if (env->me_pghead &&
5485 ((mp->mp_flags & P_DIRTY) ||
5486 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5490 MDB_ID2 *dl, ix, iy;
5491 rc = mdb_midl_need(&env->me_pghead, ovpages);
5494 if (!(mp->mp_flags & P_DIRTY)) {
5495 /* This page is no longer spilled */
5502 /* Remove from dirty list */
5503 dl = txn->mt_u.dirty_list;
5505 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5511 mdb_cassert(mc, x > 1);
5513 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5514 txn->mt_flags |= MDB_TXN_ERROR;
5515 return MDB_CORRUPTED;
5518 txn->mt_dirty_room++;
5519 if (!(env->me_flags & MDB_WRITEMAP))
5520 mdb_dpage_free(env, mp);
5522 /* Insert in me_pghead */
5523 mop = env->me_pghead;
5524 j = mop[0] + ovpages;
5525 for (i = mop[0]; i && mop[i] < pg; i--)
5531 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5535 mc->mc_db->md_overflow_pages -= ovpages;
5539 /** Return the data associated with a given node.
5540 * @param[in] txn The transaction for this operation.
5541 * @param[in] leaf The node being read.
5542 * @param[out] data Updated to point to the node's data.
5543 * @return 0 on success, non-zero on failure.
5546 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5548 MDB_page *omp; /* overflow page */
5552 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5553 data->mv_size = NODEDSZ(leaf);
5554 data->mv_data = NODEDATA(leaf);
5558 /* Read overflow data.
5560 data->mv_size = NODEDSZ(leaf);
5561 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5562 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5563 DPRINTF(("read overflow page %"Z"u failed", pgno));
5566 data->mv_data = METADATA(omp);
5572 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5573 MDB_val *key, MDB_val *data)
5580 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5582 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
5585 if (txn->mt_flags & MDB_TXN_BLOCKED)
5588 mdb_cursor_init(&mc, txn, dbi, &mx);
5589 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5592 /** Find a sibling for a page.
5593 * Replaces the page at the top of the cursor's stack with the
5594 * specified sibling, if one exists.
5595 * @param[in] mc The cursor for this operation.
5596 * @param[in] move_right Non-zero if the right sibling is requested,
5597 * otherwise the left sibling.
5598 * @return 0 on success, non-zero on failure.
5601 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5607 if (mc->mc_snum < 2) {
5608 return MDB_NOTFOUND; /* root has no siblings */
5612 DPRINTF(("parent page is page %"Z"u, index %u",
5613 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5615 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5616 : (mc->mc_ki[mc->mc_top] == 0)) {
5617 DPRINTF(("no more keys left, moving to %s sibling",
5618 move_right ? "right" : "left"));
5619 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5620 /* undo cursor_pop before returning */
5627 mc->mc_ki[mc->mc_top]++;
5629 mc->mc_ki[mc->mc_top]--;
5630 DPRINTF(("just moving to %s index key %u",
5631 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5633 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5635 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5636 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5637 /* mc will be inconsistent if caller does mc_snum++ as above */
5638 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5642 mdb_cursor_push(mc, mp);
5644 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5649 /** Move the cursor to the next data item. */
5651 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5657 if ((mc->mc_flags & C_EOF) ||
5658 ((mc->mc_flags & C_DEL) && op == MDB_NEXT_DUP)) {
5659 return MDB_NOTFOUND;
5661 if (!(mc->mc_flags & C_INITIALIZED))
5662 return mdb_cursor_first(mc, key, data);
5664 mp = mc->mc_pg[mc->mc_top];
5666 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5667 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5668 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5669 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5670 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5671 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5672 if (rc == MDB_SUCCESS)
5673 MDB_GET_KEY(leaf, key);
5678 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5679 if (op == MDB_NEXT_DUP)
5680 return MDB_NOTFOUND;
5684 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5685 mdb_dbg_pgno(mp), (void *) mc));
5686 if (mc->mc_flags & C_DEL) {
5687 mc->mc_flags ^= C_DEL;
5691 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5692 DPUTS("=====> move to next sibling page");
5693 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5694 mc->mc_flags |= C_EOF;
5697 mp = mc->mc_pg[mc->mc_top];
5698 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5700 mc->mc_ki[mc->mc_top]++;
5703 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5704 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5707 key->mv_size = mc->mc_db->md_pad;
5708 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5712 mdb_cassert(mc, IS_LEAF(mp));
5713 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5715 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5716 mdb_xcursor_init1(mc, leaf);
5719 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5722 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5723 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5724 if (rc != MDB_SUCCESS)
5729 MDB_GET_KEY(leaf, key);
5733 /** Move the cursor to the previous data item. */
5735 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5741 if (!(mc->mc_flags & C_INITIALIZED)) {
5742 rc = mdb_cursor_last(mc, key, data);
5745 mc->mc_ki[mc->mc_top]++;
5748 mp = mc->mc_pg[mc->mc_top];
5750 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5751 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5752 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5753 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5754 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5755 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5756 if (rc == MDB_SUCCESS) {
5757 MDB_GET_KEY(leaf, key);
5758 mc->mc_flags &= ~C_EOF;
5764 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5765 if (op == MDB_PREV_DUP)
5766 return MDB_NOTFOUND;
5770 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5771 mdb_dbg_pgno(mp), (void *) mc));
5773 mc->mc_flags &= ~(C_EOF|C_DEL);
5775 if (mc->mc_ki[mc->mc_top] == 0) {
5776 DPUTS("=====> move to prev sibling page");
5777 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5780 mp = mc->mc_pg[mc->mc_top];
5781 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5782 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5784 mc->mc_ki[mc->mc_top]--;
5786 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5787 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5790 key->mv_size = mc->mc_db->md_pad;
5791 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5795 mdb_cassert(mc, IS_LEAF(mp));
5796 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5798 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5799 mdb_xcursor_init1(mc, leaf);
5802 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5805 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5806 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5807 if (rc != MDB_SUCCESS)
5812 MDB_GET_KEY(leaf, key);
5816 /** Set the cursor on a specific data item. */
5818 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5819 MDB_cursor_op op, int *exactp)
5823 MDB_node *leaf = NULL;
5826 if (key->mv_size == 0)
5827 return MDB_BAD_VALSIZE;
5830 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5832 /* See if we're already on the right page */
5833 if (mc->mc_flags & C_INITIALIZED) {
5836 mp = mc->mc_pg[mc->mc_top];
5838 mc->mc_ki[mc->mc_top] = 0;
5839 return MDB_NOTFOUND;
5841 if (mp->mp_flags & P_LEAF2) {
5842 nodekey.mv_size = mc->mc_db->md_pad;
5843 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5845 leaf = NODEPTR(mp, 0);
5846 MDB_GET_KEY2(leaf, nodekey);
5848 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5850 /* Probably happens rarely, but first node on the page
5851 * was the one we wanted.
5853 mc->mc_ki[mc->mc_top] = 0;
5860 unsigned int nkeys = NUMKEYS(mp);
5862 if (mp->mp_flags & P_LEAF2) {
5863 nodekey.mv_data = LEAF2KEY(mp,
5864 nkeys-1, nodekey.mv_size);
5866 leaf = NODEPTR(mp, nkeys-1);
5867 MDB_GET_KEY2(leaf, nodekey);
5869 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5871 /* last node was the one we wanted */
5872 mc->mc_ki[mc->mc_top] = nkeys-1;
5878 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5879 /* This is definitely the right page, skip search_page */
5880 if (mp->mp_flags & P_LEAF2) {
5881 nodekey.mv_data = LEAF2KEY(mp,
5882 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5884 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5885 MDB_GET_KEY2(leaf, nodekey);
5887 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5889 /* current node was the one we wanted */
5899 /* If any parents have right-sibs, search.
5900 * Otherwise, there's nothing further.
5902 for (i=0; i<mc->mc_top; i++)
5904 NUMKEYS(mc->mc_pg[i])-1)
5906 if (i == mc->mc_top) {
5907 /* There are no other pages */
5908 mc->mc_ki[mc->mc_top] = nkeys;
5909 return MDB_NOTFOUND;
5913 /* There are no other pages */
5914 mc->mc_ki[mc->mc_top] = 0;
5915 if (op == MDB_SET_RANGE && !exactp) {
5919 return MDB_NOTFOUND;
5925 rc = mdb_page_search(mc, key, 0);
5926 if (rc != MDB_SUCCESS)
5929 mp = mc->mc_pg[mc->mc_top];
5930 mdb_cassert(mc, IS_LEAF(mp));
5933 leaf = mdb_node_search(mc, key, exactp);
5934 if (exactp != NULL && !*exactp) {
5935 /* MDB_SET specified and not an exact match. */
5936 return MDB_NOTFOUND;
5940 DPUTS("===> inexact leaf not found, goto sibling");
5941 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5942 mc->mc_flags |= C_EOF;
5943 return rc; /* no entries matched */
5945 mp = mc->mc_pg[mc->mc_top];
5946 mdb_cassert(mc, IS_LEAF(mp));
5947 leaf = NODEPTR(mp, 0);
5951 mc->mc_flags |= C_INITIALIZED;
5952 mc->mc_flags &= ~C_EOF;
5955 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5956 key->mv_size = mc->mc_db->md_pad;
5957 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5962 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5963 mdb_xcursor_init1(mc, leaf);
5966 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5967 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5968 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5971 if (op == MDB_GET_BOTH) {
5977 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5978 if (rc != MDB_SUCCESS)
5981 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5984 if ((rc = mdb_node_read(mc->mc_txn, leaf, &olddata)) != MDB_SUCCESS)
5986 dcmp = mc->mc_dbx->md_dcmp;
5987 #if UINT_MAX < SIZE_MAX
5988 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
5989 dcmp = mdb_cmp_clong;
5991 rc = dcmp(data, &olddata);
5993 if (op == MDB_GET_BOTH || rc > 0)
5994 return MDB_NOTFOUND;
6001 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6002 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
6007 /* The key already matches in all other cases */
6008 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6009 MDB_GET_KEY(leaf, key);
6010 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6015 /** Move the cursor to the first item in the database. */
6017 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6023 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6025 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6026 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6027 if (rc != MDB_SUCCESS)
6030 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6032 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6033 mc->mc_flags |= C_INITIALIZED;
6034 mc->mc_flags &= ~C_EOF;
6036 mc->mc_ki[mc->mc_top] = 0;
6038 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6039 key->mv_size = mc->mc_db->md_pad;
6040 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
6045 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6046 mdb_xcursor_init1(mc, leaf);
6047 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6051 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
6055 MDB_GET_KEY(leaf, key);
6059 /** Move the cursor to the last item in the database. */
6061 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6067 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6069 if (!(mc->mc_flags & C_EOF)) {
6071 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6072 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
6073 if (rc != MDB_SUCCESS)
6076 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6079 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
6080 mc->mc_flags |= C_INITIALIZED|C_EOF;
6081 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6083 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6084 key->mv_size = mc->mc_db->md_pad;
6085 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
6090 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6091 mdb_xcursor_init1(mc, leaf);
6092 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6096 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
6101 MDB_GET_KEY(leaf, key);
6106 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6111 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
6116 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
6120 case MDB_GET_CURRENT:
6121 if (!(mc->mc_flags & C_INITIALIZED)) {
6124 MDB_page *mp = mc->mc_pg[mc->mc_top];
6125 int nkeys = NUMKEYS(mp);
6126 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
6127 mc->mc_ki[mc->mc_top] = nkeys;
6133 key->mv_size = mc->mc_db->md_pad;
6134 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6136 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6137 MDB_GET_KEY(leaf, key);
6139 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6140 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
6142 rc = mdb_node_read(mc->mc_txn, leaf, data);
6149 case MDB_GET_BOTH_RANGE:
6154 if (mc->mc_xcursor == NULL) {
6155 rc = MDB_INCOMPATIBLE;
6165 rc = mdb_cursor_set(mc, key, data, op,
6166 op == MDB_SET_RANGE ? NULL : &exact);
6169 case MDB_GET_MULTIPLE:
6170 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6174 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6175 rc = MDB_INCOMPATIBLE;
6179 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6180 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6183 case MDB_NEXT_MULTIPLE:
6188 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6189 rc = MDB_INCOMPATIBLE;
6192 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6193 if (rc == MDB_SUCCESS) {
6194 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6197 mx = &mc->mc_xcursor->mx_cursor;
6198 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
6200 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
6201 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
6209 case MDB_NEXT_NODUP:
6210 rc = mdb_cursor_next(mc, key, data, op);
6214 case MDB_PREV_NODUP:
6215 rc = mdb_cursor_prev(mc, key, data, op);
6218 rc = mdb_cursor_first(mc, key, data);
6221 mfunc = mdb_cursor_first;
6223 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6227 if (mc->mc_xcursor == NULL) {
6228 rc = MDB_INCOMPATIBLE;
6232 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6233 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6234 MDB_GET_KEY(leaf, key);
6235 rc = mdb_node_read(mc->mc_txn, leaf, data);
6239 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6243 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
6246 rc = mdb_cursor_last(mc, key, data);
6249 mfunc = mdb_cursor_last;
6252 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
6257 if (mc->mc_flags & C_DEL)
6258 mc->mc_flags ^= C_DEL;
6263 /** Touch all the pages in the cursor stack. Set mc_top.
6264 * Makes sure all the pages are writable, before attempting a write operation.
6265 * @param[in] mc The cursor to operate on.
6268 mdb_cursor_touch(MDB_cursor *mc)
6270 int rc = MDB_SUCCESS;
6272 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & DB_DIRTY)) {
6275 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6277 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
6278 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
6281 *mc->mc_dbflag |= DB_DIRTY;
6286 rc = mdb_page_touch(mc);
6287 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
6288 mc->mc_top = mc->mc_snum-1;
6293 /** Do not spill pages to disk if txn is getting full, may fail instead */
6294 #define MDB_NOSPILL 0x8000
6297 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6301 MDB_node *leaf = NULL;
6302 MDB_page *fp, *mp, *sub_root = NULL;
6304 MDB_val xdata, *rdata, dkey, olddata;
6306 int do_sub = 0, insert_key, insert_data;
6307 unsigned int mcount = 0, dcount = 0, nospill;
6310 unsigned int nflags;
6313 if (mc == NULL || key == NULL)
6316 env = mc->mc_txn->mt_env;
6318 /* Check this first so counter will always be zero on any
6321 if (flags & MDB_MULTIPLE) {
6322 dcount = data[1].mv_size;
6323 data[1].mv_size = 0;
6324 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
6325 return MDB_INCOMPATIBLE;
6328 nospill = flags & MDB_NOSPILL;
6329 flags &= ~MDB_NOSPILL;
6331 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6332 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6334 if (key->mv_size-1 >= ENV_MAXKEY(env))
6335 return MDB_BAD_VALSIZE;
6337 #if SIZE_MAX > MAXDATASIZE
6338 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
6339 return MDB_BAD_VALSIZE;
6341 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
6342 return MDB_BAD_VALSIZE;
6345 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
6346 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
6350 if (flags == MDB_CURRENT) {
6351 if (!(mc->mc_flags & C_INITIALIZED))
6354 } else if (mc->mc_db->md_root == P_INVALID) {
6355 /* new database, cursor has nothing to point to */
6358 mc->mc_flags &= ~C_INITIALIZED;
6363 if (flags & MDB_APPEND) {
6365 rc = mdb_cursor_last(mc, &k2, &d2);
6367 rc = mc->mc_dbx->md_cmp(key, &k2);
6370 mc->mc_ki[mc->mc_top]++;
6372 /* new key is <= last key */
6377 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6379 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6380 DPRINTF(("duplicate key [%s]", DKEY(key)));
6382 return MDB_KEYEXIST;
6384 if (rc && rc != MDB_NOTFOUND)
6388 if (mc->mc_flags & C_DEL)
6389 mc->mc_flags ^= C_DEL;
6391 /* Cursor is positioned, check for room in the dirty list */
6393 if (flags & MDB_MULTIPLE) {
6395 xdata.mv_size = data->mv_size * dcount;
6399 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6403 if (rc == MDB_NO_ROOT) {
6405 /* new database, write a root leaf page */
6406 DPUTS("allocating new root leaf page");
6407 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6410 mdb_cursor_push(mc, np);
6411 mc->mc_db->md_root = np->mp_pgno;
6412 mc->mc_db->md_depth++;
6413 *mc->mc_dbflag |= DB_DIRTY;
6414 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6416 np->mp_flags |= P_LEAF2;
6417 mc->mc_flags |= C_INITIALIZED;
6419 /* make sure all cursor pages are writable */
6420 rc2 = mdb_cursor_touch(mc);
6425 insert_key = insert_data = rc;
6427 /* The key does not exist */
6428 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6429 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6430 LEAFSIZE(key, data) > env->me_nodemax)
6432 /* Too big for a node, insert in sub-DB. Set up an empty
6433 * "old sub-page" for prep_subDB to expand to a full page.
6435 fp_flags = P_LEAF|P_DIRTY;
6437 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6438 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6439 olddata.mv_size = PAGEHDRSZ;
6443 /* there's only a key anyway, so this is a no-op */
6444 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6446 unsigned int ksize = mc->mc_db->md_pad;
6447 if (key->mv_size != ksize)
6448 return MDB_BAD_VALSIZE;
6449 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6450 memcpy(ptr, key->mv_data, ksize);
6452 /* if overwriting slot 0 of leaf, need to
6453 * update branch key if there is a parent page
6455 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6456 unsigned short dtop = 1;
6458 /* slot 0 is always an empty key, find real slot */
6459 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6463 if (mc->mc_ki[mc->mc_top])
6464 rc2 = mdb_update_key(mc, key);
6475 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6476 olddata.mv_size = NODEDSZ(leaf);
6477 olddata.mv_data = NODEDATA(leaf);
6480 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6481 /* Prepare (sub-)page/sub-DB to accept the new item,
6482 * if needed. fp: old sub-page or a header faking
6483 * it. mp: new (sub-)page. offset: growth in page
6484 * size. xdata: node data with new page or DB.
6486 unsigned i, offset = 0;
6487 mp = fp = xdata.mv_data = env->me_pbuf;
6488 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6490 /* Was a single item before, must convert now */
6491 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6493 /* Just overwrite the current item */
6494 if (flags == MDB_CURRENT)
6496 dcmp = mc->mc_dbx->md_dcmp;
6497 #if UINT_MAX < SIZE_MAX
6498 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6499 dcmp = mdb_cmp_clong;
6501 /* does data match? */
6502 if (!dcmp(data, &olddata)) {
6503 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
6504 return MDB_KEYEXIST;
6509 /* Back up original data item */
6510 dkey.mv_size = olddata.mv_size;
6511 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6513 /* Make sub-page header for the dup items, with dummy body */
6514 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6515 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6516 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6517 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6518 fp->mp_flags |= P_LEAF2;
6519 fp->mp_pad = data->mv_size;
6520 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6522 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6523 (dkey.mv_size & 1) + (data->mv_size & 1);
6525 fp->mp_upper = xdata.mv_size - PAGEBASE;
6526 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6527 } else if (leaf->mn_flags & F_SUBDATA) {
6528 /* Data is on sub-DB, just store it */
6529 flags |= F_DUPDATA|F_SUBDATA;
6532 /* Data is on sub-page */
6533 fp = olddata.mv_data;
6536 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6537 offset = EVEN(NODESIZE + sizeof(indx_t) +
6541 offset = fp->mp_pad;
6542 if (SIZELEFT(fp) < offset) {
6543 offset *= 4; /* space for 4 more */
6546 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6548 fp->mp_flags |= P_DIRTY;
6549 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6550 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6554 xdata.mv_size = olddata.mv_size + offset;
6557 fp_flags = fp->mp_flags;
6558 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6559 /* Too big for a sub-page, convert to sub-DB */
6560 fp_flags &= ~P_SUBP;
6562 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6563 fp_flags |= P_LEAF2;
6564 dummy.md_pad = fp->mp_pad;
6565 dummy.md_flags = MDB_DUPFIXED;
6566 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6567 dummy.md_flags |= MDB_INTEGERKEY;
6573 dummy.md_branch_pages = 0;
6574 dummy.md_leaf_pages = 1;
6575 dummy.md_overflow_pages = 0;
6576 dummy.md_entries = NUMKEYS(fp);
6577 xdata.mv_size = sizeof(MDB_db);
6578 xdata.mv_data = &dummy;
6579 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6581 offset = env->me_psize - olddata.mv_size;
6582 flags |= F_DUPDATA|F_SUBDATA;
6583 dummy.md_root = mp->mp_pgno;
6587 mp->mp_flags = fp_flags | P_DIRTY;
6588 mp->mp_pad = fp->mp_pad;
6589 mp->mp_lower = fp->mp_lower;
6590 mp->mp_upper = fp->mp_upper + offset;
6591 if (fp_flags & P_LEAF2) {
6592 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6594 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6595 olddata.mv_size - fp->mp_upper - PAGEBASE);
6596 for (i=0; i<NUMKEYS(fp); i++)
6597 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6605 mdb_node_del(mc, 0);
6609 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
6610 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
6611 return MDB_INCOMPATIBLE;
6612 /* overflow page overwrites need special handling */
6613 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6616 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6618 memcpy(&pg, olddata.mv_data, sizeof(pg));
6619 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6621 ovpages = omp->mp_pages;
6623 /* Is the ov page large enough? */
6624 if (ovpages >= dpages) {
6625 if (!(omp->mp_flags & P_DIRTY) &&
6626 (level || (env->me_flags & MDB_WRITEMAP)))
6628 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6631 level = 0; /* dirty in this txn or clean */
6634 if (omp->mp_flags & P_DIRTY) {
6635 /* yes, overwrite it. Note in this case we don't
6636 * bother to try shrinking the page if the new data
6637 * is smaller than the overflow threshold.
6640 /* It is writable only in a parent txn */
6641 size_t sz = (size_t) env->me_psize * ovpages, off;
6642 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6648 /* Note - this page is already counted in parent's dirty_room */
6649 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6650 mdb_cassert(mc, rc2 == 0);
6651 /* Currently we make the page look as with put() in the
6652 * parent txn, in case the user peeks at MDB_RESERVEd
6653 * or unused parts. Some users treat ovpages specially.
6655 if (!(flags & MDB_RESERVE)) {
6656 /* Skip the part where LMDB will put *data.
6657 * Copy end of page, adjusting alignment so
6658 * compiler may copy words instead of bytes.
6660 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6661 memcpy((size_t *)((char *)np + off),
6662 (size_t *)((char *)omp + off), sz - off);
6665 memcpy(np, omp, sz); /* Copy beginning of page */
6668 SETDSZ(leaf, data->mv_size);
6669 if (F_ISSET(flags, MDB_RESERVE))
6670 data->mv_data = METADATA(omp);
6672 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6676 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6678 } else if (data->mv_size == olddata.mv_size) {
6679 /* same size, just replace it. Note that we could
6680 * also reuse this node if the new data is smaller,
6681 * but instead we opt to shrink the node in that case.
6683 if (F_ISSET(flags, MDB_RESERVE))
6684 data->mv_data = olddata.mv_data;
6685 else if (!(mc->mc_flags & C_SUB))
6686 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6688 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6693 mdb_node_del(mc, 0);
6699 nflags = flags & NODE_ADD_FLAGS;
6700 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6701 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6702 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6703 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6705 nflags |= MDB_SPLIT_REPLACE;
6706 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6708 /* There is room already in this leaf page. */
6709 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6711 /* Adjust other cursors pointing to mp */
6712 MDB_cursor *m2, *m3;
6713 MDB_dbi dbi = mc->mc_dbi;
6714 unsigned i = mc->mc_top;
6715 MDB_page *mp = mc->mc_pg[i];
6717 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6718 if (mc->mc_flags & C_SUB)
6719 m3 = &m2->mc_xcursor->mx_cursor;
6722 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
6723 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
6726 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6727 MDB_node *n2 = NODEPTR(mp, m3->mc_ki[i]);
6728 if ((n2->mn_flags & (F_SUBDATA|F_DUPDATA)) == F_DUPDATA)
6729 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
6735 if (rc == MDB_SUCCESS) {
6736 /* Now store the actual data in the child DB. Note that we're
6737 * storing the user data in the keys field, so there are strict
6738 * size limits on dupdata. The actual data fields of the child
6739 * DB are all zero size.
6742 int xflags, new_dupdata;
6747 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6748 if (flags & MDB_CURRENT) {
6749 xflags = MDB_CURRENT|MDB_NOSPILL;
6751 mdb_xcursor_init1(mc, leaf);
6752 xflags = (flags & MDB_NODUPDATA) ?
6753 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6756 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
6757 new_dupdata = (int)dkey.mv_size;
6758 /* converted, write the original data first */
6760 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6763 /* we've done our job */
6766 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
6767 /* Adjust other cursors pointing to mp */
6769 MDB_xcursor *mx = mc->mc_xcursor;
6770 unsigned i = mc->mc_top;
6771 MDB_page *mp = mc->mc_pg[i];
6772 int nkeys = NUMKEYS(mp);
6774 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6775 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6776 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6777 if (m2->mc_pg[i] == mp) {
6778 if (m2->mc_ki[i] == mc->mc_ki[i]) {
6779 mdb_xcursor_init2(m2, mx, new_dupdata);
6780 } else if (!insert_key && m2->mc_ki[i] < nkeys) {
6781 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[i]);
6782 if ((n2->mn_flags & (F_SUBDATA|F_DUPDATA)) == F_DUPDATA)
6783 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
6788 ecount = mc->mc_xcursor->mx_db.md_entries;
6789 if (flags & MDB_APPENDDUP)
6790 xflags |= MDB_APPEND;
6791 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6792 if (flags & F_SUBDATA) {
6793 void *db = NODEDATA(leaf);
6794 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6796 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6798 /* Increment count unless we just replaced an existing item. */
6800 mc->mc_db->md_entries++;
6802 /* Invalidate txn if we created an empty sub-DB */
6805 /* If we succeeded and the key didn't exist before,
6806 * make sure the cursor is marked valid.
6808 mc->mc_flags |= C_INITIALIZED;
6810 if (flags & MDB_MULTIPLE) {
6813 /* let caller know how many succeeded, if any */
6814 data[1].mv_size = mcount;
6815 if (mcount < dcount) {
6816 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6817 insert_key = insert_data = 0;
6824 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6827 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6832 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6838 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6839 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6841 if (!(mc->mc_flags & C_INITIALIZED))
6844 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6845 return MDB_NOTFOUND;
6847 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6850 rc = mdb_cursor_touch(mc);
6854 mp = mc->mc_pg[mc->mc_top];
6857 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6859 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6860 if (flags & MDB_NODUPDATA) {
6861 /* mdb_cursor_del0() will subtract the final entry */
6862 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6863 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
6865 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6866 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6868 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6871 /* If sub-DB still has entries, we're done */
6872 if (mc->mc_xcursor->mx_db.md_entries) {
6873 if (leaf->mn_flags & F_SUBDATA) {
6874 /* update subDB info */
6875 void *db = NODEDATA(leaf);
6876 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6879 /* shrink fake page */
6880 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6881 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6882 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6883 /* fix other sub-DB cursors pointed at fake pages on this page */
6884 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6885 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6886 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6887 if (m2->mc_pg[mc->mc_top] == mp) {
6888 if (m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top]) {
6889 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6891 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
6892 if (!(n2->mn_flags & F_SUBDATA))
6893 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
6898 mc->mc_db->md_entries--;
6901 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
6903 /* otherwise fall thru and delete the sub-DB */
6906 if (leaf->mn_flags & F_SUBDATA) {
6907 /* add all the child DB's pages to the free list */
6908 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6913 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
6914 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
6915 rc = MDB_INCOMPATIBLE;
6919 /* add overflow pages to free list */
6920 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6924 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6925 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6926 (rc = mdb_ovpage_free(mc, omp)))
6931 return mdb_cursor_del0(mc);
6934 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6938 /** Allocate and initialize new pages for a database.
6939 * @param[in] mc a cursor on the database being added to.
6940 * @param[in] flags flags defining what type of page is being allocated.
6941 * @param[in] num the number of pages to allocate. This is usually 1,
6942 * unless allocating overflow pages for a large record.
6943 * @param[out] mp Address of a page, or NULL on failure.
6944 * @return 0 on success, non-zero on failure.
6947 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6952 if ((rc = mdb_page_alloc(mc, num, &np)))
6954 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6955 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6956 np->mp_flags = flags | P_DIRTY;
6957 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
6958 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
6961 mc->mc_db->md_branch_pages++;
6962 else if (IS_LEAF(np))
6963 mc->mc_db->md_leaf_pages++;
6964 else if (IS_OVERFLOW(np)) {
6965 mc->mc_db->md_overflow_pages += num;
6973 /** Calculate the size of a leaf node.
6974 * The size depends on the environment's page size; if a data item
6975 * is too large it will be put onto an overflow page and the node
6976 * size will only include the key and not the data. Sizes are always
6977 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6978 * of the #MDB_node headers.
6979 * @param[in] env The environment handle.
6980 * @param[in] key The key for the node.
6981 * @param[in] data The data for the node.
6982 * @return The number of bytes needed to store the node.
6985 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6989 sz = LEAFSIZE(key, data);
6990 if (sz > env->me_nodemax) {
6991 /* put on overflow page */
6992 sz -= data->mv_size - sizeof(pgno_t);
6995 return EVEN(sz + sizeof(indx_t));
6998 /** Calculate the size of a branch node.
6999 * The size should depend on the environment's page size but since
7000 * we currently don't support spilling large keys onto overflow
7001 * pages, it's simply the size of the #MDB_node header plus the
7002 * size of the key. Sizes are always rounded up to an even number
7003 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7004 * @param[in] env The environment handle.
7005 * @param[in] key The key for the node.
7006 * @return The number of bytes needed to store the node.
7009 mdb_branch_size(MDB_env *env, MDB_val *key)
7014 if (sz > env->me_nodemax) {
7015 /* put on overflow page */
7016 /* not implemented */
7017 /* sz -= key->size - sizeof(pgno_t); */
7020 return sz + sizeof(indx_t);
7023 /** Add a node to the page pointed to by the cursor.
7024 * @param[in] mc The cursor for this operation.
7025 * @param[in] indx The index on the page where the new node should be added.
7026 * @param[in] key The key for the new node.
7027 * @param[in] data The data for the new node, if any.
7028 * @param[in] pgno The page number, if adding a branch node.
7029 * @param[in] flags Flags for the node.
7030 * @return 0 on success, non-zero on failure. Possible errors are:
7032 * <li>ENOMEM - failed to allocate overflow pages for the node.
7033 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
7034 * should never happen since all callers already calculate the
7035 * page's free space before calling this function.
7039 mdb_node_add(MDB_cursor *mc, indx_t indx,
7040 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
7043 size_t node_size = NODESIZE;
7047 MDB_page *mp = mc->mc_pg[mc->mc_top];
7048 MDB_page *ofp = NULL; /* overflow page */
7052 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
7054 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
7055 IS_LEAF(mp) ? "leaf" : "branch",
7056 IS_SUBP(mp) ? "sub-" : "",
7057 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
7058 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
7061 /* Move higher keys up one slot. */
7062 int ksize = mc->mc_db->md_pad, dif;
7063 char *ptr = LEAF2KEY(mp, indx, ksize);
7064 dif = NUMKEYS(mp) - indx;
7066 memmove(ptr+ksize, ptr, dif*ksize);
7067 /* insert new key */
7068 memcpy(ptr, key->mv_data, ksize);
7070 /* Just using these for counting */
7071 mp->mp_lower += sizeof(indx_t);
7072 mp->mp_upper -= ksize - sizeof(indx_t);
7076 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
7078 node_size += key->mv_size;
7080 mdb_cassert(mc, key && data);
7081 if (F_ISSET(flags, F_BIGDATA)) {
7082 /* Data already on overflow page. */
7083 node_size += sizeof(pgno_t);
7084 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
7085 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
7087 /* Put data on overflow page. */
7088 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
7089 data->mv_size, node_size+data->mv_size));
7090 node_size = EVEN(node_size + sizeof(pgno_t));
7091 if ((ssize_t)node_size > room)
7093 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
7095 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
7099 node_size += data->mv_size;
7102 node_size = EVEN(node_size);
7103 if ((ssize_t)node_size > room)
7107 /* Move higher pointers up one slot. */
7108 for (i = NUMKEYS(mp); i > indx; i--)
7109 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
7111 /* Adjust free space offsets. */
7112 ofs = mp->mp_upper - node_size;
7113 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
7114 mp->mp_ptrs[indx] = ofs;
7116 mp->mp_lower += sizeof(indx_t);
7118 /* Write the node data. */
7119 node = NODEPTR(mp, indx);
7120 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
7121 node->mn_flags = flags;
7123 SETDSZ(node,data->mv_size);
7128 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7131 ndata = NODEDATA(node);
7133 if (F_ISSET(flags, F_BIGDATA))
7134 memcpy(ndata, data->mv_data, sizeof(pgno_t));
7135 else if (F_ISSET(flags, MDB_RESERVE))
7136 data->mv_data = ndata;
7138 memcpy(ndata, data->mv_data, data->mv_size);
7140 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
7141 ndata = METADATA(ofp);
7142 if (F_ISSET(flags, MDB_RESERVE))
7143 data->mv_data = ndata;
7145 memcpy(ndata, data->mv_data, data->mv_size);
7152 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
7153 mdb_dbg_pgno(mp), NUMKEYS(mp)));
7154 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
7155 DPRINTF(("node size = %"Z"u", node_size));
7156 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7157 return MDB_PAGE_FULL;
7160 /** Delete the specified node from a page.
7161 * @param[in] mc Cursor pointing to the node to delete.
7162 * @param[in] ksize The size of a node. Only used if the page is
7163 * part of a #MDB_DUPFIXED database.
7166 mdb_node_del(MDB_cursor *mc, int ksize)
7168 MDB_page *mp = mc->mc_pg[mc->mc_top];
7169 indx_t indx = mc->mc_ki[mc->mc_top];
7171 indx_t i, j, numkeys, ptr;
7175 DPRINTF(("delete node %u on %s page %"Z"u", indx,
7176 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
7177 numkeys = NUMKEYS(mp);
7178 mdb_cassert(mc, indx < numkeys);
7181 int x = numkeys - 1 - indx;
7182 base = LEAF2KEY(mp, indx, ksize);
7184 memmove(base, base + ksize, x * ksize);
7185 mp->mp_lower -= sizeof(indx_t);
7186 mp->mp_upper += ksize - sizeof(indx_t);
7190 node = NODEPTR(mp, indx);
7191 sz = NODESIZE + node->mn_ksize;
7193 if (F_ISSET(node->mn_flags, F_BIGDATA))
7194 sz += sizeof(pgno_t);
7196 sz += NODEDSZ(node);
7200 ptr = mp->mp_ptrs[indx];
7201 for (i = j = 0; i < numkeys; i++) {
7203 mp->mp_ptrs[j] = mp->mp_ptrs[i];
7204 if (mp->mp_ptrs[i] < ptr)
7205 mp->mp_ptrs[j] += sz;
7210 base = (char *)mp + mp->mp_upper + PAGEBASE;
7211 memmove(base + sz, base, ptr - mp->mp_upper);
7213 mp->mp_lower -= sizeof(indx_t);
7217 /** Compact the main page after deleting a node on a subpage.
7218 * @param[in] mp The main page to operate on.
7219 * @param[in] indx The index of the subpage on the main page.
7222 mdb_node_shrink(MDB_page *mp, indx_t indx)
7227 indx_t delta, nsize, len, ptr;
7230 node = NODEPTR(mp, indx);
7231 sp = (MDB_page *)NODEDATA(node);
7232 delta = SIZELEFT(sp);
7233 nsize = NODEDSZ(node) - delta;
7235 /* Prepare to shift upward, set len = length(subpage part to shift) */
7239 return; /* do not make the node uneven-sized */
7241 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
7242 for (i = NUMKEYS(sp); --i >= 0; )
7243 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
7246 sp->mp_upper = sp->mp_lower;
7247 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
7248 SETDSZ(node, nsize);
7250 /* Shift <lower nodes...initial part of subpage> upward */
7251 base = (char *)mp + mp->mp_upper + PAGEBASE;
7252 memmove(base + delta, base, (char *)sp + len - base);
7254 ptr = mp->mp_ptrs[indx];
7255 for (i = NUMKEYS(mp); --i >= 0; ) {
7256 if (mp->mp_ptrs[i] <= ptr)
7257 mp->mp_ptrs[i] += delta;
7259 mp->mp_upper += delta;
7262 /** Initial setup of a sorted-dups cursor.
7263 * Sorted duplicates are implemented as a sub-database for the given key.
7264 * The duplicate data items are actually keys of the sub-database.
7265 * Operations on the duplicate data items are performed using a sub-cursor
7266 * initialized when the sub-database is first accessed. This function does
7267 * the preliminary setup of the sub-cursor, filling in the fields that
7268 * depend only on the parent DB.
7269 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7272 mdb_xcursor_init0(MDB_cursor *mc)
7274 MDB_xcursor *mx = mc->mc_xcursor;
7276 mx->mx_cursor.mc_xcursor = NULL;
7277 mx->mx_cursor.mc_txn = mc->mc_txn;
7278 mx->mx_cursor.mc_db = &mx->mx_db;
7279 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
7280 mx->mx_cursor.mc_dbi = mc->mc_dbi;
7281 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
7282 mx->mx_cursor.mc_snum = 0;
7283 mx->mx_cursor.mc_top = 0;
7284 mx->mx_cursor.mc_flags = C_SUB;
7285 mx->mx_dbx.md_name.mv_size = 0;
7286 mx->mx_dbx.md_name.mv_data = NULL;
7287 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
7288 mx->mx_dbx.md_dcmp = NULL;
7289 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
7292 /** Final setup of a sorted-dups cursor.
7293 * Sets up the fields that depend on the data from the main cursor.
7294 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7295 * @param[in] node The data containing the #MDB_db record for the
7296 * sorted-dup database.
7299 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
7301 MDB_xcursor *mx = mc->mc_xcursor;
7303 if (node->mn_flags & F_SUBDATA) {
7304 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
7305 mx->mx_cursor.mc_pg[0] = 0;
7306 mx->mx_cursor.mc_snum = 0;
7307 mx->mx_cursor.mc_top = 0;
7308 mx->mx_cursor.mc_flags = C_SUB;
7310 MDB_page *fp = NODEDATA(node);
7311 mx->mx_db.md_pad = 0;
7312 mx->mx_db.md_flags = 0;
7313 mx->mx_db.md_depth = 1;
7314 mx->mx_db.md_branch_pages = 0;
7315 mx->mx_db.md_leaf_pages = 1;
7316 mx->mx_db.md_overflow_pages = 0;
7317 mx->mx_db.md_entries = NUMKEYS(fp);
7318 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
7319 mx->mx_cursor.mc_snum = 1;
7320 mx->mx_cursor.mc_top = 0;
7321 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
7322 mx->mx_cursor.mc_pg[0] = fp;
7323 mx->mx_cursor.mc_ki[0] = 0;
7324 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7325 mx->mx_db.md_flags = MDB_DUPFIXED;
7326 mx->mx_db.md_pad = fp->mp_pad;
7327 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7328 mx->mx_db.md_flags |= MDB_INTEGERKEY;
7331 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7332 mx->mx_db.md_root));
7333 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
7334 #if UINT_MAX < SIZE_MAX
7335 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
7336 mx->mx_dbx.md_cmp = mdb_cmp_clong;
7341 /** Fixup a sorted-dups cursor due to underlying update.
7342 * Sets up some fields that depend on the data from the main cursor.
7343 * Almost the same as init1, but skips initialization steps if the
7344 * xcursor had already been used.
7345 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
7346 * @param[in] src_mx The xcursor of an up-to-date cursor.
7347 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
7350 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
7352 MDB_xcursor *mx = mc->mc_xcursor;
7355 mx->mx_cursor.mc_snum = 1;
7356 mx->mx_cursor.mc_top = 0;
7357 mx->mx_cursor.mc_flags |= C_INITIALIZED;
7358 mx->mx_cursor.mc_ki[0] = 0;
7359 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
7360 #if UINT_MAX < SIZE_MAX
7361 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
7363 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
7366 mx->mx_db = src_mx->mx_db;
7367 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
7368 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7369 mx->mx_db.md_root));
7372 /** Initialize a cursor for a given transaction and database. */
7374 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
7377 mc->mc_backup = NULL;
7380 mc->mc_db = &txn->mt_dbs[dbi];
7381 mc->mc_dbx = &txn->mt_dbxs[dbi];
7382 mc->mc_dbflag = &txn->mt_dbflags[dbi];
7388 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
7389 mdb_tassert(txn, mx != NULL);
7390 mc->mc_xcursor = mx;
7391 mdb_xcursor_init0(mc);
7393 mc->mc_xcursor = NULL;
7395 if (*mc->mc_dbflag & DB_STALE) {
7396 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
7401 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
7404 size_t size = sizeof(MDB_cursor);
7406 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
7409 if (txn->mt_flags & MDB_TXN_BLOCKED)
7412 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7415 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
7416 size += sizeof(MDB_xcursor);
7418 if ((mc = malloc(size)) != NULL) {
7419 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
7420 if (txn->mt_cursors) {
7421 mc->mc_next = txn->mt_cursors[dbi];
7422 txn->mt_cursors[dbi] = mc;
7423 mc->mc_flags |= C_UNTRACK;
7435 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
7437 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
7440 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
7443 if (txn->mt_flags & MDB_TXN_BLOCKED)
7446 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
7450 /* Return the count of duplicate data items for the current key */
7452 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7456 if (mc == NULL || countp == NULL)
7459 if (mc->mc_xcursor == NULL)
7460 return MDB_INCOMPATIBLE;
7462 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
7465 if (!(mc->mc_flags & C_INITIALIZED))
7468 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
7469 return MDB_NOTFOUND;
7471 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7472 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7475 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7478 *countp = mc->mc_xcursor->mx_db.md_entries;
7484 mdb_cursor_close(MDB_cursor *mc)
7486 if (mc && !mc->mc_backup) {
7487 /* remove from txn, if tracked */
7488 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7489 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7490 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7492 *prev = mc->mc_next;
7499 mdb_cursor_txn(MDB_cursor *mc)
7501 if (!mc) return NULL;
7506 mdb_cursor_dbi(MDB_cursor *mc)
7511 /** Replace the key for a branch node with a new key.
7512 * @param[in] mc Cursor pointing to the node to operate on.
7513 * @param[in] key The new key to use.
7514 * @return 0 on success, non-zero on failure.
7517 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7523 int delta, ksize, oksize;
7524 indx_t ptr, i, numkeys, indx;
7527 indx = mc->mc_ki[mc->mc_top];
7528 mp = mc->mc_pg[mc->mc_top];
7529 node = NODEPTR(mp, indx);
7530 ptr = mp->mp_ptrs[indx];
7534 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7535 k2.mv_data = NODEKEY(node);
7536 k2.mv_size = node->mn_ksize;
7537 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7539 mdb_dkey(&k2, kbuf2),
7545 /* Sizes must be 2-byte aligned. */
7546 ksize = EVEN(key->mv_size);
7547 oksize = EVEN(node->mn_ksize);
7548 delta = ksize - oksize;
7550 /* Shift node contents if EVEN(key length) changed. */
7552 if (delta > 0 && SIZELEFT(mp) < delta) {
7554 /* not enough space left, do a delete and split */
7555 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7556 pgno = NODEPGNO(node);
7557 mdb_node_del(mc, 0);
7558 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7561 numkeys = NUMKEYS(mp);
7562 for (i = 0; i < numkeys; i++) {
7563 if (mp->mp_ptrs[i] <= ptr)
7564 mp->mp_ptrs[i] -= delta;
7567 base = (char *)mp + mp->mp_upper + PAGEBASE;
7568 len = ptr - mp->mp_upper + NODESIZE;
7569 memmove(base - delta, base, len);
7570 mp->mp_upper -= delta;
7572 node = NODEPTR(mp, indx);
7575 /* But even if no shift was needed, update ksize */
7576 if (node->mn_ksize != key->mv_size)
7577 node->mn_ksize = key->mv_size;
7580 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7586 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7588 /** Perform \b act while tracking temporary cursor \b mn */
7589 #define WITH_CURSOR_TRACKING(mn, act) do { \
7590 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
7591 if ((mn).mc_flags & C_SUB) { \
7592 dummy.mc_flags = C_INITIALIZED; \
7593 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
7598 tracked->mc_next = *tp; \
7601 *tp = tracked->mc_next; \
7604 /** Move a node from csrc to cdst.
7607 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
7614 unsigned short flags;
7618 /* Mark src and dst as dirty. */
7619 if ((rc = mdb_page_touch(csrc)) ||
7620 (rc = mdb_page_touch(cdst)))
7623 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7624 key.mv_size = csrc->mc_db->md_pad;
7625 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7627 data.mv_data = NULL;
7631 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7632 mdb_cassert(csrc, !((size_t)srcnode & 1));
7633 srcpg = NODEPGNO(srcnode);
7634 flags = srcnode->mn_flags;
7635 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7636 unsigned int snum = csrc->mc_snum;
7638 /* must find the lowest key below src */
7639 rc = mdb_page_search_lowest(csrc);
7642 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7643 key.mv_size = csrc->mc_db->md_pad;
7644 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7646 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7647 key.mv_size = NODEKSZ(s2);
7648 key.mv_data = NODEKEY(s2);
7650 csrc->mc_snum = snum--;
7651 csrc->mc_top = snum;
7653 key.mv_size = NODEKSZ(srcnode);
7654 key.mv_data = NODEKEY(srcnode);
7656 data.mv_size = NODEDSZ(srcnode);
7657 data.mv_data = NODEDATA(srcnode);
7659 mn.mc_xcursor = NULL;
7660 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7661 unsigned int snum = cdst->mc_snum;
7664 /* must find the lowest key below dst */
7665 mdb_cursor_copy(cdst, &mn);
7666 rc = mdb_page_search_lowest(&mn);
7669 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7670 bkey.mv_size = mn.mc_db->md_pad;
7671 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7673 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7674 bkey.mv_size = NODEKSZ(s2);
7675 bkey.mv_data = NODEKEY(s2);
7677 mn.mc_snum = snum--;
7680 rc = mdb_update_key(&mn, &bkey);
7685 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7686 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7687 csrc->mc_ki[csrc->mc_top],
7689 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7690 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7692 /* Add the node to the destination page.
7694 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7695 if (rc != MDB_SUCCESS)
7698 /* Delete the node from the source page.
7700 mdb_node_del(csrc, key.mv_size);
7703 /* Adjust other cursors pointing to mp */
7704 MDB_cursor *m2, *m3;
7705 MDB_dbi dbi = csrc->mc_dbi;
7706 MDB_page *mpd, *mps;
7708 mps = csrc->mc_pg[csrc->mc_top];
7709 /* If we're adding on the left, bump others up */
7711 mpd = cdst->mc_pg[csrc->mc_top];
7712 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7713 if (csrc->mc_flags & C_SUB)
7714 m3 = &m2->mc_xcursor->mx_cursor;
7717 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
7720 m3->mc_pg[csrc->mc_top] == mpd &&
7721 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
7722 m3->mc_ki[csrc->mc_top]++;
7725 m3->mc_pg[csrc->mc_top] == mps &&
7726 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
7727 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7728 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7729 m3->mc_ki[csrc->mc_top-1]++;
7731 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
7733 MDB_node *node = NODEPTR(m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
7734 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
7735 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
7739 /* Adding on the right, bump others down */
7741 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7742 if (csrc->mc_flags & C_SUB)
7743 m3 = &m2->mc_xcursor->mx_cursor;
7746 if (m3 == csrc) continue;
7747 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
7749 if (m3->mc_pg[csrc->mc_top] == mps) {
7750 if (!m3->mc_ki[csrc->mc_top]) {
7751 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7752 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7753 m3->mc_ki[csrc->mc_top-1]--;
7755 m3->mc_ki[csrc->mc_top]--;
7757 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
7759 MDB_node *node = NODEPTR(m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
7760 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
7761 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
7768 /* Update the parent separators.
7770 if (csrc->mc_ki[csrc->mc_top] == 0) {
7771 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7772 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7773 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7775 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7776 key.mv_size = NODEKSZ(srcnode);
7777 key.mv_data = NODEKEY(srcnode);
7779 DPRINTF(("update separator for source page %"Z"u to [%s]",
7780 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7781 mdb_cursor_copy(csrc, &mn);
7784 /* We want mdb_rebalance to find mn when doing fixups */
7785 WITH_CURSOR_TRACKING(mn,
7786 rc = mdb_update_key(&mn, &key));
7790 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7792 indx_t ix = csrc->mc_ki[csrc->mc_top];
7793 nullkey.mv_size = 0;
7794 csrc->mc_ki[csrc->mc_top] = 0;
7795 rc = mdb_update_key(csrc, &nullkey);
7796 csrc->mc_ki[csrc->mc_top] = ix;
7797 mdb_cassert(csrc, rc == MDB_SUCCESS);
7801 if (cdst->mc_ki[cdst->mc_top] == 0) {
7802 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7803 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7804 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7806 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7807 key.mv_size = NODEKSZ(srcnode);
7808 key.mv_data = NODEKEY(srcnode);
7810 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7811 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7812 mdb_cursor_copy(cdst, &mn);
7815 /* We want mdb_rebalance to find mn when doing fixups */
7816 WITH_CURSOR_TRACKING(mn,
7817 rc = mdb_update_key(&mn, &key));
7821 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7823 indx_t ix = cdst->mc_ki[cdst->mc_top];
7824 nullkey.mv_size = 0;
7825 cdst->mc_ki[cdst->mc_top] = 0;
7826 rc = mdb_update_key(cdst, &nullkey);
7827 cdst->mc_ki[cdst->mc_top] = ix;
7828 mdb_cassert(cdst, rc == MDB_SUCCESS);
7835 /** Merge one page into another.
7836 * The nodes from the page pointed to by \b csrc will
7837 * be copied to the page pointed to by \b cdst and then
7838 * the \b csrc page will be freed.
7839 * @param[in] csrc Cursor pointing to the source page.
7840 * @param[in] cdst Cursor pointing to the destination page.
7841 * @return 0 on success, non-zero on failure.
7844 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7846 MDB_page *psrc, *pdst;
7853 psrc = csrc->mc_pg[csrc->mc_top];
7854 pdst = cdst->mc_pg[cdst->mc_top];
7856 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7858 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7859 mdb_cassert(csrc, cdst->mc_snum > 1);
7861 /* Mark dst as dirty. */
7862 if ((rc = mdb_page_touch(cdst)))
7865 /* get dst page again now that we've touched it. */
7866 pdst = cdst->mc_pg[cdst->mc_top];
7868 /* Move all nodes from src to dst.
7870 j = nkeys = NUMKEYS(pdst);
7871 if (IS_LEAF2(psrc)) {
7872 key.mv_size = csrc->mc_db->md_pad;
7873 key.mv_data = METADATA(psrc);
7874 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7875 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7876 if (rc != MDB_SUCCESS)
7878 key.mv_data = (char *)key.mv_data + key.mv_size;
7881 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7882 srcnode = NODEPTR(psrc, i);
7883 if (i == 0 && IS_BRANCH(psrc)) {
7886 mdb_cursor_copy(csrc, &mn);
7887 mn.mc_xcursor = NULL;
7888 /* must find the lowest key below src */
7889 rc = mdb_page_search_lowest(&mn);
7892 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7893 key.mv_size = mn.mc_db->md_pad;
7894 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7896 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7897 key.mv_size = NODEKSZ(s2);
7898 key.mv_data = NODEKEY(s2);
7901 key.mv_size = srcnode->mn_ksize;
7902 key.mv_data = NODEKEY(srcnode);
7905 data.mv_size = NODEDSZ(srcnode);
7906 data.mv_data = NODEDATA(srcnode);
7907 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7908 if (rc != MDB_SUCCESS)
7913 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7914 pdst->mp_pgno, NUMKEYS(pdst),
7915 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7917 /* Unlink the src page from parent and add to free list.
7920 mdb_node_del(csrc, 0);
7921 if (csrc->mc_ki[csrc->mc_top] == 0) {
7923 rc = mdb_update_key(csrc, &key);
7931 psrc = csrc->mc_pg[csrc->mc_top];
7932 /* If not operating on FreeDB, allow this page to be reused
7933 * in this txn. Otherwise just add to free list.
7935 rc = mdb_page_loose(csrc, psrc);
7939 csrc->mc_db->md_leaf_pages--;
7941 csrc->mc_db->md_branch_pages--;
7943 /* Adjust other cursors pointing to mp */
7944 MDB_cursor *m2, *m3;
7945 MDB_dbi dbi = csrc->mc_dbi;
7946 unsigned int top = csrc->mc_top;
7948 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7949 if (csrc->mc_flags & C_SUB)
7950 m3 = &m2->mc_xcursor->mx_cursor;
7953 if (m3 == csrc) continue;
7954 if (m3->mc_snum < csrc->mc_snum) continue;
7955 if (m3->mc_pg[top] == psrc) {
7956 m3->mc_pg[top] = pdst;
7957 m3->mc_ki[top] += nkeys;
7958 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
7959 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
7960 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
7963 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
7965 MDB_node *node = NODEPTR(m3->mc_pg[top], m3->mc_ki[top]);
7966 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
7967 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
7972 unsigned int snum = cdst->mc_snum;
7973 uint16_t depth = cdst->mc_db->md_depth;
7974 mdb_cursor_pop(cdst);
7975 rc = mdb_rebalance(cdst);
7976 /* Did the tree height change? */
7977 if (depth != cdst->mc_db->md_depth)
7978 snum += cdst->mc_db->md_depth - depth;
7979 cdst->mc_snum = snum;
7980 cdst->mc_top = snum-1;
7985 /** Copy the contents of a cursor.
7986 * @param[in] csrc The cursor to copy from.
7987 * @param[out] cdst The cursor to copy to.
7990 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7994 cdst->mc_txn = csrc->mc_txn;
7995 cdst->mc_dbi = csrc->mc_dbi;
7996 cdst->mc_db = csrc->mc_db;
7997 cdst->mc_dbx = csrc->mc_dbx;
7998 cdst->mc_snum = csrc->mc_snum;
7999 cdst->mc_top = csrc->mc_top;
8000 cdst->mc_flags = csrc->mc_flags;
8002 for (i=0; i<csrc->mc_snum; i++) {
8003 cdst->mc_pg[i] = csrc->mc_pg[i];
8004 cdst->mc_ki[i] = csrc->mc_ki[i];
8008 /** Rebalance the tree after a delete operation.
8009 * @param[in] mc Cursor pointing to the page where rebalancing
8011 * @return 0 on success, non-zero on failure.
8014 mdb_rebalance(MDB_cursor *mc)
8018 unsigned int ptop, minkeys, thresh;
8022 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
8027 thresh = FILL_THRESHOLD;
8029 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
8030 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
8031 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
8032 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
8034 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
8035 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
8036 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
8037 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
8041 if (mc->mc_snum < 2) {
8042 MDB_page *mp = mc->mc_pg[0];
8044 DPUTS("Can't rebalance a subpage, ignoring");
8047 if (NUMKEYS(mp) == 0) {
8048 DPUTS("tree is completely empty");
8049 mc->mc_db->md_root = P_INVALID;
8050 mc->mc_db->md_depth = 0;
8051 mc->mc_db->md_leaf_pages = 0;
8052 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8055 /* Adjust cursors pointing to mp */
8058 mc->mc_flags &= ~C_INITIALIZED;
8060 MDB_cursor *m2, *m3;
8061 MDB_dbi dbi = mc->mc_dbi;
8063 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8064 if (mc->mc_flags & C_SUB)
8065 m3 = &m2->mc_xcursor->mx_cursor;
8068 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
8070 if (m3->mc_pg[0] == mp) {
8073 m3->mc_flags &= ~C_INITIALIZED;
8077 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
8079 DPUTS("collapsing root page!");
8080 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8083 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
8084 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
8087 mc->mc_db->md_depth--;
8088 mc->mc_db->md_branch_pages--;
8089 mc->mc_ki[0] = mc->mc_ki[1];
8090 for (i = 1; i<mc->mc_db->md_depth; i++) {
8091 mc->mc_pg[i] = mc->mc_pg[i+1];
8092 mc->mc_ki[i] = mc->mc_ki[i+1];
8095 /* Adjust other cursors pointing to mp */
8096 MDB_cursor *m2, *m3;
8097 MDB_dbi dbi = mc->mc_dbi;
8099 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8100 if (mc->mc_flags & C_SUB)
8101 m3 = &m2->mc_xcursor->mx_cursor;
8104 if (m3 == mc) continue;
8105 if (!(m3->mc_flags & C_INITIALIZED))
8107 if (m3->mc_pg[0] == mp) {
8108 for (i=0; i<mc->mc_db->md_depth; i++) {
8109 m3->mc_pg[i] = m3->mc_pg[i+1];
8110 m3->mc_ki[i] = m3->mc_ki[i+1];
8118 DPUTS("root page doesn't need rebalancing");
8122 /* The parent (branch page) must have at least 2 pointers,
8123 * otherwise the tree is invalid.
8125 ptop = mc->mc_top-1;
8126 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
8128 /* Leaf page fill factor is below the threshold.
8129 * Try to move keys from left or right neighbor, or
8130 * merge with a neighbor page.
8135 mdb_cursor_copy(mc, &mn);
8136 mn.mc_xcursor = NULL;
8138 oldki = mc->mc_ki[mc->mc_top];
8139 if (mc->mc_ki[ptop] == 0) {
8140 /* We're the leftmost leaf in our parent.
8142 DPUTS("reading right neighbor");
8144 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8145 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
8148 mn.mc_ki[mn.mc_top] = 0;
8149 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
8152 /* There is at least one neighbor to the left.
8154 DPUTS("reading left neighbor");
8156 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8157 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
8160 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
8161 mc->mc_ki[mc->mc_top] = 0;
8165 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
8166 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
8167 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
8169 /* If the neighbor page is above threshold and has enough keys,
8170 * move one key from it. Otherwise we should try to merge them.
8171 * (A branch page must never have less than 2 keys.)
8173 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
8174 rc = mdb_node_move(&mn, mc, fromleft);
8176 /* if we inserted on left, bump position up */
8181 rc = mdb_page_merge(&mn, mc);
8183 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
8184 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
8185 /* We want mdb_rebalance to find mn when doing fixups */
8186 WITH_CURSOR_TRACKING(mn,
8187 rc = mdb_page_merge(mc, &mn));
8188 mdb_cursor_copy(&mn, mc);
8190 mc->mc_flags &= ~C_EOF;
8192 mc->mc_ki[mc->mc_top] = oldki;
8196 /** Complete a delete operation started by #mdb_cursor_del(). */
8198 mdb_cursor_del0(MDB_cursor *mc)
8204 MDB_cursor *m2, *m3;
8205 MDB_dbi dbi = mc->mc_dbi;
8207 ki = mc->mc_ki[mc->mc_top];
8208 mp = mc->mc_pg[mc->mc_top];
8209 mdb_node_del(mc, mc->mc_db->md_pad);
8210 mc->mc_db->md_entries--;
8212 /* Adjust other cursors pointing to mp */
8213 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8214 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8215 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8217 if (m3 == mc || m3->mc_snum < mc->mc_snum)
8219 if (m3->mc_pg[mc->mc_top] == mp) {
8220 if (m3->mc_ki[mc->mc_top] == ki) {
8221 m3->mc_flags |= C_DEL;
8222 } else if (m3->mc_ki[mc->mc_top] > ki) {
8223 m3->mc_ki[mc->mc_top]--;
8225 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
8226 MDB_node *node = NODEPTR(m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
8227 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8228 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8233 rc = mdb_rebalance(mc);
8235 if (rc == MDB_SUCCESS) {
8236 /* DB is totally empty now, just bail out.
8237 * Other cursors adjustments were already done
8238 * by mdb_rebalance and aren't needed here.
8243 mp = mc->mc_pg[mc->mc_top];
8244 nkeys = NUMKEYS(mp);
8246 /* Adjust other cursors pointing to mp */
8247 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
8248 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8249 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8251 if (m3->mc_snum < mc->mc_snum)
8253 if (m3->mc_pg[mc->mc_top] == mp) {
8254 /* if m3 points past last node in page, find next sibling */
8255 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
8256 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8257 rc = mdb_cursor_sibling(m3, 1);
8258 if (rc == MDB_NOTFOUND) {
8259 m3->mc_flags |= C_EOF;
8264 if (mc->mc_db->md_flags & MDB_DUPSORT) {
8265 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
8266 if (node->mn_flags & F_DUPDATA) {
8267 mdb_xcursor_init1(m3, node);
8268 m3->mc_xcursor->mx_cursor.mc_flags |= C_DEL;
8274 mc->mc_flags |= C_DEL;
8278 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8283 mdb_del(MDB_txn *txn, MDB_dbi dbi,
8284 MDB_val *key, MDB_val *data)
8286 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8289 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8290 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8292 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
8293 /* must ignore any data */
8297 return mdb_del0(txn, dbi, key, data, 0);
8301 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
8302 MDB_val *key, MDB_val *data, unsigned flags)
8307 MDB_val rdata, *xdata;
8311 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
8313 mdb_cursor_init(&mc, txn, dbi, &mx);
8322 flags |= MDB_NODUPDATA;
8324 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
8326 /* let mdb_page_split know about this cursor if needed:
8327 * delete will trigger a rebalance; if it needs to move
8328 * a node from one page to another, it will have to
8329 * update the parent's separator key(s). If the new sepkey
8330 * is larger than the current one, the parent page may
8331 * run out of space, triggering a split. We need this
8332 * cursor to be consistent until the end of the rebalance.
8334 mc.mc_flags |= C_UNTRACK;
8335 mc.mc_next = txn->mt_cursors[dbi];
8336 txn->mt_cursors[dbi] = &mc;
8337 rc = mdb_cursor_del(&mc, flags);
8338 txn->mt_cursors[dbi] = mc.mc_next;
8343 /** Split a page and insert a new node.
8344 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
8345 * The cursor will be updated to point to the actual page and index where
8346 * the node got inserted after the split.
8347 * @param[in] newkey The key for the newly inserted node.
8348 * @param[in] newdata The data for the newly inserted node.
8349 * @param[in] newpgno The page number, if the new node is a branch node.
8350 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
8351 * @return 0 on success, non-zero on failure.
8354 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
8355 unsigned int nflags)
8358 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
8361 int i, j, split_indx, nkeys, pmax;
8362 MDB_env *env = mc->mc_txn->mt_env;
8364 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
8365 MDB_page *copy = NULL;
8366 MDB_page *mp, *rp, *pp;
8371 mp = mc->mc_pg[mc->mc_top];
8372 newindx = mc->mc_ki[mc->mc_top];
8373 nkeys = NUMKEYS(mp);
8375 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
8376 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
8377 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
8379 /* Create a right sibling. */
8380 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
8382 rp->mp_pad = mp->mp_pad;
8383 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
8385 /* Usually when splitting the root page, the cursor
8386 * height is 1. But when called from mdb_update_key,
8387 * the cursor height may be greater because it walks
8388 * up the stack while finding the branch slot to update.
8390 if (mc->mc_top < 1) {
8391 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
8393 /* shift current top to make room for new parent */
8394 for (i=mc->mc_snum; i>0; i--) {
8395 mc->mc_pg[i] = mc->mc_pg[i-1];
8396 mc->mc_ki[i] = mc->mc_ki[i-1];
8400 mc->mc_db->md_root = pp->mp_pgno;
8401 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
8402 new_root = mc->mc_db->md_depth++;
8404 /* Add left (implicit) pointer. */
8405 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
8406 /* undo the pre-push */
8407 mc->mc_pg[0] = mc->mc_pg[1];
8408 mc->mc_ki[0] = mc->mc_ki[1];
8409 mc->mc_db->md_root = mp->mp_pgno;
8410 mc->mc_db->md_depth--;
8417 ptop = mc->mc_top-1;
8418 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
8421 mdb_cursor_copy(mc, &mn);
8422 mn.mc_xcursor = NULL;
8423 mn.mc_pg[mn.mc_top] = rp;
8424 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
8426 if (nflags & MDB_APPEND) {
8427 mn.mc_ki[mn.mc_top] = 0;
8429 split_indx = newindx;
8433 split_indx = (nkeys+1) / 2;
8438 unsigned int lsize, rsize, ksize;
8439 /* Move half of the keys to the right sibling */
8440 x = mc->mc_ki[mc->mc_top] - split_indx;
8441 ksize = mc->mc_db->md_pad;
8442 split = LEAF2KEY(mp, split_indx, ksize);
8443 rsize = (nkeys - split_indx) * ksize;
8444 lsize = (nkeys - split_indx) * sizeof(indx_t);
8445 mp->mp_lower -= lsize;
8446 rp->mp_lower += lsize;
8447 mp->mp_upper += rsize - lsize;
8448 rp->mp_upper -= rsize - lsize;
8449 sepkey.mv_size = ksize;
8450 if (newindx == split_indx) {
8451 sepkey.mv_data = newkey->mv_data;
8453 sepkey.mv_data = split;
8456 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
8457 memcpy(rp->mp_ptrs, split, rsize);
8458 sepkey.mv_data = rp->mp_ptrs;
8459 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
8460 memcpy(ins, newkey->mv_data, ksize);
8461 mp->mp_lower += sizeof(indx_t);
8462 mp->mp_upper -= ksize - sizeof(indx_t);
8465 memcpy(rp->mp_ptrs, split, x * ksize);
8466 ins = LEAF2KEY(rp, x, ksize);
8467 memcpy(ins, newkey->mv_data, ksize);
8468 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
8469 rp->mp_lower += sizeof(indx_t);
8470 rp->mp_upper -= ksize - sizeof(indx_t);
8471 mc->mc_ki[mc->mc_top] = x;
8474 int psize, nsize, k;
8475 /* Maximum free space in an empty page */
8476 pmax = env->me_psize - PAGEHDRSZ;
8478 nsize = mdb_leaf_size(env, newkey, newdata);
8480 nsize = mdb_branch_size(env, newkey);
8481 nsize = EVEN(nsize);
8483 /* grab a page to hold a temporary copy */
8484 copy = mdb_page_malloc(mc->mc_txn, 1);
8489 copy->mp_pgno = mp->mp_pgno;
8490 copy->mp_flags = mp->mp_flags;
8491 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
8492 copy->mp_upper = env->me_psize - PAGEBASE;
8494 /* prepare to insert */
8495 for (i=0, j=0; i<nkeys; i++) {
8497 copy->mp_ptrs[j++] = 0;
8499 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
8502 /* When items are relatively large the split point needs
8503 * to be checked, because being off-by-one will make the
8504 * difference between success or failure in mdb_node_add.
8506 * It's also relevant if a page happens to be laid out
8507 * such that one half of its nodes are all "small" and
8508 * the other half of its nodes are "large." If the new
8509 * item is also "large" and falls on the half with
8510 * "large" nodes, it also may not fit.
8512 * As a final tweak, if the new item goes on the last
8513 * spot on the page (and thus, onto the new page), bias
8514 * the split so the new page is emptier than the old page.
8515 * This yields better packing during sequential inserts.
8517 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
8518 /* Find split point */
8520 if (newindx <= split_indx || newindx >= nkeys) {
8522 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
8527 for (; i!=k; i+=j) {
8532 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8533 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
8535 if (F_ISSET(node->mn_flags, F_BIGDATA))
8536 psize += sizeof(pgno_t);
8538 psize += NODEDSZ(node);
8540 psize = EVEN(psize);
8542 if (psize > pmax || i == k-j) {
8543 split_indx = i + (j<0);
8548 if (split_indx == newindx) {
8549 sepkey.mv_size = newkey->mv_size;
8550 sepkey.mv_data = newkey->mv_data;
8552 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
8553 sepkey.mv_size = node->mn_ksize;
8554 sepkey.mv_data = NODEKEY(node);
8559 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
8561 /* Copy separator key to the parent.
8563 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
8564 int snum = mc->mc_snum;
8568 /* We want other splits to find mn when doing fixups */
8569 WITH_CURSOR_TRACKING(mn,
8570 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
8575 if (mc->mc_snum > snum) {
8578 /* Right page might now have changed parent.
8579 * Check if left page also changed parent.
8581 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8582 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8583 for (i=0; i<ptop; i++) {
8584 mc->mc_pg[i] = mn.mc_pg[i];
8585 mc->mc_ki[i] = mn.mc_ki[i];
8587 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8588 if (mn.mc_ki[ptop]) {
8589 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8591 /* find right page's left sibling */
8592 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8593 mdb_cursor_sibling(mc, 0);
8598 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8601 if (rc != MDB_SUCCESS) {
8604 if (nflags & MDB_APPEND) {
8605 mc->mc_pg[mc->mc_top] = rp;
8606 mc->mc_ki[mc->mc_top] = 0;
8607 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8610 for (i=0; i<mc->mc_top; i++)
8611 mc->mc_ki[i] = mn.mc_ki[i];
8612 } else if (!IS_LEAF2(mp)) {
8614 mc->mc_pg[mc->mc_top] = rp;
8619 rkey.mv_data = newkey->mv_data;
8620 rkey.mv_size = newkey->mv_size;
8626 /* Update index for the new key. */
8627 mc->mc_ki[mc->mc_top] = j;
8629 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8630 rkey.mv_data = NODEKEY(node);
8631 rkey.mv_size = node->mn_ksize;
8633 xdata.mv_data = NODEDATA(node);
8634 xdata.mv_size = NODEDSZ(node);
8637 pgno = NODEPGNO(node);
8638 flags = node->mn_flags;
8641 if (!IS_LEAF(mp) && j == 0) {
8642 /* First branch index doesn't need key data. */
8646 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8652 mc->mc_pg[mc->mc_top] = copy;
8657 } while (i != split_indx);
8659 nkeys = NUMKEYS(copy);
8660 for (i=0; i<nkeys; i++)
8661 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8662 mp->mp_lower = copy->mp_lower;
8663 mp->mp_upper = copy->mp_upper;
8664 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8665 env->me_psize - copy->mp_upper - PAGEBASE);
8667 /* reset back to original page */
8668 if (newindx < split_indx) {
8669 mc->mc_pg[mc->mc_top] = mp;
8671 mc->mc_pg[mc->mc_top] = rp;
8673 /* Make sure mc_ki is still valid.
8675 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8676 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8677 for (i=0; i<=ptop; i++) {
8678 mc->mc_pg[i] = mn.mc_pg[i];
8679 mc->mc_ki[i] = mn.mc_ki[i];
8683 if (nflags & MDB_RESERVE) {
8684 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8685 if (!(node->mn_flags & F_BIGDATA))
8686 newdata->mv_data = NODEDATA(node);
8689 if (newindx >= split_indx) {
8690 mc->mc_pg[mc->mc_top] = rp;
8692 /* Make sure mc_ki is still valid.
8694 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8695 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8696 for (i=0; i<=ptop; i++) {
8697 mc->mc_pg[i] = mn.mc_pg[i];
8698 mc->mc_ki[i] = mn.mc_ki[i];
8705 /* Adjust other cursors pointing to mp */
8706 MDB_cursor *m2, *m3;
8707 MDB_dbi dbi = mc->mc_dbi;
8708 nkeys = NUMKEYS(mp);
8710 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8711 if (mc->mc_flags & C_SUB)
8712 m3 = &m2->mc_xcursor->mx_cursor;
8717 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8721 /* sub cursors may be on different DB */
8722 if (m3->mc_pg[0] != mp)
8725 for (k=new_root; k>=0; k--) {
8726 m3->mc_ki[k+1] = m3->mc_ki[k];
8727 m3->mc_pg[k+1] = m3->mc_pg[k];
8729 if (m3->mc_ki[0] >= nkeys) {
8734 m3->mc_pg[0] = mc->mc_pg[0];
8738 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8739 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8740 m3->mc_ki[mc->mc_top]++;
8741 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8742 m3->mc_pg[mc->mc_top] = rp;
8743 m3->mc_ki[mc->mc_top] -= nkeys;
8744 for (i=0; i<mc->mc_top; i++) {
8745 m3->mc_ki[i] = mn.mc_ki[i];
8746 m3->mc_pg[i] = mn.mc_pg[i];
8749 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8750 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8753 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8755 MDB_node *node = NODEPTR(m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
8756 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8757 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8761 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8764 if (copy) /* tmp page */
8765 mdb_page_free(env, copy);
8767 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8772 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8773 MDB_val *key, MDB_val *data, unsigned int flags)
8779 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8782 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
8785 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8786 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8788 mdb_cursor_init(&mc, txn, dbi, &mx);
8789 mc.mc_next = txn->mt_cursors[dbi];
8790 txn->mt_cursors[dbi] = &mc;
8791 rc = mdb_cursor_put(&mc, key, data, flags);
8792 txn->mt_cursors[dbi] = mc.mc_next;
8797 #define MDB_WBUF (1024*1024)
8800 /** State needed for a compacting copy. */
8801 typedef struct mdb_copy {
8802 pthread_mutex_t mc_mutex;
8803 pthread_cond_t mc_cond;
8810 pgno_t mc_next_pgno;
8813 volatile int mc_new;
8818 /** Dedicated writer thread for compacting copy. */
8819 static THREAD_RET ESECT CALL_CONV
8820 mdb_env_copythr(void *arg)
8824 int toggle = 0, wsize, rc;
8827 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8830 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8833 pthread_mutex_lock(&my->mc_mutex);
8835 pthread_cond_signal(&my->mc_cond);
8838 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8839 if (my->mc_new < 0) {
8844 wsize = my->mc_wlen[toggle];
8845 ptr = my->mc_wbuf[toggle];
8848 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8852 } else if (len > 0) {
8866 /* If there's an overflow page tail, write it too */
8867 if (my->mc_olen[toggle]) {
8868 wsize = my->mc_olen[toggle];
8869 ptr = my->mc_over[toggle];
8870 my->mc_olen[toggle] = 0;
8873 my->mc_wlen[toggle] = 0;
8875 pthread_cond_signal(&my->mc_cond);
8877 pthread_cond_signal(&my->mc_cond);
8878 pthread_mutex_unlock(&my->mc_mutex);
8879 return (THREAD_RET)0;
8883 /** Tell the writer thread there's a buffer ready to write */
8885 mdb_env_cthr_toggle(mdb_copy *my, int st)
8887 int toggle = my->mc_toggle ^ 1;
8888 pthread_mutex_lock(&my->mc_mutex);
8889 if (my->mc_status) {
8890 pthread_mutex_unlock(&my->mc_mutex);
8891 return my->mc_status;
8893 while (my->mc_new == 1)
8894 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8896 my->mc_toggle = toggle;
8897 pthread_cond_signal(&my->mc_cond);
8898 pthread_mutex_unlock(&my->mc_mutex);
8902 /** Depth-first tree traversal for compacting copy. */
8904 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8906 MDB_cursor mc = {0};
8907 MDB_txn *txn = my->mc_txn;
8909 MDB_page *mo, *mp, *leaf;
8914 /* Empty DB, nothing to do */
8915 if (*pg == P_INVALID)
8921 rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
8924 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8928 /* Make cursor pages writable */
8929 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8933 for (i=0; i<mc.mc_top; i++) {
8934 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8935 mc.mc_pg[i] = (MDB_page *)ptr;
8936 ptr += my->mc_env->me_psize;
8939 /* This is writable space for a leaf page. Usually not needed. */
8940 leaf = (MDB_page *)ptr;
8942 toggle = my->mc_toggle;
8943 while (mc.mc_snum > 0) {
8945 mp = mc.mc_pg[mc.mc_top];
8949 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8950 for (i=0; i<n; i++) {
8951 ni = NODEPTR(mp, i);
8952 if (ni->mn_flags & F_BIGDATA) {
8956 /* Need writable leaf */
8958 mc.mc_pg[mc.mc_top] = leaf;
8959 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8961 ni = NODEPTR(mp, i);
8964 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8965 rc = mdb_page_get(txn, pg, &omp, NULL);
8968 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8969 rc = mdb_env_cthr_toggle(my, 1);
8972 toggle = my->mc_toggle;
8974 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8975 memcpy(mo, omp, my->mc_env->me_psize);
8976 mo->mp_pgno = my->mc_next_pgno;
8977 my->mc_next_pgno += omp->mp_pages;
8978 my->mc_wlen[toggle] += my->mc_env->me_psize;
8979 if (omp->mp_pages > 1) {
8980 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
8981 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
8982 rc = mdb_env_cthr_toggle(my, 1);
8985 toggle = my->mc_toggle;
8987 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
8988 } else if (ni->mn_flags & F_SUBDATA) {
8991 /* Need writable leaf */
8993 mc.mc_pg[mc.mc_top] = leaf;
8994 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8996 ni = NODEPTR(mp, i);
8999 memcpy(&db, NODEDATA(ni), sizeof(db));
9000 my->mc_toggle = toggle;
9001 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
9004 toggle = my->mc_toggle;
9005 memcpy(NODEDATA(ni), &db, sizeof(db));
9010 mc.mc_ki[mc.mc_top]++;
9011 if (mc.mc_ki[mc.mc_top] < n) {
9014 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
9016 rc = mdb_page_get(txn, pg, &mp, NULL);
9021 mc.mc_ki[mc.mc_top] = 0;
9022 if (IS_BRANCH(mp)) {
9023 /* Whenever we advance to a sibling branch page,
9024 * we must proceed all the way down to its first leaf.
9026 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
9029 mc.mc_pg[mc.mc_top] = mp;
9033 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9034 rc = mdb_env_cthr_toggle(my, 1);
9037 toggle = my->mc_toggle;
9039 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9040 mdb_page_copy(mo, mp, my->mc_env->me_psize);
9041 mo->mp_pgno = my->mc_next_pgno++;
9042 my->mc_wlen[toggle] += my->mc_env->me_psize;
9044 /* Update parent if there is one */
9045 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
9046 SETPGNO(ni, mo->mp_pgno);
9047 mdb_cursor_pop(&mc);
9049 /* Otherwise we're done */
9059 /** Copy environment with compaction. */
9061 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
9066 MDB_txn *txn = NULL;
9071 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
9072 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
9073 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
9074 if (my.mc_wbuf[0] == NULL)
9077 pthread_mutex_init(&my.mc_mutex, NULL);
9078 pthread_cond_init(&my.mc_cond, NULL);
9079 #ifdef HAVE_MEMALIGN
9080 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
9081 if (my.mc_wbuf[0] == NULL)
9084 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_os_psize, MDB_WBUF*2);
9089 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
9090 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
9095 my.mc_next_pgno = NUM_METAS;
9101 THREAD_CREATE(thr, mdb_env_copythr, &my);
9103 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9107 mp = (MDB_page *)my.mc_wbuf[0];
9108 memset(mp, 0, NUM_METAS * env->me_psize);
9110 mp->mp_flags = P_META;
9111 mm = (MDB_meta *)METADATA(mp);
9112 mdb_env_init_meta0(env, mm);
9113 mm->mm_address = env->me_metas[0]->mm_address;
9115 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
9117 mp->mp_flags = P_META;
9118 *(MDB_meta *)METADATA(mp) = *mm;
9119 mm = (MDB_meta *)METADATA(mp);
9121 /* Count the number of free pages, subtract from lastpg to find
9122 * number of active pages
9125 MDB_ID freecount = 0;
9128 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
9129 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
9130 freecount += *(MDB_ID *)data.mv_data;
9131 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
9132 txn->mt_dbs[FREE_DBI].md_leaf_pages +
9133 txn->mt_dbs[FREE_DBI].md_overflow_pages;
9135 /* Set metapage 1 */
9136 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
9137 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
9138 if (mm->mm_last_pg > NUM_METAS-1) {
9139 mm->mm_dbs[MAIN_DBI].md_root = mm->mm_last_pg;
9142 mm->mm_dbs[MAIN_DBI].md_root = P_INVALID;
9145 my.mc_wlen[0] = env->me_psize * NUM_METAS;
9147 pthread_mutex_lock(&my.mc_mutex);
9149 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
9150 pthread_mutex_unlock(&my.mc_mutex);
9151 rc = mdb_env_cwalk(&my, &txn->mt_dbs[MAIN_DBI].md_root, 0);
9152 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
9153 rc = mdb_env_cthr_toggle(&my, 1);
9154 mdb_env_cthr_toggle(&my, -1);
9155 pthread_mutex_lock(&my.mc_mutex);
9157 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
9158 pthread_mutex_unlock(&my.mc_mutex);
9163 CloseHandle(my.mc_cond);
9164 CloseHandle(my.mc_mutex);
9165 _aligned_free(my.mc_wbuf[0]);
9167 pthread_cond_destroy(&my.mc_cond);
9168 pthread_mutex_destroy(&my.mc_mutex);
9169 free(my.mc_wbuf[0]);
9174 /** Copy environment as-is. */
9176 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
9178 MDB_txn *txn = NULL;
9179 mdb_mutexref_t wmutex = NULL;
9185 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9189 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9192 /* Do the lock/unlock of the reader mutex before starting the
9193 * write txn. Otherwise other read txns could block writers.
9195 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9200 /* We must start the actual read txn after blocking writers */
9201 mdb_txn_end(txn, MDB_END_RESET_TMP);
9203 /* Temporarily block writers until we snapshot the meta pages */
9204 wmutex = env->me_wmutex;
9205 if (LOCK_MUTEX(rc, env, wmutex))
9208 rc = mdb_txn_renew0(txn);
9210 UNLOCK_MUTEX(wmutex);
9215 wsize = env->me_psize * NUM_METAS;
9219 DO_WRITE(rc, fd, ptr, w2, len);
9223 } else if (len > 0) {
9229 /* Non-blocking or async handles are not supported */
9235 UNLOCK_MUTEX(wmutex);
9240 w3 = txn->mt_next_pgno * env->me_psize;
9243 if ((rc = mdb_fsize(env->me_fd, &fsize)))
9250 if (wsize > MAX_WRITE)
9254 DO_WRITE(rc, fd, ptr, w2, len);
9258 } else if (len > 0) {
9275 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
9277 if (flags & MDB_CP_COMPACT)
9278 return mdb_env_copyfd1(env, fd);
9280 return mdb_env_copyfd0(env, fd);
9284 mdb_env_copyfd(MDB_env *env, HANDLE fd)
9286 return mdb_env_copyfd2(env, fd, 0);
9290 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
9294 HANDLE newfd = INVALID_HANDLE_VALUE;
9299 if (env->me_flags & MDB_NOSUBDIR) {
9300 lpath = (char *)path;
9303 len += sizeof(DATANAME);
9304 lpath = malloc(len);
9307 sprintf(lpath, "%s" DATANAME, path);
9310 /* The destination path must exist, but the destination file must not.
9311 * We don't want the OS to cache the writes, since the source data is
9312 * already in the OS cache.
9315 rc = utf8_to_utf16(lpath, -1, &wpath, NULL);
9318 newfd = CreateFileW(wpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
9319 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
9322 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
9324 if (newfd == INVALID_HANDLE_VALUE) {
9329 if (env->me_psize >= env->me_os_psize) {
9331 /* Set O_DIRECT if the file system supports it */
9332 if ((rc = fcntl(newfd, F_GETFL)) != -1)
9333 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
9335 #ifdef F_NOCACHE /* __APPLE__ */
9336 rc = fcntl(newfd, F_NOCACHE, 1);
9344 rc = mdb_env_copyfd2(env, newfd, flags);
9347 if (!(env->me_flags & MDB_NOSUBDIR))
9349 if (newfd != INVALID_HANDLE_VALUE)
9350 if (close(newfd) < 0 && rc == MDB_SUCCESS)
9357 mdb_env_copy(MDB_env *env, const char *path)
9359 return mdb_env_copy2(env, path, 0);
9363 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
9365 if (flag & ~CHANGEABLE)
9368 env->me_flags |= flag;
9370 env->me_flags &= ~flag;
9375 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
9380 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
9385 mdb_env_set_userctx(MDB_env *env, void *ctx)
9389 env->me_userctx = ctx;
9394 mdb_env_get_userctx(MDB_env *env)
9396 return env ? env->me_userctx : NULL;
9400 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
9405 env->me_assert_func = func;
9411 mdb_env_get_path(MDB_env *env, const char **arg)
9416 *arg = env->me_path;
9421 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
9430 /** Common code for #mdb_stat() and #mdb_env_stat().
9431 * @param[in] env the environment to operate in.
9432 * @param[in] db the #MDB_db record containing the stats to return.
9433 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
9434 * @return 0, this function always succeeds.
9437 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
9439 arg->ms_psize = env->me_psize;
9440 arg->ms_depth = db->md_depth;
9441 arg->ms_branch_pages = db->md_branch_pages;
9442 arg->ms_leaf_pages = db->md_leaf_pages;
9443 arg->ms_overflow_pages = db->md_overflow_pages;
9444 arg->ms_entries = db->md_entries;
9450 mdb_env_stat(MDB_env *env, MDB_stat *arg)
9454 if (env == NULL || arg == NULL)
9457 meta = mdb_env_pick_meta(env);
9459 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
9463 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
9467 if (env == NULL || arg == NULL)
9470 meta = mdb_env_pick_meta(env);
9471 arg->me_mapaddr = meta->mm_address;
9472 arg->me_last_pgno = meta->mm_last_pg;
9473 arg->me_last_txnid = meta->mm_txnid;
9475 arg->me_mapsize = env->me_mapsize;
9476 arg->me_maxreaders = env->me_maxreaders;
9477 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
9481 /** Set the default comparison functions for a database.
9482 * Called immediately after a database is opened to set the defaults.
9483 * The user can then override them with #mdb_set_compare() or
9484 * #mdb_set_dupsort().
9485 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
9486 * @param[in] dbi A database handle returned by #mdb_dbi_open()
9489 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
9491 uint16_t f = txn->mt_dbs[dbi].md_flags;
9493 txn->mt_dbxs[dbi].md_cmp =
9494 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
9495 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
9497 txn->mt_dbxs[dbi].md_dcmp =
9498 !(f & MDB_DUPSORT) ? 0 :
9499 ((f & MDB_INTEGERDUP)
9500 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
9501 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
9504 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
9510 int rc, dbflag, exact;
9511 unsigned int unused = 0, seq;
9515 if (flags & ~VALID_FLAGS)
9517 if (txn->mt_flags & MDB_TXN_BLOCKED)
9523 if (flags & PERSISTENT_FLAGS) {
9524 uint16_t f2 = flags & PERSISTENT_FLAGS;
9525 /* make sure flag changes get committed */
9526 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
9527 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
9528 txn->mt_flags |= MDB_TXN_DIRTY;
9531 mdb_default_cmp(txn, MAIN_DBI);
9535 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
9536 mdb_default_cmp(txn, MAIN_DBI);
9539 /* Is the DB already open? */
9541 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
9542 if (!txn->mt_dbxs[i].md_name.mv_size) {
9543 /* Remember this free slot */
9544 if (!unused) unused = i;
9547 if (len == txn->mt_dbxs[i].md_name.mv_size &&
9548 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
9554 /* If no free slot and max hit, fail */
9555 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
9556 return MDB_DBS_FULL;
9558 /* Cannot mix named databases with some mainDB flags */
9559 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
9560 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
9562 /* Find the DB info */
9563 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
9566 key.mv_data = (void *)name;
9567 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
9568 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
9569 if (rc == MDB_SUCCESS) {
9570 /* make sure this is actually a DB */
9571 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
9572 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
9573 return MDB_INCOMPATIBLE;
9574 } else if (! (rc == MDB_NOTFOUND && (flags & MDB_CREATE))) {
9578 /* Done here so we cannot fail after creating a new DB */
9579 if ((namedup = strdup(name)) == NULL)
9583 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
9584 data.mv_size = sizeof(MDB_db);
9585 data.mv_data = &dummy;
9586 memset(&dummy, 0, sizeof(dummy));
9587 dummy.md_root = P_INVALID;
9588 dummy.md_flags = flags & PERSISTENT_FLAGS;
9589 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
9596 /* Got info, register DBI in this txn */
9597 unsigned int slot = unused ? unused : txn->mt_numdbs;
9598 txn->mt_dbxs[slot].md_name.mv_data = namedup;
9599 txn->mt_dbxs[slot].md_name.mv_size = len;
9600 txn->mt_dbxs[slot].md_rel = NULL;
9601 txn->mt_dbflags[slot] = dbflag;
9602 /* txn-> and env-> are the same in read txns, use
9603 * tmp variable to avoid undefined assignment
9605 seq = ++txn->mt_env->me_dbiseqs[slot];
9606 txn->mt_dbiseqs[slot] = seq;
9608 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
9610 mdb_default_cmp(txn, slot);
9620 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9622 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
9625 if (txn->mt_flags & MDB_TXN_BLOCKED)
9628 if (txn->mt_dbflags[dbi] & DB_STALE) {
9631 /* Stale, must read the DB's root. cursor_init does it for us. */
9632 mdb_cursor_init(&mc, txn, dbi, &mx);
9634 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9637 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9640 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
9642 ptr = env->me_dbxs[dbi].md_name.mv_data;
9643 /* If there was no name, this was already closed */
9645 env->me_dbxs[dbi].md_name.mv_data = NULL;
9646 env->me_dbxs[dbi].md_name.mv_size = 0;
9647 env->me_dbflags[dbi] = 0;
9648 env->me_dbiseqs[dbi]++;
9653 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9655 /* We could return the flags for the FREE_DBI too but what's the point? */
9656 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9658 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9662 /** Add all the DB's pages to the free list.
9663 * @param[in] mc Cursor on the DB to free.
9664 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9665 * @return 0 on success, non-zero on failure.
9668 mdb_drop0(MDB_cursor *mc, int subs)
9672 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9673 if (rc == MDB_SUCCESS) {
9674 MDB_txn *txn = mc->mc_txn;
9679 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
9680 * This also avoids any P_LEAF2 pages, which have no nodes.
9681 * Also if the DB doesn't have sub-DBs and has no overflow
9682 * pages, omit scanning leaves.
9684 if ((mc->mc_flags & C_SUB) ||
9685 (!subs && !mc->mc_db->md_overflow_pages))
9688 mdb_cursor_copy(mc, &mx);
9689 while (mc->mc_snum > 0) {
9690 MDB_page *mp = mc->mc_pg[mc->mc_top];
9691 unsigned n = NUMKEYS(mp);
9693 for (i=0; i<n; i++) {
9694 ni = NODEPTR(mp, i);
9695 if (ni->mn_flags & F_BIGDATA) {
9698 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9699 rc = mdb_page_get(txn, pg, &omp, NULL);
9702 mdb_cassert(mc, IS_OVERFLOW(omp));
9703 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9707 mc->mc_db->md_overflow_pages -= omp->mp_pages;
9708 if (!mc->mc_db->md_overflow_pages && !subs)
9710 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9711 mdb_xcursor_init1(mc, ni);
9712 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9717 if (!subs && !mc->mc_db->md_overflow_pages)
9720 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9722 for (i=0; i<n; i++) {
9724 ni = NODEPTR(mp, i);
9727 mdb_midl_xappend(txn->mt_free_pgs, pg);
9732 mc->mc_ki[mc->mc_top] = i;
9733 rc = mdb_cursor_sibling(mc, 1);
9735 if (rc != MDB_NOTFOUND)
9737 /* no more siblings, go back to beginning
9738 * of previous level.
9743 for (i=1; i<mc->mc_snum; i++) {
9745 mc->mc_pg[i] = mx.mc_pg[i];
9750 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9753 txn->mt_flags |= MDB_TXN_ERROR;
9754 } else if (rc == MDB_NOTFOUND) {
9757 mc->mc_flags &= ~C_INITIALIZED;
9761 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9763 MDB_cursor *mc, *m2;
9766 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9769 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9772 if (TXN_DBI_CHANGED(txn, dbi))
9775 rc = mdb_cursor_open(txn, dbi, &mc);
9779 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9780 /* Invalidate the dropped DB's cursors */
9781 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9782 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9786 /* Can't delete the main DB */
9787 if (del && dbi >= CORE_DBS) {
9788 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
9790 txn->mt_dbflags[dbi] = DB_STALE;
9791 mdb_dbi_close(txn->mt_env, dbi);
9793 txn->mt_flags |= MDB_TXN_ERROR;
9796 /* reset the DB record, mark it dirty */
9797 txn->mt_dbflags[dbi] |= DB_DIRTY;
9798 txn->mt_dbs[dbi].md_depth = 0;
9799 txn->mt_dbs[dbi].md_branch_pages = 0;
9800 txn->mt_dbs[dbi].md_leaf_pages = 0;
9801 txn->mt_dbs[dbi].md_overflow_pages = 0;
9802 txn->mt_dbs[dbi].md_entries = 0;
9803 txn->mt_dbs[dbi].md_root = P_INVALID;
9805 txn->mt_flags |= MDB_TXN_DIRTY;
9808 mdb_cursor_close(mc);
9812 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9814 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9817 txn->mt_dbxs[dbi].md_cmp = cmp;
9821 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9823 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9826 txn->mt_dbxs[dbi].md_dcmp = cmp;
9830 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9832 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9835 txn->mt_dbxs[dbi].md_rel = rel;
9839 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9841 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9844 txn->mt_dbxs[dbi].md_relctx = ctx;
9849 mdb_env_get_maxkeysize(MDB_env *env)
9851 return ENV_MAXKEY(env);
9855 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9857 unsigned int i, rdrs;
9860 int rc = 0, first = 1;
9864 if (!env->me_txns) {
9865 return func("(no reader locks)\n", ctx);
9867 rdrs = env->me_txns->mti_numreaders;
9868 mr = env->me_txns->mti_readers;
9869 for (i=0; i<rdrs; i++) {
9871 txnid_t txnid = mr[i].mr_txnid;
9872 sprintf(buf, txnid == (txnid_t)-1 ?
9873 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9874 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9877 rc = func(" pid thread txnid\n", ctx);
9881 rc = func(buf, ctx);
9887 rc = func("(no active readers)\n", ctx);
9892 /** Insert pid into list if not already present.
9893 * return -1 if already present.
9896 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9898 /* binary search of pid in list */
9900 unsigned cursor = 1;
9902 unsigned n = ids[0];
9905 unsigned pivot = n >> 1;
9906 cursor = base + pivot + 1;
9907 val = pid - ids[cursor];
9912 } else if ( val > 0 ) {
9917 /* found, so it's a duplicate */
9926 for (n = ids[0]; n > cursor; n--)
9933 mdb_reader_check(MDB_env *env, int *dead)
9939 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
9942 /** As #mdb_reader_check(). rlocked = <caller locked the reader mutex>. */
9944 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
9946 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
9947 unsigned int i, j, rdrs;
9949 MDB_PID_T *pids, pid;
9950 int rc = MDB_SUCCESS, count = 0;
9952 rdrs = env->me_txns->mti_numreaders;
9953 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
9957 mr = env->me_txns->mti_readers;
9958 for (i=0; i<rdrs; i++) {
9960 if (pid && pid != env->me_pid) {
9961 if (mdb_pid_insert(pids, pid) == 0) {
9962 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9963 /* Stale reader found */
9966 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
9967 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
9969 rdrs = 0; /* the above checked all readers */
9971 /* Recheck, a new process may have reused pid */
9972 if (mdb_reader_pid(env, Pidcheck, pid))
9977 if (mr[j].mr_pid == pid) {
9978 DPRINTF(("clear stale reader pid %u txn %"Z"d",
9979 (unsigned) pid, mr[j].mr_txnid));
9984 UNLOCK_MUTEX(rmutex);
9995 #ifdef MDB_ROBUST_SUPPORTED
9996 /** Handle #LOCK_MUTEX0() failure.
9997 * Try to repair the lock file if the mutex owner died.
9998 * @param[in] env the environment handle
9999 * @param[in] mutex LOCK_MUTEX0() mutex
10000 * @param[in] rc LOCK_MUTEX0() error (nonzero)
10001 * @return 0 on success with the mutex locked, or an error code on failure.
10004 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10009 if (rc == MDB_OWNERDEAD) {
10010 /* We own the mutex. Clean up after dead previous owner. */
10012 rlocked = (mutex == env->me_rmutex);
10014 /* Keep mti_txnid updated, otherwise next writer can
10015 * overwrite data which latest meta page refers to.
10017 meta = mdb_env_pick_meta(env);
10018 env->me_txns->mti_txnid = meta->mm_txnid;
10019 /* env is hosed if the dead thread was ours */
10021 env->me_flags |= MDB_FATAL_ERROR;
10022 env->me_txn = NULL;
10026 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
10027 (rc ? "this process' env is hosed" : "recovering")));
10028 rc2 = mdb_reader_check0(env, rlocked, NULL);
10030 rc2 = mdb_mutex_consistent(mutex);
10031 if (rc || (rc = rc2)) {
10032 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
10033 UNLOCK_MUTEX(mutex);
10039 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
10044 #endif /* MDB_ROBUST_SUPPORTED */
10047 #if defined(_WIN32)
10048 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize)
10052 need = MultiByteToWideChar(CP_UTF8, 0, src, srcsize, NULL, 0);
10053 if (need == 0xFFFD)
10057 result = malloc(sizeof(wchar_t) * need);
10060 MultiByteToWideChar(CP_UTF8, 0, src, srcsize, result, need);
10066 #endif /* defined(_WIN32) */