2 * @brief Lightning memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2015 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
41 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
42 * as int64 which is wrong. MSVC doesn't define it at all, so just
46 #define MDB_THR_T DWORD
47 #include <sys/types.h>
50 # include <sys/param.h>
52 # define LITTLE_ENDIAN 1234
53 # define BIG_ENDIAN 4321
54 # define BYTE_ORDER LITTLE_ENDIAN
56 # define SSIZE_MAX INT_MAX
60 #include <sys/types.h>
62 #define MDB_PID_T pid_t
63 #define MDB_THR_T pthread_t
64 #include <sys/param.h>
67 #ifdef HAVE_SYS_FILE_H
73 #if defined(__mips) && defined(__linux)
74 /* MIPS has cache coherency issues, requires explicit cache control */
75 #include <asm/cachectl.h>
76 extern int cacheflush(char *addr, int nbytes, int cache);
77 #define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
79 #define CACHEFLUSH(addr, bytes, cache)
82 #if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
83 /** fdatasync is broken on ext3/ext4fs on older kernels, see
84 * description in #mdb_env_open2 comments. You can safely
85 * define MDB_FDATASYNC_WORKS if this code will only be run
86 * on kernels 3.6 and newer.
88 #define BROKEN_FDATASYNC
102 typedef SSIZE_T ssize_t;
107 #if defined(__sun) || defined(ANDROID)
108 /* Most platforms have posix_memalign, older may only have memalign */
109 #define HAVE_MEMALIGN 1
113 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
114 #include <netinet/in.h>
115 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
118 #if defined(__APPLE__) || defined (BSD)
119 # define MDB_USE_POSIX_SEM 1
120 # define MDB_FDATASYNC fsync
121 #elif defined(ANDROID)
122 # define MDB_FDATASYNC fsync
127 #ifdef MDB_USE_POSIX_SEM
128 # define MDB_USE_HASH 1
129 #include <semaphore.h>
131 #define MDB_USE_POSIX_MUTEX 1
135 #if defined(_WIN32) + defined(MDB_USE_POSIX_SEM) \
136 + defined(MDB_USE_POSIX_MUTEX) != 1
137 # error "Ambiguous shared-lock implementation"
141 #include <valgrind/memcheck.h>
142 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
143 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
144 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
145 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
146 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
148 #define VGMEMP_CREATE(h,r,z)
149 #define VGMEMP_ALLOC(h,a,s)
150 #define VGMEMP_FREE(h,a)
151 #define VGMEMP_DESTROY(h)
152 #define VGMEMP_DEFINED(a,s)
156 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
157 /* Solaris just defines one or the other */
158 # define LITTLE_ENDIAN 1234
159 # define BIG_ENDIAN 4321
160 # ifdef _LITTLE_ENDIAN
161 # define BYTE_ORDER LITTLE_ENDIAN
163 # define BYTE_ORDER BIG_ENDIAN
166 # define BYTE_ORDER __BYTE_ORDER
170 #ifndef LITTLE_ENDIAN
171 #define LITTLE_ENDIAN __LITTLE_ENDIAN
174 #define BIG_ENDIAN __BIG_ENDIAN
177 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
178 #define MISALIGNED_OK 1
184 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
185 # error "Unknown or unsupported endianness (BYTE_ORDER)"
186 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
187 # error "Two's complement, reasonably sized integer types, please"
191 /** Put infrequently used env functions in separate section */
193 # define ESECT __attribute__ ((section("__TEXT,text_env")))
195 # define ESECT __attribute__ ((section("text_env")))
202 #define CALL_CONV WINAPI
207 /** @defgroup internal LMDB Internals
210 /** @defgroup compat Compatibility Macros
211 * A bunch of macros to minimize the amount of platform-specific ifdefs
212 * needed throughout the rest of the code. When the features this library
213 * needs are similar enough to POSIX to be hidden in a one-or-two line
214 * replacement, this macro approach is used.
218 /** Features under development */
223 /** Wrapper around __func__, which is a C99 feature */
224 #if __STDC_VERSION__ >= 199901L
225 # define mdb_func_ __func__
226 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
227 # define mdb_func_ __FUNCTION__
229 /* If a debug message says <mdb_unknown>(), update the #if statements above */
230 # define mdb_func_ "<mdb_unknown>"
233 /* Internal error codes, not exposed outside liblmdb */
234 #define MDB_NO_ROOT (MDB_LAST_ERRCODE + 10)
236 #define MDB_OWNERDEAD ((int) WAIT_ABANDONED)
237 #elif defined(MDB_USE_POSIX_MUTEX) && defined(EOWNERDEAD)
238 #define MDB_OWNERDEAD EOWNERDEAD /**< #LOCK_MUTEX0() result if dead owner */
242 /** Some platforms define the EOWNERDEAD error code
243 * even though they don't support Robust Mutexes.
244 * Compile with -DMDB_USE_ROBUST=0, or use some other
245 * mechanism like -DMDB_USE_SYSV_SEM instead of
246 * -DMDB_USE_POSIX_MUTEX. (SysV semaphores are
247 * also Robust, but some systems don't support them
250 #ifndef MDB_USE_ROBUST
251 /* Android currently lacks Robust Mutex support */
252 #if defined(ANDROID) && defined(MDB_USE_POSIX_MUTEX) && !defined(MDB_USE_ROBUST)
253 #define MDB_USE_ROBUST 0
255 #define MDB_USE_ROBUST 1
257 #endif /* MDB_USE_ROBUST */
259 #if defined(MDB_OWNERDEAD) && MDB_USE_ROBUST
260 #define MDB_ROBUST_SUPPORTED 1
264 #define MDB_USE_HASH 1
265 #define MDB_PIDLOCK 0
266 #define THREAD_RET DWORD
267 #define pthread_t HANDLE
268 #define pthread_mutex_t HANDLE
269 #define pthread_cond_t HANDLE
270 typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
271 #define pthread_key_t DWORD
272 #define pthread_self() GetCurrentThreadId()
273 #define pthread_key_create(x,y) \
274 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
275 #define pthread_key_delete(x) TlsFree(x)
276 #define pthread_getspecific(x) TlsGetValue(x)
277 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
278 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
279 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
280 #define pthread_cond_signal(x) SetEvent(*x)
281 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
282 #define THREAD_CREATE(thr,start,arg) thr=CreateThread(NULL,0,start,arg,0,NULL)
283 #define THREAD_FINISH(thr) WaitForSingleObject(thr, INFINITE)
284 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
285 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
286 #define mdb_mutex_consistent(mutex) 0
287 #define getpid() GetCurrentProcessId()
288 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
289 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
290 #define ErrCode() GetLastError()
291 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
292 #define close(fd) (CloseHandle(fd) ? 0 : -1)
293 #define munmap(ptr,len) UnmapViewOfFile(ptr)
294 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
295 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
297 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
301 #define THREAD_RET void *
302 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
303 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
304 #define Z "z" /**< printf format modifier for size_t */
306 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
307 #define MDB_PIDLOCK 1
309 #ifdef MDB_USE_POSIX_SEM
311 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
312 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
313 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
316 mdb_sem_wait(sem_t *sem)
319 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
323 #else /* MDB_USE_POSIX_MUTEX: */
324 /** Shared mutex/semaphore as it is stored (mdb_mutex_t), and as
325 * local variables keep it (mdb_mutexref_t).
327 * When #mdb_mutexref_t is a pointer declaration and #mdb_mutex_t is
328 * not, then it is array[size 1] so it can be assigned to a pointer.
331 typedef pthread_mutex_t mdb_mutex_t[1], *mdb_mutexref_t;
333 /** Lock the reader or writer mutex.
334 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
336 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
337 /** Unlock the reader or writer mutex.
339 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
340 /** Mark mutex-protected data as repaired, after death of previous owner.
342 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
343 #endif /* MDB_USE_POSIX_SEM */
345 /** Get the error code for the last failed system function.
347 #define ErrCode() errno
349 /** An abstraction for a file handle.
350 * On POSIX systems file handles are small integers. On Windows
351 * they're opaque pointers.
355 /** A value for an invalid file handle.
356 * Mainly used to initialize file variables and signify that they are
359 #define INVALID_HANDLE_VALUE (-1)
361 /** Get the size of a memory page for the system.
362 * This is the basic size that the platform's memory manager uses, and is
363 * fundamental to the use of memory-mapped files.
365 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
368 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
371 #define MNAME_LEN (sizeof(pthread_mutex_t))
376 #ifdef MDB_ROBUST_SUPPORTED
377 /** Lock mutex, handle any error, set rc = result.
378 * Return 0 on success, nonzero (not rc) on error.
380 #define LOCK_MUTEX(rc, env, mutex) \
381 (((rc) = LOCK_MUTEX0(mutex)) && \
382 ((rc) = mdb_mutex_failed(env, mutex, rc)))
383 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
385 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
386 #define mdb_mutex_failed(env, mutex, rc) (rc)
390 /** A flag for opening a file and requesting synchronous data writes.
391 * This is only used when writing a meta page. It's not strictly needed;
392 * we could just do a normal write and then immediately perform a flush.
393 * But if this flag is available it saves us an extra system call.
395 * @note If O_DSYNC is undefined but exists in /usr/include,
396 * preferably set some compiler flag to get the definition.
397 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
400 # define MDB_DSYNC O_DSYNC
404 /** Function for flushing the data of a file. Define this to fsync
405 * if fdatasync() is not supported.
407 #ifndef MDB_FDATASYNC
408 # define MDB_FDATASYNC fdatasync
412 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
423 /** A page number in the database.
424 * Note that 64 bit page numbers are overkill, since pages themselves
425 * already represent 12-13 bits of addressable memory, and the OS will
426 * always limit applications to a maximum of 63 bits of address space.
428 * @note In the #MDB_node structure, we only store 48 bits of this value,
429 * which thus limits us to only 60 bits of addressable data.
431 typedef MDB_ID pgno_t;
433 /** A transaction ID.
434 * See struct MDB_txn.mt_txnid for details.
436 typedef MDB_ID txnid_t;
438 /** @defgroup debug Debug Macros
442 /** Enable debug output. Needs variable argument macros (a C99 feature).
443 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
444 * read from and written to the database (used for free space management).
450 static int mdb_debug;
451 static txnid_t mdb_debug_start;
453 /** Print a debug message with printf formatting.
454 * Requires double parenthesis around 2 or more args.
456 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
457 # define DPRINTF0(fmt, ...) \
458 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
460 # define DPRINTF(args) ((void) 0)
462 /** Print a debug string.
463 * The string is printed literally, with no format processing.
465 #define DPUTS(arg) DPRINTF(("%s", arg))
466 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
468 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
471 /** @brief The maximum size of a database page.
473 * It is 32k or 64k, since value-PAGEBASE must fit in
474 * #MDB_page.%mp_upper.
476 * LMDB will use database pages < OS pages if needed.
477 * That causes more I/O in write transactions: The OS must
478 * know (read) the whole page before writing a partial page.
480 * Note that we don't currently support Huge pages. On Linux,
481 * regular data files cannot use Huge pages, and in general
482 * Huge pages aren't actually pageable. We rely on the OS
483 * demand-pager to read our data and page it out when memory
484 * pressure from other processes is high. So until OSs have
485 * actual paging support for Huge pages, they're not viable.
487 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
489 /** The minimum number of keys required in a database page.
490 * Setting this to a larger value will place a smaller bound on the
491 * maximum size of a data item. Data items larger than this size will
492 * be pushed into overflow pages instead of being stored directly in
493 * the B-tree node. This value used to default to 4. With a page size
494 * of 4096 bytes that meant that any item larger than 1024 bytes would
495 * go into an overflow page. That also meant that on average 2-3KB of
496 * each overflow page was wasted space. The value cannot be lower than
497 * 2 because then there would no longer be a tree structure. With this
498 * value, items larger than 2KB will go into overflow pages, and on
499 * average only 1KB will be wasted.
501 #define MDB_MINKEYS 2
503 /** A stamp that identifies a file as an LMDB file.
504 * There's nothing special about this value other than that it is easily
505 * recognizable, and it will reflect any byte order mismatches.
507 #define MDB_MAGIC 0xBEEFC0DE
509 /** The version number for a database's datafile format. */
510 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
511 /** The version number for a database's lockfile format. */
512 #define MDB_LOCK_VERSION 1
514 /** @brief The max size of a key we can write, or 0 for computed max.
516 * This macro should normally be left alone or set to 0.
517 * Note that a database with big keys or dupsort data cannot be
518 * reliably modified by a liblmdb which uses a smaller max.
519 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
521 * Other values are allowed, for backwards compat. However:
522 * A value bigger than the computed max can break if you do not
523 * know what you are doing, and liblmdb <= 0.9.10 can break when
524 * modifying a DB with keys/dupsort data bigger than its max.
526 * Data items in an #MDB_DUPSORT database are also limited to
527 * this size, since they're actually keys of a sub-DB. Keys and
528 * #MDB_DUPSORT data items must fit on a node in a regular page.
530 #ifndef MDB_MAXKEYSIZE
531 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
534 /** The maximum size of a key we can write to the environment. */
536 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
538 #define ENV_MAXKEY(env) ((env)->me_maxkey)
541 /** @brief The maximum size of a data item.
543 * We only store a 32 bit value for node sizes.
545 #define MAXDATASIZE 0xffffffffUL
548 /** Key size which fits in a #DKBUF.
551 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
554 * This is used for printing a hex dump of a key's contents.
556 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
557 /** Display a key in hex.
559 * Invoke a function to display a key in hex.
561 #define DKEY(x) mdb_dkey(x, kbuf)
567 /** An invalid page number.
568 * Mainly used to denote an empty tree.
570 #define P_INVALID (~(pgno_t)0)
572 /** Test if the flags \b f are set in a flag word \b w. */
573 #define F_ISSET(w, f) (((w) & (f)) == (f))
575 /** Round \b n up to an even number. */
576 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
578 /** Used for offsets within a single page.
579 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
582 typedef uint16_t indx_t;
584 /** Default size of memory map.
585 * This is certainly too small for any actual applications. Apps should always set
586 * the size explicitly using #mdb_env_set_mapsize().
588 #define DEFAULT_MAPSIZE 1048576
590 /** @defgroup readers Reader Lock Table
591 * Readers don't acquire any locks for their data access. Instead, they
592 * simply record their transaction ID in the reader table. The reader
593 * mutex is needed just to find an empty slot in the reader table. The
594 * slot's address is saved in thread-specific data so that subsequent read
595 * transactions started by the same thread need no further locking to proceed.
597 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
599 * No reader table is used if the database is on a read-only filesystem, or
600 * if #MDB_NOLOCK is set.
602 * Since the database uses multi-version concurrency control, readers don't
603 * actually need any locking. This table is used to keep track of which
604 * readers are using data from which old transactions, so that we'll know
605 * when a particular old transaction is no longer in use. Old transactions
606 * that have discarded any data pages can then have those pages reclaimed
607 * for use by a later write transaction.
609 * The lock table is constructed such that reader slots are aligned with the
610 * processor's cache line size. Any slot is only ever used by one thread.
611 * This alignment guarantees that there will be no contention or cache
612 * thrashing as threads update their own slot info, and also eliminates
613 * any need for locking when accessing a slot.
615 * A writer thread will scan every slot in the table to determine the oldest
616 * outstanding reader transaction. Any freed pages older than this will be
617 * reclaimed by the writer. The writer doesn't use any locks when scanning
618 * this table. This means that there's no guarantee that the writer will
619 * see the most up-to-date reader info, but that's not required for correct
620 * operation - all we need is to know the upper bound on the oldest reader,
621 * we don't care at all about the newest reader. So the only consequence of
622 * reading stale information here is that old pages might hang around a
623 * while longer before being reclaimed. That's actually good anyway, because
624 * the longer we delay reclaiming old pages, the more likely it is that a
625 * string of contiguous pages can be found after coalescing old pages from
626 * many old transactions together.
629 /** Number of slots in the reader table.
630 * This value was chosen somewhat arbitrarily. 126 readers plus a
631 * couple mutexes fit exactly into 8KB on my development machine.
632 * Applications should set the table size using #mdb_env_set_maxreaders().
634 #define DEFAULT_READERS 126
636 /** The size of a CPU cache line in bytes. We want our lock structures
637 * aligned to this size to avoid false cache line sharing in the
639 * This value works for most CPUs. For Itanium this should be 128.
645 /** The information we store in a single slot of the reader table.
646 * In addition to a transaction ID, we also record the process and
647 * thread ID that owns a slot, so that we can detect stale information,
648 * e.g. threads or processes that went away without cleaning up.
649 * @note We currently don't check for stale records. We simply re-init
650 * the table when we know that we're the only process opening the
653 typedef struct MDB_rxbody {
654 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
655 * Multiple readers that start at the same time will probably have the
656 * same ID here. Again, it's not important to exclude them from
657 * anything; all we need to know is which version of the DB they
658 * started from so we can avoid overwriting any data used in that
659 * particular version.
661 volatile txnid_t mrb_txnid;
662 /** The process ID of the process owning this reader txn. */
663 volatile MDB_PID_T mrb_pid;
664 /** The thread ID of the thread owning this txn. */
665 volatile MDB_THR_T mrb_tid;
668 /** The actual reader record, with cacheline padding. */
669 typedef struct MDB_reader {
672 /** shorthand for mrb_txnid */
673 #define mr_txnid mru.mrx.mrb_txnid
674 #define mr_pid mru.mrx.mrb_pid
675 #define mr_tid mru.mrx.mrb_tid
676 /** cache line alignment */
677 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
681 /** The header for the reader table.
682 * The table resides in a memory-mapped file. (This is a different file
683 * than is used for the main database.)
685 * For POSIX the actual mutexes reside in the shared memory of this
686 * mapped file. On Windows, mutexes are named objects allocated by the
687 * kernel; we store the mutex names in this mapped file so that other
688 * processes can grab them. This same approach is also used on
689 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
690 * process-shared POSIX mutexes. For these cases where a named object
691 * is used, the object name is derived from a 64 bit FNV hash of the
692 * environment pathname. As such, naming collisions are extremely
693 * unlikely. If a collision occurs, the results are unpredictable.
695 typedef struct MDB_txbody {
696 /** Stamp identifying this as an LMDB file. It must be set
699 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
701 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
702 char mtb_rmname[MNAME_LEN];
704 /** Mutex protecting access to this table.
705 * This is the reader table lock used with LOCK_MUTEX().
707 mdb_mutex_t mtb_rmutex;
709 /** The ID of the last transaction committed to the database.
710 * This is recorded here only for convenience; the value can always
711 * be determined by reading the main database meta pages.
713 volatile txnid_t mtb_txnid;
714 /** The number of slots that have been used in the reader table.
715 * This always records the maximum count, it is not decremented
716 * when readers release their slots.
718 volatile unsigned mtb_numreaders;
721 /** The actual reader table definition. */
722 typedef struct MDB_txninfo {
725 #define mti_magic mt1.mtb.mtb_magic
726 #define mti_format mt1.mtb.mtb_format
727 #define mti_rmutex mt1.mtb.mtb_rmutex
728 #define mti_rmname mt1.mtb.mtb_rmname
729 #define mti_txnid mt1.mtb.mtb_txnid
730 #define mti_numreaders mt1.mtb.mtb_numreaders
731 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
734 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
735 char mt2_wmname[MNAME_LEN];
736 #define mti_wmname mt2.mt2_wmname
738 mdb_mutex_t mt2_wmutex;
739 #define mti_wmutex mt2.mt2_wmutex
741 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
743 MDB_reader mti_readers[1];
746 /** Lockfile format signature: version, features and field layout */
747 #define MDB_LOCK_FORMAT \
749 ((MDB_LOCK_VERSION) \
750 /* Flags which describe functionality */ \
751 + (((MDB_PIDLOCK) != 0) << 16)))
754 /** Common header for all page types.
755 * Overflow records occupy a number of contiguous pages with no
756 * headers on any page after the first.
758 typedef struct MDB_page {
759 #define mp_pgno mp_p.p_pgno
760 #define mp_next mp_p.p_next
762 pgno_t p_pgno; /**< page number */
763 struct MDB_page *p_next; /**< for in-memory list of freed pages */
766 /** @defgroup mdb_page Page Flags
768 * Flags for the page headers.
771 #define P_BRANCH 0x01 /**< branch page */
772 #define P_LEAF 0x02 /**< leaf page */
773 #define P_OVERFLOW 0x04 /**< overflow page */
774 #define P_META 0x08 /**< meta page */
775 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
776 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
777 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
778 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
779 #define P_KEEP 0x8000 /**< leave this page alone during spill */
781 uint16_t mp_flags; /**< @ref mdb_page */
782 #define mp_lower mp_pb.pb.pb_lower
783 #define mp_upper mp_pb.pb.pb_upper
784 #define mp_pages mp_pb.pb_pages
787 indx_t pb_lower; /**< lower bound of free space */
788 indx_t pb_upper; /**< upper bound of free space */
790 uint32_t pb_pages; /**< number of overflow pages */
792 indx_t mp_ptrs[1]; /**< dynamic size */
795 /** Size of the page header, excluding dynamic data at the end */
796 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
798 /** Address of first usable data byte in a page, after the header */
799 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
801 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
802 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
804 /** Number of nodes on a page */
805 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
807 /** The amount of space remaining in the page */
808 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
810 /** The percentage of space used in the page, in tenths of a percent. */
811 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
812 ((env)->me_psize - PAGEHDRSZ))
813 /** The minimum page fill factor, in tenths of a percent.
814 * Pages emptier than this are candidates for merging.
816 #define FILL_THRESHOLD 250
818 /** Test if a page is a leaf page */
819 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
820 /** Test if a page is a LEAF2 page */
821 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
822 /** Test if a page is a branch page */
823 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
824 /** Test if a page is an overflow page */
825 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
826 /** Test if a page is a sub page */
827 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
829 /** The number of overflow pages needed to store the given size. */
830 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
832 /** Link in #MDB_txn.%mt_loose_pgs list */
833 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
835 /** Header for a single key/data pair within a page.
836 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
837 * We guarantee 2-byte alignment for 'MDB_node's.
839 typedef struct MDB_node {
840 /** lo and hi are used for data size on leaf nodes and for
841 * child pgno on branch nodes. On 64 bit platforms, flags
842 * is also used for pgno. (Branch nodes have no flags).
843 * They are in host byte order in case that lets some
844 * accesses be optimized into a 32-bit word access.
846 #if BYTE_ORDER == LITTLE_ENDIAN
847 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
849 unsigned short mn_hi, mn_lo;
851 /** @defgroup mdb_node Node Flags
853 * Flags for node headers.
856 #define F_BIGDATA 0x01 /**< data put on overflow page */
857 #define F_SUBDATA 0x02 /**< data is a sub-database */
858 #define F_DUPDATA 0x04 /**< data has duplicates */
860 /** valid flags for #mdb_node_add() */
861 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
864 unsigned short mn_flags; /**< @ref mdb_node */
865 unsigned short mn_ksize; /**< key size */
866 char mn_data[1]; /**< key and data are appended here */
869 /** Size of the node header, excluding dynamic data at the end */
870 #define NODESIZE offsetof(MDB_node, mn_data)
872 /** Bit position of top word in page number, for shifting mn_flags */
873 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
875 /** Size of a node in a branch page with a given key.
876 * This is just the node header plus the key, there is no data.
878 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
880 /** Size of a node in a leaf page with a given key and data.
881 * This is node header plus key plus data size.
883 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
885 /** Address of node \b i in page \b p */
886 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
888 /** Address of the key for the node */
889 #define NODEKEY(node) (void *)((node)->mn_data)
891 /** Address of the data for a node */
892 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
894 /** Get the page number pointed to by a branch node */
895 #define NODEPGNO(node) \
896 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
897 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
898 /** Set the page number in a branch node */
899 #define SETPGNO(node,pgno) do { \
900 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
901 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
903 /** Get the size of the data in a leaf node */
904 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
905 /** Set the size of the data for a leaf node */
906 #define SETDSZ(node,size) do { \
907 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
908 /** The size of a key in a node */
909 #define NODEKSZ(node) ((node)->mn_ksize)
911 /** Copy a page number from src to dst */
913 #define COPY_PGNO(dst,src) dst = src
915 #if SIZE_MAX > 4294967295UL
916 #define COPY_PGNO(dst,src) do { \
917 unsigned short *s, *d; \
918 s = (unsigned short *)&(src); \
919 d = (unsigned short *)&(dst); \
926 #define COPY_PGNO(dst,src) do { \
927 unsigned short *s, *d; \
928 s = (unsigned short *)&(src); \
929 d = (unsigned short *)&(dst); \
935 /** The address of a key in a LEAF2 page.
936 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
937 * There are no node headers, keys are stored contiguously.
939 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
941 /** Set the \b node's key into \b keyptr, if requested. */
942 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
943 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
945 /** Set the \b node's key into \b key. */
946 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
948 /** Information about a single database in the environment. */
949 typedef struct MDB_db {
950 uint32_t md_pad; /**< also ksize for LEAF2 pages */
951 uint16_t md_flags; /**< @ref mdb_dbi_open */
952 uint16_t md_depth; /**< depth of this tree */
953 pgno_t md_branch_pages; /**< number of internal pages */
954 pgno_t md_leaf_pages; /**< number of leaf pages */
955 pgno_t md_overflow_pages; /**< number of overflow pages */
956 size_t md_entries; /**< number of data items */
957 pgno_t md_root; /**< the root page of this tree */
960 /** mdb_dbi_open flags */
961 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
962 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
963 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
964 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
966 /** Handle for the DB used to track free pages. */
968 /** Handle for the default DB. */
970 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
973 /** Number of meta pages - also hardcoded elsewhere */
976 /** Meta page content.
977 * A meta page is the start point for accessing a database snapshot.
978 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
980 typedef struct MDB_meta {
981 /** Stamp identifying this as an LMDB file. It must be set
984 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
986 void *mm_address; /**< address for fixed mapping */
987 size_t mm_mapsize; /**< size of mmap region */
988 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
989 /** The size of pages used in this DB */
990 #define mm_psize mm_dbs[FREE_DBI].md_pad
991 /** Any persistent environment flags. @ref mdb_env */
992 #define mm_flags mm_dbs[FREE_DBI].md_flags
993 pgno_t mm_last_pg; /**< last used page in file */
994 volatile txnid_t mm_txnid; /**< txnid that committed this page */
997 /** Buffer for a stack-allocated meta page.
998 * The members define size and alignment, and silence type
999 * aliasing warnings. They are not used directly; that could
1000 * mean incorrectly using several union members in parallel.
1002 typedef union MDB_metabuf {
1005 char mm_pad[PAGEHDRSZ];
1010 /** Auxiliary DB info.
1011 * The information here is mostly static/read-only. There is
1012 * only a single copy of this record in the environment.
1014 typedef struct MDB_dbx {
1015 MDB_val md_name; /**< name of the database */
1016 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1017 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1018 MDB_rel_func *md_rel; /**< user relocate function */
1019 void *md_relctx; /**< user-provided context for md_rel */
1022 /** A database transaction.
1023 * Every operation requires a transaction handle.
1026 MDB_txn *mt_parent; /**< parent of a nested txn */
1027 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1029 pgno_t mt_next_pgno; /**< next unallocated page */
1030 /** The ID of this transaction. IDs are integers incrementing from 1.
1031 * Only committed write transactions increment the ID. If a transaction
1032 * aborts, the ID may be re-used by the next writer.
1035 MDB_env *mt_env; /**< the DB environment */
1036 /** The list of pages that became unused during this transaction.
1038 MDB_IDL mt_free_pgs;
1039 /** The list of loose pages that became unused and may be reused
1040 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1042 MDB_page *mt_loose_pgs;
1043 /* #Number of loose pages (#mt_loose_pgs) */
1045 /** The sorted list of dirty pages we temporarily wrote to disk
1046 * because the dirty list was full. page numbers in here are
1047 * shifted left by 1, deleted slots have the LSB set.
1049 MDB_IDL mt_spill_pgs;
1051 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1052 MDB_ID2L dirty_list;
1053 /** For read txns: This thread/txn's reader table slot, or NULL. */
1056 /** Array of records for each DB known in the environment. */
1058 /** Array of MDB_db records for each known DB */
1060 /** Array of sequence numbers for each DB handle */
1061 unsigned int *mt_dbiseqs;
1062 /** @defgroup mt_dbflag Transaction DB Flags
1066 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
1067 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1068 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1069 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1070 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1072 /** In write txns, array of cursors for each DB */
1073 MDB_cursor **mt_cursors;
1074 /** Array of flags for each DB */
1075 unsigned char *mt_dbflags;
1076 /** Number of DB records in use, or 0 when the txn is finished.
1077 * This number only ever increments until the txn finishes; we
1078 * don't decrement it when individual DB handles are closed.
1082 /** @defgroup mdb_txn Transaction Flags
1086 /** #mdb_txn_begin() flags */
1087 #define MDB_TXN_BEGIN_FLAGS MDB_RDONLY
1088 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1089 /* internal txn flags */
1090 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1091 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1092 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1093 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1094 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1095 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1096 /** most operations on the txn are currently illegal */
1097 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1099 unsigned int mt_flags; /**< @ref mdb_txn */
1100 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1101 * Includes ancestor txns' dirty pages not hidden by other txns'
1102 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1103 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1105 unsigned int mt_dirty_room;
1108 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1109 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1110 * raise this on a 64 bit machine.
1112 #define CURSOR_STACK 32
1116 /** Cursors are used for all DB operations.
1117 * A cursor holds a path of (page pointer, key index) from the DB
1118 * root to a position in the DB, plus other state. #MDB_DUPSORT
1119 * cursors include an xcursor to the current data item. Write txns
1120 * track their cursors and keep them up to date when data moves.
1121 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1122 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1125 /** Next cursor on this DB in this txn */
1126 MDB_cursor *mc_next;
1127 /** Backup of the original cursor if this cursor is a shadow */
1128 MDB_cursor *mc_backup;
1129 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1130 struct MDB_xcursor *mc_xcursor;
1131 /** The transaction that owns this cursor */
1133 /** The database handle this cursor operates on */
1135 /** The database record for this cursor */
1137 /** The database auxiliary record for this cursor */
1139 /** The @ref mt_dbflag for this database */
1140 unsigned char *mc_dbflag;
1141 unsigned short mc_snum; /**< number of pushed pages */
1142 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1143 /** @defgroup mdb_cursor Cursor Flags
1145 * Cursor state flags.
1148 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1149 #define C_EOF 0x02 /**< No more data */
1150 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1151 #define C_DEL 0x08 /**< last op was a cursor_del */
1152 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
1153 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1155 unsigned int mc_flags; /**< @ref mdb_cursor */
1156 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1157 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1160 /** Context for sorted-dup records.
1161 * We could have gone to a fully recursive design, with arbitrarily
1162 * deep nesting of sub-databases. But for now we only handle these
1163 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1165 typedef struct MDB_xcursor {
1166 /** A sub-cursor for traversing the Dup DB */
1167 MDB_cursor mx_cursor;
1168 /** The database record for this Dup DB */
1170 /** The auxiliary DB record for this Dup DB */
1172 /** The @ref mt_dbflag for this Dup DB */
1173 unsigned char mx_dbflag;
1176 /** State of FreeDB old pages, stored in the MDB_env */
1177 typedef struct MDB_pgstate {
1178 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1179 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1182 /** The database environment. */
1184 HANDLE me_fd; /**< The main data file */
1185 HANDLE me_lfd; /**< The lock file */
1186 HANDLE me_mfd; /**< just for writing the meta pages */
1187 /** Failed to update the meta page. Probably an I/O error. */
1188 #define MDB_FATAL_ERROR 0x80000000U
1189 /** Some fields are initialized. */
1190 #define MDB_ENV_ACTIVE 0x20000000U
1191 /** me_txkey is set */
1192 #define MDB_ENV_TXKEY 0x10000000U
1193 /** fdatasync is unreliable */
1194 #define MDB_FSYNCONLY 0x08000000U
1195 uint32_t me_flags; /**< @ref mdb_env */
1196 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1197 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1198 unsigned int me_maxreaders; /**< size of the reader table */
1199 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1200 volatile int me_close_readers;
1201 MDB_dbi me_numdbs; /**< number of DBs opened */
1202 MDB_dbi me_maxdbs; /**< size of the DB table */
1203 MDB_PID_T me_pid; /**< process ID of this env */
1204 char *me_path; /**< path to the DB files */
1205 char *me_map; /**< the memory map of the data file */
1206 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1207 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1208 void *me_pbuf; /**< scratch area for DUPSORT put() */
1209 MDB_txn *me_txn; /**< current write transaction */
1210 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1211 size_t me_mapsize; /**< size of the data memory map */
1212 off_t me_size; /**< current file size */
1213 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1214 MDB_dbx *me_dbxs; /**< array of static DB info */
1215 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1216 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1217 pthread_key_t me_txkey; /**< thread-key for readers */
1218 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1219 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1220 # define me_pglast me_pgstate.mf_pglast
1221 # define me_pghead me_pgstate.mf_pghead
1222 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1223 /** IDL of pages that became unused in a write txn */
1224 MDB_IDL me_free_pgs;
1225 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1226 MDB_ID2L me_dirty_list;
1227 /** Max number of freelist items that can fit in a single overflow page */
1229 /** Max size of a node on a page */
1230 unsigned int me_nodemax;
1231 #if !(MDB_MAXKEYSIZE)
1232 unsigned int me_maxkey; /**< max size of a key */
1234 int me_live_reader; /**< have liveness lock in reader table */
1236 int me_pidquery; /**< Used in OpenProcess */
1238 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1239 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1240 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1242 mdb_mutex_t me_rmutex;
1243 mdb_mutex_t me_wmutex;
1245 void *me_userctx; /**< User-settable context */
1246 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1249 /** Nested transaction */
1250 typedef struct MDB_ntxn {
1251 MDB_txn mnt_txn; /**< the transaction */
1252 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1255 /** max number of pages to commit in one writev() call */
1256 #define MDB_COMMIT_PAGES 64
1257 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1258 #undef MDB_COMMIT_PAGES
1259 #define MDB_COMMIT_PAGES IOV_MAX
1262 /** max bytes to write in one call */
1263 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1265 /** Check \b txn and \b dbi arguments to a function */
1266 #define TXN_DBI_EXIST(txn, dbi, validity) \
1267 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1269 /** Check for misused \b dbi handles */
1270 #define TXN_DBI_CHANGED(txn, dbi) \
1271 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1273 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1274 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1275 static int mdb_page_touch(MDB_cursor *mc);
1277 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1278 "reset-tmp", "fail-begin", "fail-beginchild"}
1280 /* mdb_txn_end operation number, for logging */
1281 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1282 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1284 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1285 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1286 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1287 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1288 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1290 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1291 static int mdb_page_search_root(MDB_cursor *mc,
1292 MDB_val *key, int modify);
1293 #define MDB_PS_MODIFY 1
1294 #define MDB_PS_ROOTONLY 2
1295 #define MDB_PS_FIRST 4
1296 #define MDB_PS_LAST 8
1297 static int mdb_page_search(MDB_cursor *mc,
1298 MDB_val *key, int flags);
1299 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1301 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1302 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1303 pgno_t newpgno, unsigned int nflags);
1305 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1306 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1307 static int mdb_env_write_meta(MDB_txn *txn);
1308 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1309 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1311 static void mdb_env_close0(MDB_env *env, int excl);
1313 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1314 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1315 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1316 static void mdb_node_del(MDB_cursor *mc, int ksize);
1317 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1318 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1319 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1320 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1321 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1323 static int mdb_rebalance(MDB_cursor *mc);
1324 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1326 static void mdb_cursor_pop(MDB_cursor *mc);
1327 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1329 static int mdb_cursor_del0(MDB_cursor *mc);
1330 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1331 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1332 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1333 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1334 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1336 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1337 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1339 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1340 static void mdb_xcursor_init0(MDB_cursor *mc);
1341 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1342 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1344 static int mdb_drop0(MDB_cursor *mc, int subs);
1345 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1346 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1349 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1352 /** Compare two items pointing at size_t's of unknown alignment. */
1353 #ifdef MISALIGNED_OK
1354 # define mdb_cmp_clong mdb_cmp_long
1356 # define mdb_cmp_clong mdb_cmp_cint
1360 static SECURITY_DESCRIPTOR mdb_null_sd;
1361 static SECURITY_ATTRIBUTES mdb_all_sa;
1362 static int mdb_sec_inited;
1365 /** Return the library version info. */
1367 mdb_version(int *major, int *minor, int *patch)
1369 if (major) *major = MDB_VERSION_MAJOR;
1370 if (minor) *minor = MDB_VERSION_MINOR;
1371 if (patch) *patch = MDB_VERSION_PATCH;
1372 return MDB_VERSION_STRING;
1375 /** Table of descriptions for LMDB @ref errors */
1376 static char *const mdb_errstr[] = {
1377 "MDB_KEYEXIST: Key/data pair already exists",
1378 "MDB_NOTFOUND: No matching key/data pair found",
1379 "MDB_PAGE_NOTFOUND: Requested page not found",
1380 "MDB_CORRUPTED: Located page was wrong type",
1381 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1382 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1383 "MDB_INVALID: File is not an LMDB file",
1384 "MDB_MAP_FULL: Environment mapsize limit reached",
1385 "MDB_DBS_FULL: Environment maxdbs limit reached",
1386 "MDB_READERS_FULL: Environment maxreaders limit reached",
1387 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1388 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1389 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1390 "MDB_PAGE_FULL: Internal error - page has no more space",
1391 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1392 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1393 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1394 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1395 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1396 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1400 mdb_strerror(int err)
1403 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1404 * This works as long as no function between the call to mdb_strerror
1405 * and the actual use of the message uses more than 4K of stack.
1408 char buf[1024], *ptr = buf;
1412 return ("Successful return: 0");
1414 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1415 i = err - MDB_KEYEXIST;
1416 return mdb_errstr[i];
1420 /* These are the C-runtime error codes we use. The comment indicates
1421 * their numeric value, and the Win32 error they would correspond to
1422 * if the error actually came from a Win32 API. A major mess, we should
1423 * have used LMDB-specific error codes for everything.
1426 case ENOENT: /* 2, FILE_NOT_FOUND */
1427 case EIO: /* 5, ACCESS_DENIED */
1428 case ENOMEM: /* 12, INVALID_ACCESS */
1429 case EACCES: /* 13, INVALID_DATA */
1430 case EBUSY: /* 16, CURRENT_DIRECTORY */
1431 case EINVAL: /* 22, BAD_COMMAND */
1432 case ENOSPC: /* 28, OUT_OF_PAPER */
1433 return strerror(err);
1438 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1439 FORMAT_MESSAGE_IGNORE_INSERTS,
1440 NULL, err, 0, ptr, sizeof(buf), (va_list *)pad);
1443 return strerror(err);
1447 /** assert(3) variant in cursor context */
1448 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1449 /** assert(3) variant in transaction context */
1450 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1451 /** assert(3) variant in environment context */
1452 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1455 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1456 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1459 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1460 const char *func, const char *file, int line)
1463 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1464 file, line, expr_txt, func);
1465 if (env->me_assert_func)
1466 env->me_assert_func(env, buf);
1467 fprintf(stderr, "%s\n", buf);
1471 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1475 /** Return the page number of \b mp which may be sub-page, for debug output */
1477 mdb_dbg_pgno(MDB_page *mp)
1480 COPY_PGNO(ret, mp->mp_pgno);
1484 /** Display a key in hexadecimal and return the address of the result.
1485 * @param[in] key the key to display
1486 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1487 * @return The key in hexadecimal form.
1490 mdb_dkey(MDB_val *key, char *buf)
1493 unsigned char *c = key->mv_data;
1499 if (key->mv_size > DKBUF_MAXKEYSIZE)
1500 return "MDB_MAXKEYSIZE";
1501 /* may want to make this a dynamic check: if the key is mostly
1502 * printable characters, print it as-is instead of converting to hex.
1506 for (i=0; i<key->mv_size; i++)
1507 ptr += sprintf(ptr, "%02x", *c++);
1509 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1515 mdb_leafnode_type(MDB_node *n)
1517 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1518 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1519 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1522 /** Display all the keys in the page. */
1524 mdb_page_list(MDB_page *mp)
1526 pgno_t pgno = mdb_dbg_pgno(mp);
1527 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1529 unsigned int i, nkeys, nsize, total = 0;
1533 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1534 case P_BRANCH: type = "Branch page"; break;
1535 case P_LEAF: type = "Leaf page"; break;
1536 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1537 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1538 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1540 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1541 pgno, mp->mp_pages, state);
1544 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1545 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1548 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1552 nkeys = NUMKEYS(mp);
1553 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1555 for (i=0; i<nkeys; i++) {
1556 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1557 key.mv_size = nsize = mp->mp_pad;
1558 key.mv_data = LEAF2KEY(mp, i, nsize);
1560 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1563 node = NODEPTR(mp, i);
1564 key.mv_size = node->mn_ksize;
1565 key.mv_data = node->mn_data;
1566 nsize = NODESIZE + key.mv_size;
1567 if (IS_BRANCH(mp)) {
1568 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1572 if (F_ISSET(node->mn_flags, F_BIGDATA))
1573 nsize += sizeof(pgno_t);
1575 nsize += NODEDSZ(node);
1577 nsize += sizeof(indx_t);
1578 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1579 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1581 total = EVEN(total);
1583 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1584 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1588 mdb_cursor_chk(MDB_cursor *mc)
1594 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1595 for (i=0; i<mc->mc_top; i++) {
1597 node = NODEPTR(mp, mc->mc_ki[i]);
1598 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1601 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1607 /** Count all the pages in each DB and in the freelist
1608 * and make sure it matches the actual number of pages
1610 * All named DBs must be open for a correct count.
1612 static void mdb_audit(MDB_txn *txn)
1616 MDB_ID freecount, count;
1621 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1622 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1623 freecount += *(MDB_ID *)data.mv_data;
1624 mdb_tassert(txn, rc == MDB_NOTFOUND);
1627 for (i = 0; i<txn->mt_numdbs; i++) {
1629 if (!(txn->mt_dbflags[i] & DB_VALID))
1631 mdb_cursor_init(&mc, txn, i, &mx);
1632 if (txn->mt_dbs[i].md_root == P_INVALID)
1634 count += txn->mt_dbs[i].md_branch_pages +
1635 txn->mt_dbs[i].md_leaf_pages +
1636 txn->mt_dbs[i].md_overflow_pages;
1637 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1638 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1639 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1642 mp = mc.mc_pg[mc.mc_top];
1643 for (j=0; j<NUMKEYS(mp); j++) {
1644 MDB_node *leaf = NODEPTR(mp, j);
1645 if (leaf->mn_flags & F_SUBDATA) {
1647 memcpy(&db, NODEDATA(leaf), sizeof(db));
1648 count += db.md_branch_pages + db.md_leaf_pages +
1649 db.md_overflow_pages;
1653 mdb_tassert(txn, rc == MDB_NOTFOUND);
1656 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1657 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1658 txn->mt_txnid, freecount, count+NUM_METAS,
1659 freecount+count+NUM_METAS, txn->mt_next_pgno);
1665 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1667 return txn->mt_dbxs[dbi].md_cmp(a, b);
1671 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1673 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1674 #if UINT_MAX < SIZE_MAX
1675 if (dcmp == mdb_cmp_int && a->mv_size == sizeof(size_t))
1676 dcmp = mdb_cmp_clong;
1681 /** Allocate memory for a page.
1682 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1685 mdb_page_malloc(MDB_txn *txn, unsigned num)
1687 MDB_env *env = txn->mt_env;
1688 MDB_page *ret = env->me_dpages;
1689 size_t psize = env->me_psize, sz = psize, off;
1690 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1691 * For a single page alloc, we init everything after the page header.
1692 * For multi-page, we init the final page; if the caller needed that
1693 * many pages they will be filling in at least up to the last page.
1697 VGMEMP_ALLOC(env, ret, sz);
1698 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1699 env->me_dpages = ret->mp_next;
1702 psize -= off = PAGEHDRSZ;
1707 if ((ret = malloc(sz)) != NULL) {
1708 VGMEMP_ALLOC(env, ret, sz);
1709 if (!(env->me_flags & MDB_NOMEMINIT)) {
1710 memset((char *)ret + off, 0, psize);
1714 txn->mt_flags |= MDB_TXN_ERROR;
1718 /** Free a single page.
1719 * Saves single pages to a list, for future reuse.
1720 * (This is not used for multi-page overflow pages.)
1723 mdb_page_free(MDB_env *env, MDB_page *mp)
1725 mp->mp_next = env->me_dpages;
1726 VGMEMP_FREE(env, mp);
1727 env->me_dpages = mp;
1730 /** Free a dirty page */
1732 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1734 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1735 mdb_page_free(env, dp);
1737 /* large pages just get freed directly */
1738 VGMEMP_FREE(env, dp);
1743 /** Return all dirty pages to dpage list */
1745 mdb_dlist_free(MDB_txn *txn)
1747 MDB_env *env = txn->mt_env;
1748 MDB_ID2L dl = txn->mt_u.dirty_list;
1749 unsigned i, n = dl[0].mid;
1751 for (i = 1; i <= n; i++) {
1752 mdb_dpage_free(env, dl[i].mptr);
1757 /** Loosen or free a single page.
1758 * Saves single pages to a list for future reuse
1759 * in this same txn. It has been pulled from the freeDB
1760 * and already resides on the dirty list, but has been
1761 * deleted. Use these pages first before pulling again
1764 * If the page wasn't dirtied in this txn, just add it
1765 * to this txn's free list.
1768 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1771 pgno_t pgno = mp->mp_pgno;
1772 MDB_txn *txn = mc->mc_txn;
1774 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1775 if (txn->mt_parent) {
1776 MDB_ID2 *dl = txn->mt_u.dirty_list;
1777 /* If txn has a parent, make sure the page is in our
1781 unsigned x = mdb_mid2l_search(dl, pgno);
1782 if (x <= dl[0].mid && dl[x].mid == pgno) {
1783 if (mp != dl[x].mptr) { /* bad cursor? */
1784 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1785 txn->mt_flags |= MDB_TXN_ERROR;
1786 return MDB_CORRUPTED;
1793 /* no parent txn, so it's just ours */
1798 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1800 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1801 txn->mt_loose_pgs = mp;
1802 txn->mt_loose_count++;
1803 mp->mp_flags |= P_LOOSE;
1805 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1813 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1814 * @param[in] mc A cursor handle for the current operation.
1815 * @param[in] pflags Flags of the pages to update:
1816 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1817 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1818 * @return 0 on success, non-zero on failure.
1821 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1823 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1824 MDB_txn *txn = mc->mc_txn;
1830 int rc = MDB_SUCCESS, level;
1832 /* Mark pages seen by cursors */
1833 if (mc->mc_flags & C_UNTRACK)
1834 mc = NULL; /* will find mc in mt_cursors */
1835 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1836 for (; mc; mc=mc->mc_next) {
1837 if (!(mc->mc_flags & C_INITIALIZED))
1839 for (m3 = mc;; m3 = &mx->mx_cursor) {
1841 for (j=0; j<m3->mc_snum; j++) {
1843 if ((mp->mp_flags & Mask) == pflags)
1844 mp->mp_flags ^= P_KEEP;
1846 mx = m3->mc_xcursor;
1847 /* Proceed to mx if it is at a sub-database */
1848 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1850 if (! (mp && (mp->mp_flags & P_LEAF)))
1852 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1853 if (!(leaf->mn_flags & F_SUBDATA))
1862 /* Mark dirty root pages */
1863 for (i=0; i<txn->mt_numdbs; i++) {
1864 if (txn->mt_dbflags[i] & DB_DIRTY) {
1865 pgno_t pgno = txn->mt_dbs[i].md_root;
1866 if (pgno == P_INVALID)
1868 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1870 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1871 dp->mp_flags ^= P_KEEP;
1879 static int mdb_page_flush(MDB_txn *txn, int keep);
1881 /** Spill pages from the dirty list back to disk.
1882 * This is intended to prevent running into #MDB_TXN_FULL situations,
1883 * but note that they may still occur in a few cases:
1884 * 1) our estimate of the txn size could be too small. Currently this
1885 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1886 * 2) child txns may run out of space if their parents dirtied a
1887 * lot of pages and never spilled them. TODO: we probably should do
1888 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1889 * the parent's dirty_room is below a given threshold.
1891 * Otherwise, if not using nested txns, it is expected that apps will
1892 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1893 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1894 * If the txn never references them again, they can be left alone.
1895 * If the txn only reads them, they can be used without any fuss.
1896 * If the txn writes them again, they can be dirtied immediately without
1897 * going thru all of the work of #mdb_page_touch(). Such references are
1898 * handled by #mdb_page_unspill().
1900 * Also note, we never spill DB root pages, nor pages of active cursors,
1901 * because we'll need these back again soon anyway. And in nested txns,
1902 * we can't spill a page in a child txn if it was already spilled in a
1903 * parent txn. That would alter the parent txns' data even though
1904 * the child hasn't committed yet, and we'd have no way to undo it if
1905 * the child aborted.
1907 * @param[in] m0 cursor A cursor handle identifying the transaction and
1908 * database for which we are checking space.
1909 * @param[in] key For a put operation, the key being stored.
1910 * @param[in] data For a put operation, the data being stored.
1911 * @return 0 on success, non-zero on failure.
1914 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1916 MDB_txn *txn = m0->mc_txn;
1918 MDB_ID2L dl = txn->mt_u.dirty_list;
1919 unsigned int i, j, need;
1922 if (m0->mc_flags & C_SUB)
1925 /* Estimate how much space this op will take */
1926 i = m0->mc_db->md_depth;
1927 /* Named DBs also dirty the main DB */
1928 if (m0->mc_dbi >= CORE_DBS)
1929 i += txn->mt_dbs[MAIN_DBI].md_depth;
1930 /* For puts, roughly factor in the key+data size */
1932 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1933 i += i; /* double it for good measure */
1936 if (txn->mt_dirty_room > i)
1939 if (!txn->mt_spill_pgs) {
1940 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1941 if (!txn->mt_spill_pgs)
1944 /* purge deleted slots */
1945 MDB_IDL sl = txn->mt_spill_pgs;
1946 unsigned int num = sl[0];
1948 for (i=1; i<=num; i++) {
1955 /* Preserve pages which may soon be dirtied again */
1956 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1959 /* Less aggressive spill - we originally spilled the entire dirty list,
1960 * with a few exceptions for cursor pages and DB root pages. But this
1961 * turns out to be a lot of wasted effort because in a large txn many
1962 * of those pages will need to be used again. So now we spill only 1/8th
1963 * of the dirty pages. Testing revealed this to be a good tradeoff,
1964 * better than 1/2, 1/4, or 1/10.
1966 if (need < MDB_IDL_UM_MAX / 8)
1967 need = MDB_IDL_UM_MAX / 8;
1969 /* Save the page IDs of all the pages we're flushing */
1970 /* flush from the tail forward, this saves a lot of shifting later on. */
1971 for (i=dl[0].mid; i && need; i--) {
1972 MDB_ID pn = dl[i].mid << 1;
1974 if (dp->mp_flags & (P_LOOSE|P_KEEP))
1976 /* Can't spill twice, make sure it's not already in a parent's
1979 if (txn->mt_parent) {
1981 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1982 if (tx2->mt_spill_pgs) {
1983 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1984 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1985 dp->mp_flags |= P_KEEP;
1993 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1997 mdb_midl_sort(txn->mt_spill_pgs);
1999 /* Flush the spilled part of dirty list */
2000 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2003 /* Reset any dirty pages we kept that page_flush didn't see */
2004 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2007 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2011 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2013 mdb_find_oldest(MDB_txn *txn)
2016 txnid_t mr, oldest = txn->mt_txnid - 1;
2017 if (txn->mt_env->me_txns) {
2018 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2019 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2030 /** Add a page to the txn's dirty list */
2032 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2035 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2037 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2038 insert = mdb_mid2l_append;
2040 insert = mdb_mid2l_insert;
2042 mid.mid = mp->mp_pgno;
2044 rc = insert(txn->mt_u.dirty_list, &mid);
2045 mdb_tassert(txn, rc == 0);
2046 txn->mt_dirty_room--;
2049 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2050 * me_pghead and mt_next_pgno.
2052 * If there are free pages available from older transactions, they
2053 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2054 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2055 * and move me_pglast to say which records were consumed. Only this
2056 * function can create me_pghead and move me_pglast/mt_next_pgno.
2057 * @param[in] mc cursor A cursor handle identifying the transaction and
2058 * database for which we are allocating.
2059 * @param[in] num the number of pages to allocate.
2060 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2061 * will always be satisfied by a single contiguous chunk of memory.
2062 * @return 0 on success, non-zero on failure.
2065 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2067 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2068 /* Get at most <Max_retries> more freeDB records once me_pghead
2069 * has enough pages. If not enough, use new pages from the map.
2070 * If <Paranoid> and mc is updating the freeDB, only get new
2071 * records if me_pghead is empty. Then the freelist cannot play
2072 * catch-up with itself by growing while trying to save it.
2074 enum { Paranoid = 1, Max_retries = 500 };
2076 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2078 int rc, retry = num * 60;
2079 MDB_txn *txn = mc->mc_txn;
2080 MDB_env *env = txn->mt_env;
2081 pgno_t pgno, *mop = env->me_pghead;
2082 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2084 txnid_t oldest = 0, last;
2089 /* If there are any loose pages, just use them */
2090 if (num == 1 && txn->mt_loose_pgs) {
2091 np = txn->mt_loose_pgs;
2092 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2093 txn->mt_loose_count--;
2094 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
2102 /* If our dirty list is already full, we can't do anything */
2103 if (txn->mt_dirty_room == 0) {
2108 for (op = MDB_FIRST;; op = MDB_NEXT) {
2113 /* Seek a big enough contiguous page range. Prefer
2114 * pages at the tail, just truncating the list.
2120 if (mop[i-n2] == pgno+n2)
2127 if (op == MDB_FIRST) { /* 1st iteration */
2128 /* Prepare to fetch more and coalesce */
2129 last = env->me_pglast;
2130 oldest = env->me_pgoldest;
2131 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2134 key.mv_data = &last; /* will look up last+1 */
2135 key.mv_size = sizeof(last);
2137 if (Paranoid && mc->mc_dbi == FREE_DBI)
2140 if (Paranoid && retry < 0 && mop_len)
2144 /* Do not fetch more if the record will be too recent */
2145 if (oldest <= last) {
2147 oldest = mdb_find_oldest(txn);
2148 env->me_pgoldest = oldest;
2154 rc = mdb_cursor_get(&m2, &key, NULL, op);
2156 if (rc == MDB_NOTFOUND)
2160 last = *(txnid_t*)key.mv_data;
2161 if (oldest <= last) {
2163 oldest = mdb_find_oldest(txn);
2164 env->me_pgoldest = oldest;
2170 np = m2.mc_pg[m2.mc_top];
2171 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2172 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
2175 idl = (MDB_ID *) data.mv_data;
2178 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2183 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2185 mop = env->me_pghead;
2187 env->me_pglast = last;
2189 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2190 last, txn->mt_dbs[FREE_DBI].md_root, i));
2192 DPRINTF(("IDL %"Z"u", idl[j]));
2194 /* Merge in descending sorted order */
2195 mdb_midl_xmerge(mop, idl);
2199 /* Use new pages from the map when nothing suitable in the freeDB */
2201 pgno = txn->mt_next_pgno;
2202 if (pgno + num >= env->me_maxpg) {
2203 DPUTS("DB size maxed out");
2209 if (env->me_flags & MDB_WRITEMAP) {
2210 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2212 if (!(np = mdb_page_malloc(txn, num))) {
2218 mop[0] = mop_len -= num;
2219 /* Move any stragglers down */
2220 for (j = i-num; j < mop_len; )
2221 mop[++j] = mop[++i];
2223 txn->mt_next_pgno = pgno + num;
2226 mdb_page_dirty(txn, np);
2232 txn->mt_flags |= MDB_TXN_ERROR;
2236 /** Copy the used portions of a non-overflow page.
2237 * @param[in] dst page to copy into
2238 * @param[in] src page to copy from
2239 * @param[in] psize size of a page
2242 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2244 enum { Align = sizeof(pgno_t) };
2245 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2247 /* If page isn't full, just copy the used portion. Adjust
2248 * alignment so memcpy may copy words instead of bytes.
2250 if ((unused &= -Align) && !IS_LEAF2(src)) {
2251 upper = (upper + PAGEBASE) & -Align;
2252 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2253 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2256 memcpy(dst, src, psize - unused);
2260 /** Pull a page off the txn's spill list, if present.
2261 * If a page being referenced was spilled to disk in this txn, bring
2262 * it back and make it dirty/writable again.
2263 * @param[in] txn the transaction handle.
2264 * @param[in] mp the page being referenced. It must not be dirty.
2265 * @param[out] ret the writable page, if any. ret is unchanged if
2266 * mp wasn't spilled.
2269 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2271 MDB_env *env = txn->mt_env;
2274 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2276 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2277 if (!tx2->mt_spill_pgs)
2279 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2280 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2283 if (txn->mt_dirty_room == 0)
2284 return MDB_TXN_FULL;
2285 if (IS_OVERFLOW(mp))
2289 if (env->me_flags & MDB_WRITEMAP) {
2292 np = mdb_page_malloc(txn, num);
2296 memcpy(np, mp, num * env->me_psize);
2298 mdb_page_copy(np, mp, env->me_psize);
2301 /* If in current txn, this page is no longer spilled.
2302 * If it happens to be the last page, truncate the spill list.
2303 * Otherwise mark it as deleted by setting the LSB.
2305 if (x == txn->mt_spill_pgs[0])
2306 txn->mt_spill_pgs[0]--;
2308 txn->mt_spill_pgs[x] |= 1;
2309 } /* otherwise, if belonging to a parent txn, the
2310 * page remains spilled until child commits
2313 mdb_page_dirty(txn, np);
2314 np->mp_flags |= P_DIRTY;
2322 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2323 * @param[in] mc cursor pointing to the page to be touched
2324 * @return 0 on success, non-zero on failure.
2327 mdb_page_touch(MDB_cursor *mc)
2329 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2330 MDB_txn *txn = mc->mc_txn;
2331 MDB_cursor *m2, *m3;
2335 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2336 if (txn->mt_flags & MDB_TXN_SPILLS) {
2338 rc = mdb_page_unspill(txn, mp, &np);
2344 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2345 (rc = mdb_page_alloc(mc, 1, &np)))
2348 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2349 mp->mp_pgno, pgno));
2350 mdb_cassert(mc, mp->mp_pgno != pgno);
2351 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2352 /* Update the parent page, if any, to point to the new page */
2354 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2355 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2356 SETPGNO(node, pgno);
2358 mc->mc_db->md_root = pgno;
2360 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2361 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2363 /* If txn has a parent, make sure the page is in our
2367 unsigned x = mdb_mid2l_search(dl, pgno);
2368 if (x <= dl[0].mid && dl[x].mid == pgno) {
2369 if (mp != dl[x].mptr) { /* bad cursor? */
2370 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2371 txn->mt_flags |= MDB_TXN_ERROR;
2372 return MDB_CORRUPTED;
2377 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2379 np = mdb_page_malloc(txn, 1);
2384 rc = mdb_mid2l_insert(dl, &mid);
2385 mdb_cassert(mc, rc == 0);
2390 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2392 np->mp_flags |= P_DIRTY;
2395 /* Adjust cursors pointing to mp */
2396 mc->mc_pg[mc->mc_top] = np;
2397 m2 = txn->mt_cursors[mc->mc_dbi];
2398 if (mc->mc_flags & C_SUB) {
2399 for (; m2; m2=m2->mc_next) {
2400 m3 = &m2->mc_xcursor->mx_cursor;
2401 if (m3->mc_snum < mc->mc_snum) continue;
2402 if (m3->mc_pg[mc->mc_top] == mp)
2403 m3->mc_pg[mc->mc_top] = np;
2406 for (; m2; m2=m2->mc_next) {
2407 if (m2->mc_snum < mc->mc_snum) continue;
2408 if (m2->mc_pg[mc->mc_top] == mp) {
2409 m2->mc_pg[mc->mc_top] = np;
2410 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2412 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2414 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2415 if (!(leaf->mn_flags & F_SUBDATA))
2416 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2424 txn->mt_flags |= MDB_TXN_ERROR;
2429 mdb_env_sync(MDB_env *env, int force)
2432 if (env->me_flags & MDB_RDONLY)
2434 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2435 if (env->me_flags & MDB_WRITEMAP) {
2436 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2437 ? MS_ASYNC : MS_SYNC;
2438 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2441 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2445 #ifdef BROKEN_FDATASYNC
2446 if (env->me_flags & MDB_FSYNCONLY) {
2447 if (fsync(env->me_fd))
2451 if (MDB_FDATASYNC(env->me_fd))
2458 /** Back up parent txn's cursors, then grab the originals for tracking */
2460 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2462 MDB_cursor *mc, *bk;
2467 for (i = src->mt_numdbs; --i >= 0; ) {
2468 if ((mc = src->mt_cursors[i]) != NULL) {
2469 size = sizeof(MDB_cursor);
2471 size += sizeof(MDB_xcursor);
2472 for (; mc; mc = bk->mc_next) {
2478 mc->mc_db = &dst->mt_dbs[i];
2479 /* Kill pointers into src - and dst to reduce abuse: The
2480 * user may not use mc until dst ends. Otherwise we'd...
2482 mc->mc_txn = NULL; /* ...set this to dst */
2483 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2484 if ((mx = mc->mc_xcursor) != NULL) {
2485 *(MDB_xcursor *)(bk+1) = *mx;
2486 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2488 mc->mc_next = dst->mt_cursors[i];
2489 dst->mt_cursors[i] = mc;
2496 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2497 * @param[in] txn the transaction handle.
2498 * @param[in] merge true to keep changes to parent cursors, false to revert.
2499 * @return 0 on success, non-zero on failure.
2502 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2504 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2508 for (i = txn->mt_numdbs; --i >= 0; ) {
2509 for (mc = cursors[i]; mc; mc = next) {
2511 if ((bk = mc->mc_backup) != NULL) {
2513 /* Commit changes to parent txn */
2514 mc->mc_next = bk->mc_next;
2515 mc->mc_backup = bk->mc_backup;
2516 mc->mc_txn = bk->mc_txn;
2517 mc->mc_db = bk->mc_db;
2518 mc->mc_dbflag = bk->mc_dbflag;
2519 if ((mx = mc->mc_xcursor) != NULL)
2520 mx->mx_cursor.mc_txn = bk->mc_txn;
2522 /* Abort nested txn */
2524 if ((mx = mc->mc_xcursor) != NULL)
2525 *mx = *(MDB_xcursor *)(bk+1);
2529 /* Only malloced cursors are permanently tracked. */
2536 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2542 Pidset = F_SETLK, Pidcheck = F_GETLK
2546 /** Set or check a pid lock. Set returns 0 on success.
2547 * Check returns 0 if the process is certainly dead, nonzero if it may
2548 * be alive (the lock exists or an error happened so we do not know).
2550 * On Windows Pidset is a no-op, we merely check for the existence
2551 * of the process with the given pid. On POSIX we use a single byte
2552 * lock on the lockfile, set at an offset equal to the pid.
2555 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2557 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2560 if (op == Pidcheck) {
2561 h = OpenProcess(env->me_pidquery, FALSE, pid);
2562 /* No documented "no such process" code, but other program use this: */
2564 return ErrCode() != ERROR_INVALID_PARAMETER;
2565 /* A process exists until all handles to it close. Has it exited? */
2566 ret = WaitForSingleObject(h, 0) != 0;
2573 struct flock lock_info;
2574 memset(&lock_info, 0, sizeof(lock_info));
2575 lock_info.l_type = F_WRLCK;
2576 lock_info.l_whence = SEEK_SET;
2577 lock_info.l_start = pid;
2578 lock_info.l_len = 1;
2579 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2580 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2582 } else if ((rc = ErrCode()) == EINTR) {
2590 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2591 * @param[in] txn the transaction handle to initialize
2592 * @return 0 on success, non-zero on failure.
2595 mdb_txn_renew0(MDB_txn *txn)
2597 MDB_env *env = txn->mt_env;
2598 MDB_txninfo *ti = env->me_txns;
2600 unsigned int i, nr, flags = txn->mt_flags;
2602 int rc, new_notls = 0;
2604 if ((flags &= MDB_TXN_RDONLY) != 0) {
2606 meta = mdb_env_pick_meta(env);
2607 txn->mt_txnid = meta->mm_txnid;
2608 txn->mt_u.reader = NULL;
2610 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2611 pthread_getspecific(env->me_txkey);
2613 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2614 return MDB_BAD_RSLOT;
2616 MDB_PID_T pid = env->me_pid;
2617 MDB_THR_T tid = pthread_self();
2618 mdb_mutexref_t rmutex = env->me_rmutex;
2620 if (!env->me_live_reader) {
2621 rc = mdb_reader_pid(env, Pidset, pid);
2624 env->me_live_reader = 1;
2627 if (LOCK_MUTEX(rc, env, rmutex))
2629 nr = ti->mti_numreaders;
2630 for (i=0; i<nr; i++)
2631 if (ti->mti_readers[i].mr_pid == 0)
2633 if (i == env->me_maxreaders) {
2634 UNLOCK_MUTEX(rmutex);
2635 return MDB_READERS_FULL;
2637 r = &ti->mti_readers[i];
2638 /* Claim the reader slot, carefully since other code
2639 * uses the reader table un-mutexed: First reset the
2640 * slot, next publish it in mti_numreaders. After
2641 * that, it is safe for mdb_env_close() to touch it.
2642 * When it will be closed, we can finally claim it.
2645 r->mr_txnid = (txnid_t)-1;
2648 ti->mti_numreaders = ++nr;
2649 env->me_close_readers = nr;
2651 UNLOCK_MUTEX(rmutex);
2653 new_notls = (env->me_flags & MDB_NOTLS);
2654 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2659 do /* LY: Retry on a race, ITS#7970. */
2660 r->mr_txnid = ti->mti_txnid;
2661 while(r->mr_txnid != ti->mti_txnid);
2662 txn->mt_txnid = r->mr_txnid;
2663 txn->mt_u.reader = r;
2664 meta = env->me_metas[txn->mt_txnid & 1];
2668 /* Not yet touching txn == env->me_txn0, it may be active */
2670 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2672 txn->mt_txnid = ti->mti_txnid;
2673 meta = env->me_metas[txn->mt_txnid & 1];
2675 meta = mdb_env_pick_meta(env);
2676 txn->mt_txnid = meta->mm_txnid;
2680 if (txn->mt_txnid == mdb_debug_start)
2683 txn->mt_child = NULL;
2684 txn->mt_loose_pgs = NULL;
2685 txn->mt_loose_count = 0;
2686 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2687 txn->mt_u.dirty_list = env->me_dirty_list;
2688 txn->mt_u.dirty_list[0].mid = 0;
2689 txn->mt_free_pgs = env->me_free_pgs;
2690 txn->mt_free_pgs[0] = 0;
2691 txn->mt_spill_pgs = NULL;
2693 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2696 /* Copy the DB info and flags */
2697 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
2699 /* Moved to here to avoid a data race in read TXNs */
2700 txn->mt_next_pgno = meta->mm_last_pg+1;
2702 txn->mt_flags = flags;
2705 txn->mt_numdbs = env->me_numdbs;
2706 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
2707 x = env->me_dbflags[i];
2708 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2709 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
2711 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
2712 txn->mt_dbflags[FREE_DBI] = DB_VALID;
2714 if (env->me_flags & MDB_FATAL_ERROR) {
2715 DPUTS("environment had fatal error, must shutdown!");
2717 } else if (env->me_maxpg < txn->mt_next_pgno) {
2718 rc = MDB_MAP_RESIZED;
2722 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
2727 mdb_txn_renew(MDB_txn *txn)
2731 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
2734 rc = mdb_txn_renew0(txn);
2735 if (rc == MDB_SUCCESS) {
2736 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2737 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2738 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2744 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2748 int rc, size, tsize;
2750 flags &= MDB_TXN_BEGIN_FLAGS;
2751 flags |= env->me_flags & MDB_WRITEMAP;
2753 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
2757 /* Nested transactions: Max 1 child, write txns only, no writemap */
2758 flags |= parent->mt_flags;
2759 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
2760 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2762 /* Child txns save MDB_pgstate and use own copy of cursors */
2763 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
2764 size += tsize = sizeof(MDB_ntxn);
2765 } else if (flags & MDB_RDONLY) {
2766 size = env->me_maxdbs * (sizeof(MDB_db)+1);
2767 size += tsize = sizeof(MDB_txn);
2769 /* Reuse preallocated write txn. However, do not touch it until
2770 * mdb_txn_renew0() succeeds, since it currently may be active.
2775 if ((txn = calloc(1, size)) == NULL) {
2776 DPRINTF(("calloc: %s", strerror(errno)));
2779 txn->mt_dbxs = env->me_dbxs; /* static */
2780 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2781 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
2782 txn->mt_flags = flags;
2787 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2788 txn->mt_dbiseqs = parent->mt_dbiseqs;
2789 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2790 if (!txn->mt_u.dirty_list ||
2791 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2793 free(txn->mt_u.dirty_list);
2797 txn->mt_txnid = parent->mt_txnid;
2798 txn->mt_dirty_room = parent->mt_dirty_room;
2799 txn->mt_u.dirty_list[0].mid = 0;
2800 txn->mt_spill_pgs = NULL;
2801 txn->mt_next_pgno = parent->mt_next_pgno;
2802 parent->mt_flags |= MDB_TXN_HAS_CHILD;
2803 parent->mt_child = txn;
2804 txn->mt_parent = parent;
2805 txn->mt_numdbs = parent->mt_numdbs;
2806 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2807 /* Copy parent's mt_dbflags, but clear DB_NEW */
2808 for (i=0; i<txn->mt_numdbs; i++)
2809 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2811 ntxn = (MDB_ntxn *)txn;
2812 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2813 if (env->me_pghead) {
2814 size = MDB_IDL_SIZEOF(env->me_pghead);
2815 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2817 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2822 rc = mdb_cursor_shadow(parent, txn);
2824 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
2825 } else { /* MDB_RDONLY */
2826 txn->mt_dbiseqs = env->me_dbiseqs;
2828 rc = mdb_txn_renew0(txn);
2831 if (txn != env->me_txn0)
2834 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
2836 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2837 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
2838 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2845 mdb_txn_env(MDB_txn *txn)
2847 if(!txn) return NULL;
2852 mdb_txn_id(MDB_txn *txn)
2855 return txn->mt_txnid;
2858 /** Export or close DBI handles opened in this txn. */
2860 mdb_dbis_update(MDB_txn *txn, int keep)
2863 MDB_dbi n = txn->mt_numdbs;
2864 MDB_env *env = txn->mt_env;
2865 unsigned char *tdbflags = txn->mt_dbflags;
2867 for (i = n; --i >= CORE_DBS;) {
2868 if (tdbflags[i] & DB_NEW) {
2870 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2872 char *ptr = env->me_dbxs[i].md_name.mv_data;
2874 env->me_dbxs[i].md_name.mv_data = NULL;
2875 env->me_dbxs[i].md_name.mv_size = 0;
2876 env->me_dbflags[i] = 0;
2877 env->me_dbiseqs[i]++;
2883 if (keep && env->me_numdbs < n)
2887 /** End a transaction, except successful commit of a nested transaction.
2888 * May be called twice for readonly txns: First reset it, then abort.
2889 * @param[in] txn the transaction handle to end
2890 * @param[in] mode why and how to end the transaction
2893 mdb_txn_end(MDB_txn *txn, unsigned mode)
2895 MDB_env *env = txn->mt_env;
2897 static const char *const names[] = MDB_END_NAMES;
2900 /* Export or close DBI handles opened in this txn */
2901 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
2903 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2904 names[mode & MDB_END_OPMASK],
2905 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2906 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2908 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2909 if (txn->mt_u.reader) {
2910 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2911 if (!(env->me_flags & MDB_NOTLS)) {
2912 txn->mt_u.reader = NULL; /* txn does not own reader */
2913 } else if (mode & MDB_END_SLOT) {
2914 txn->mt_u.reader->mr_pid = 0;
2915 txn->mt_u.reader = NULL;
2916 } /* else txn owns the slot until it does MDB_END_SLOT */
2918 txn->mt_numdbs = 0; /* prevent further DBI activity */
2919 txn->mt_flags |= MDB_TXN_FINISHED;
2921 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
2922 pgno_t *pghead = env->me_pghead;
2924 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
2925 mdb_cursors_close(txn, 0);
2926 if (!(env->me_flags & MDB_WRITEMAP)) {
2927 mdb_dlist_free(txn);
2931 txn->mt_flags = MDB_TXN_FINISHED;
2933 if (!txn->mt_parent) {
2934 mdb_midl_shrink(&txn->mt_free_pgs);
2935 env->me_free_pgs = txn->mt_free_pgs;
2937 env->me_pghead = NULL;
2941 mode = 0; /* txn == env->me_txn0, do not free() it */
2943 /* The writer mutex was locked in mdb_txn_begin. */
2945 UNLOCK_MUTEX(env->me_wmutex);
2947 txn->mt_parent->mt_child = NULL;
2948 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
2949 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2950 mdb_midl_free(txn->mt_free_pgs);
2951 mdb_midl_free(txn->mt_spill_pgs);
2952 free(txn->mt_u.dirty_list);
2955 mdb_midl_free(pghead);
2958 if (mode & MDB_END_FREE)
2963 mdb_txn_reset(MDB_txn *txn)
2968 /* This call is only valid for read-only txns */
2969 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2972 mdb_txn_end(txn, MDB_END_RESET);
2976 mdb_txn_abort(MDB_txn *txn)
2982 mdb_txn_abort(txn->mt_child);
2984 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
2987 /** Save the freelist as of this transaction to the freeDB.
2988 * This changes the freelist. Keep trying until it stabilizes.
2991 mdb_freelist_save(MDB_txn *txn)
2993 /* env->me_pghead[] can grow and shrink during this call.
2994 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2995 * Page numbers cannot disappear from txn->mt_free_pgs[].
2998 MDB_env *env = txn->mt_env;
2999 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3000 txnid_t pglast = 0, head_id = 0;
3001 pgno_t freecnt = 0, *free_pgs, *mop;
3002 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3004 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3006 if (env->me_pghead) {
3007 /* Make sure first page of freeDB is touched and on freelist */
3008 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3009 if (rc && rc != MDB_NOTFOUND)
3013 if (!env->me_pghead && txn->mt_loose_pgs) {
3014 /* Put loose page numbers in mt_free_pgs, since
3015 * we may be unable to return them to me_pghead.
3017 MDB_page *mp = txn->mt_loose_pgs;
3018 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3020 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3021 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3022 txn->mt_loose_pgs = NULL;
3023 txn->mt_loose_count = 0;
3026 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3027 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3028 ? SSIZE_MAX : maxfree_1pg;
3031 /* Come back here after each Put() in case freelist changed */
3036 /* If using records from freeDB which we have not yet
3037 * deleted, delete them and any we reserved for me_pghead.
3039 while (pglast < env->me_pglast) {
3040 rc = mdb_cursor_first(&mc, &key, NULL);
3043 pglast = head_id = *(txnid_t *)key.mv_data;
3044 total_room = head_room = 0;
3045 mdb_tassert(txn, pglast <= env->me_pglast);
3046 rc = mdb_cursor_del(&mc, 0);
3051 /* Save the IDL of pages freed by this txn, to a single record */
3052 if (freecnt < txn->mt_free_pgs[0]) {
3054 /* Make sure last page of freeDB is touched and on freelist */
3055 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3056 if (rc && rc != MDB_NOTFOUND)
3059 free_pgs = txn->mt_free_pgs;
3060 /* Write to last page of freeDB */
3061 key.mv_size = sizeof(txn->mt_txnid);
3062 key.mv_data = &txn->mt_txnid;
3064 freecnt = free_pgs[0];
3065 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3066 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3069 /* Retry if mt_free_pgs[] grew during the Put() */
3070 free_pgs = txn->mt_free_pgs;
3071 } while (freecnt < free_pgs[0]);
3072 mdb_midl_sort(free_pgs);
3073 memcpy(data.mv_data, free_pgs, data.mv_size);
3076 unsigned int i = free_pgs[0];
3077 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
3078 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3080 DPRINTF(("IDL %"Z"u", free_pgs[i]));
3086 mop = env->me_pghead;
3087 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3089 /* Reserve records for me_pghead[]. Split it if multi-page,
3090 * to avoid searching freeDB for a page range. Use keys in
3091 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3093 if (total_room >= mop_len) {
3094 if (total_room == mop_len || --more < 0)
3096 } else if (head_room >= maxfree_1pg && head_id > 1) {
3097 /* Keep current record (overflow page), add a new one */
3101 /* (Re)write {key = head_id, IDL length = head_room} */
3102 total_room -= head_room;
3103 head_room = mop_len - total_room;
3104 if (head_room > maxfree_1pg && head_id > 1) {
3105 /* Overflow multi-page for part of me_pghead */
3106 head_room /= head_id; /* amortize page sizes */
3107 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3108 } else if (head_room < 0) {
3109 /* Rare case, not bothering to delete this record */
3112 key.mv_size = sizeof(head_id);
3113 key.mv_data = &head_id;
3114 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3115 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3118 /* IDL is initially empty, zero out at least the length */
3119 pgs = (pgno_t *)data.mv_data;
3120 j = head_room > clean_limit ? head_room : 0;
3124 total_room += head_room;
3127 /* Return loose page numbers to me_pghead, though usually none are
3128 * left at this point. The pages themselves remain in dirty_list.
3130 if (txn->mt_loose_pgs) {
3131 MDB_page *mp = txn->mt_loose_pgs;
3132 unsigned count = txn->mt_loose_count;
3134 /* Room for loose pages + temp IDL with same */
3135 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3137 mop = env->me_pghead;
3138 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3139 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3140 loose[ ++count ] = mp->mp_pgno;
3142 mdb_midl_sort(loose);
3143 mdb_midl_xmerge(mop, loose);
3144 txn->mt_loose_pgs = NULL;
3145 txn->mt_loose_count = 0;
3149 /* Fill in the reserved me_pghead records */
3155 rc = mdb_cursor_first(&mc, &key, &data);
3156 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3157 txnid_t id = *(txnid_t *)key.mv_data;
3158 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3161 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3163 if (len > mop_len) {
3165 data.mv_size = (len + 1) * sizeof(MDB_ID);
3167 data.mv_data = mop -= len;
3170 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3172 if (rc || !(mop_len -= len))
3179 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3180 * @param[in] txn the transaction that's being committed
3181 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3182 * @return 0 on success, non-zero on failure.
3185 mdb_page_flush(MDB_txn *txn, int keep)
3187 MDB_env *env = txn->mt_env;
3188 MDB_ID2L dl = txn->mt_u.dirty_list;
3189 unsigned psize = env->me_psize, j;
3190 int i, pagecount = dl[0].mid, rc;
3191 size_t size = 0, pos = 0;
3193 MDB_page *dp = NULL;
3197 struct iovec iov[MDB_COMMIT_PAGES];
3198 ssize_t wpos = 0, wsize = 0, wres;
3199 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3205 if (env->me_flags & MDB_WRITEMAP) {
3206 /* Clear dirty flags */
3207 while (++i <= pagecount) {
3209 /* Don't flush this page yet */
3210 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3211 dp->mp_flags &= ~P_KEEP;
3215 dp->mp_flags &= ~P_DIRTY;
3220 /* Write the pages */
3222 if (++i <= pagecount) {
3224 /* Don't flush this page yet */
3225 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3226 dp->mp_flags &= ~P_KEEP;
3231 /* clear dirty flag */
3232 dp->mp_flags &= ~P_DIRTY;
3235 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3240 /* Windows actually supports scatter/gather I/O, but only on
3241 * unbuffered file handles. Since we're relying on the OS page
3242 * cache for all our data, that's self-defeating. So we just
3243 * write pages one at a time. We use the ov structure to set
3244 * the write offset, to at least save the overhead of a Seek
3247 DPRINTF(("committing page %"Z"u", pgno));
3248 memset(&ov, 0, sizeof(ov));
3249 ov.Offset = pos & 0xffffffff;
3250 ov.OffsetHigh = pos >> 16 >> 16;
3251 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3253 DPRINTF(("WriteFile: %d", rc));
3257 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3258 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3261 /* Write previous page(s) */
3262 #ifdef MDB_USE_PWRITEV
3263 wres = pwritev(env->me_fd, iov, n, wpos);
3266 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3269 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3273 DPRINTF(("lseek: %s", strerror(rc)));
3276 wres = writev(env->me_fd, iov, n);
3279 if (wres != wsize) {
3284 DPRINTF(("Write error: %s", strerror(rc)));
3286 rc = EIO; /* TODO: Use which error code? */
3287 DPUTS("short write, filesystem full?");
3298 DPRINTF(("committing page %"Z"u", pgno));
3299 next_pos = pos + size;
3300 iov[n].iov_len = size;
3301 iov[n].iov_base = (char *)dp;
3307 /* MIPS has cache coherency issues, this is a no-op everywhere else
3308 * Note: for any size >= on-chip cache size, entire on-chip cache is
3311 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3313 for (i = keep; ++i <= pagecount; ) {
3315 /* This is a page we skipped above */
3318 dl[j].mid = dp->mp_pgno;
3321 mdb_dpage_free(env, dp);
3326 txn->mt_dirty_room += i - j;
3332 mdb_txn_commit(MDB_txn *txn)
3335 unsigned int i, end_mode;
3341 /* mdb_txn_end() mode for a commit which writes nothing */
3342 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3344 if (txn->mt_child) {
3345 rc = mdb_txn_commit(txn->mt_child);
3352 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3356 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3357 DPUTS("txn has failed/finished, can't commit");
3359 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3364 if (txn->mt_parent) {
3365 MDB_txn *parent = txn->mt_parent;
3369 unsigned x, y, len, ps_len;
3371 /* Append our free list to parent's */
3372 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3375 mdb_midl_free(txn->mt_free_pgs);
3376 /* Failures after this must either undo the changes
3377 * to the parent or set MDB_TXN_ERROR in the parent.
3380 parent->mt_next_pgno = txn->mt_next_pgno;
3381 parent->mt_flags = txn->mt_flags;
3383 /* Merge our cursors into parent's and close them */
3384 mdb_cursors_close(txn, 1);
3386 /* Update parent's DB table. */
3387 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3388 parent->mt_numdbs = txn->mt_numdbs;
3389 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3390 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3391 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3392 /* preserve parent's DB_NEW status */
3393 x = parent->mt_dbflags[i] & DB_NEW;
3394 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3397 dst = parent->mt_u.dirty_list;
3398 src = txn->mt_u.dirty_list;
3399 /* Remove anything in our dirty list from parent's spill list */
3400 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3402 pspill[0] = (pgno_t)-1;
3403 /* Mark our dirty pages as deleted in parent spill list */
3404 for (i=0, len=src[0].mid; ++i <= len; ) {
3405 MDB_ID pn = src[i].mid << 1;
3406 while (pn > pspill[x])
3408 if (pn == pspill[x]) {
3413 /* Squash deleted pagenums if we deleted any */
3414 for (x=y; ++x <= ps_len; )
3415 if (!(pspill[x] & 1))
3416 pspill[++y] = pspill[x];
3420 /* Find len = length of merging our dirty list with parent's */
3422 dst[0].mid = 0; /* simplify loops */
3423 if (parent->mt_parent) {
3424 len = x + src[0].mid;
3425 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3426 for (i = x; y && i; y--) {
3427 pgno_t yp = src[y].mid;
3428 while (yp < dst[i].mid)
3430 if (yp == dst[i].mid) {
3435 } else { /* Simplify the above for single-ancestor case */
3436 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3438 /* Merge our dirty list with parent's */
3440 for (i = len; y; dst[i--] = src[y--]) {
3441 pgno_t yp = src[y].mid;
3442 while (yp < dst[x].mid)
3443 dst[i--] = dst[x--];
3444 if (yp == dst[x].mid)
3445 free(dst[x--].mptr);
3447 mdb_tassert(txn, i == x);
3449 free(txn->mt_u.dirty_list);
3450 parent->mt_dirty_room = txn->mt_dirty_room;
3451 if (txn->mt_spill_pgs) {
3452 if (parent->mt_spill_pgs) {
3453 /* TODO: Prevent failure here, so parent does not fail */
3454 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3456 parent->mt_flags |= MDB_TXN_ERROR;
3457 mdb_midl_free(txn->mt_spill_pgs);
3458 mdb_midl_sort(parent->mt_spill_pgs);
3460 parent->mt_spill_pgs = txn->mt_spill_pgs;
3464 /* Append our loose page list to parent's */
3465 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(lp))
3467 *lp = txn->mt_loose_pgs;
3468 parent->mt_loose_count += txn->mt_loose_count;
3470 parent->mt_child = NULL;
3471 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3476 if (txn != env->me_txn) {
3477 DPUTS("attempt to commit unknown transaction");
3482 mdb_cursors_close(txn, 0);
3484 if (!txn->mt_u.dirty_list[0].mid &&
3485 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3488 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3489 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3491 /* Update DB root pointers */
3492 if (txn->mt_numdbs > CORE_DBS) {
3496 data.mv_size = sizeof(MDB_db);
3498 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3499 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3500 if (txn->mt_dbflags[i] & DB_DIRTY) {
3501 if (TXN_DBI_CHANGED(txn, i)) {
3505 data.mv_data = &txn->mt_dbs[i];
3506 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3514 rc = mdb_freelist_save(txn);
3518 mdb_midl_free(env->me_pghead);
3519 env->me_pghead = NULL;
3520 mdb_midl_shrink(&txn->mt_free_pgs);
3526 if ((rc = mdb_page_flush(txn, 0)) ||
3527 (rc = mdb_env_sync(env, 0)) ||
3528 (rc = mdb_env_write_meta(txn)))
3530 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3533 mdb_txn_end(txn, end_mode);
3541 /** Read the environment parameters of a DB environment before
3542 * mapping it into memory.
3543 * @param[in] env the environment handle
3544 * @param[out] meta address of where to store the meta information
3545 * @return 0 on success, non-zero on failure.
3548 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3554 enum { Size = sizeof(pbuf) };
3556 /* We don't know the page size yet, so use a minimum value.
3557 * Read both meta pages so we can use the latest one.
3560 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3564 memset(&ov, 0, sizeof(ov));
3566 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3567 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3570 rc = pread(env->me_fd, &pbuf, Size, off);
3573 if (rc == 0 && off == 0)
3575 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3576 DPRINTF(("read: %s", mdb_strerror(rc)));
3580 p = (MDB_page *)&pbuf;
3582 if (!F_ISSET(p->mp_flags, P_META)) {
3583 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3588 if (m->mm_magic != MDB_MAGIC) {
3589 DPUTS("meta has invalid magic");
3593 if (m->mm_version != MDB_DATA_VERSION) {
3594 DPRINTF(("database is version %u, expected version %u",
3595 m->mm_version, MDB_DATA_VERSION));
3596 return MDB_VERSION_MISMATCH;
3599 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3605 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3607 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3609 meta->mm_magic = MDB_MAGIC;
3610 meta->mm_version = MDB_DATA_VERSION;
3611 meta->mm_mapsize = env->me_mapsize;
3612 meta->mm_psize = env->me_psize;
3613 meta->mm_last_pg = NUM_METAS-1;
3614 meta->mm_flags = env->me_flags & 0xffff;
3615 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3616 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3617 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3620 /** Write the environment parameters of a freshly created DB environment.
3621 * @param[in] env the environment handle
3622 * @param[in] meta the #MDB_meta to write
3623 * @return 0 on success, non-zero on failure.
3626 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3634 memset(&ov, 0, sizeof(ov));
3635 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3637 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3640 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3641 len = pwrite(fd, ptr, size, pos); \
3642 if (len == -1 && ErrCode() == EINTR) continue; \
3643 rc = (len >= 0); break; } while(1)
3646 DPUTS("writing new meta page");
3648 psize = env->me_psize;
3650 p = calloc(NUM_METAS, psize);
3655 p->mp_flags = P_META;
3656 *(MDB_meta *)METADATA(p) = *meta;
3658 q = (MDB_page *)((char *)p + psize);
3660 q->mp_flags = P_META;
3661 *(MDB_meta *)METADATA(q) = *meta;
3663 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
3666 else if ((unsigned) len == psize * NUM_METAS)
3674 /** Update the environment info to commit a transaction.
3675 * @param[in] txn the transaction that's being committed
3676 * @return 0 on success, non-zero on failure.
3679 mdb_env_write_meta(MDB_txn *txn)
3682 MDB_meta meta, metab, *mp;
3686 int rc, len, toggle;
3695 toggle = txn->mt_txnid & 1;
3696 DPRINTF(("writing meta page %d for root page %"Z"u",
3697 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3700 flags = env->me_flags;
3701 mp = env->me_metas[toggle];
3702 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3703 /* Persist any increases of mapsize config */
3704 if (mapsize < env->me_mapsize)
3705 mapsize = env->me_mapsize;
3707 if (flags & MDB_WRITEMAP) {
3708 mp->mm_mapsize = mapsize;
3709 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3710 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3711 mp->mm_last_pg = txn->mt_next_pgno - 1;
3712 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
3713 !(defined(__i386__) || defined(__x86_64__))
3714 /* LY: issue a memory barrier, if not x86. ITS#7969 */
3715 __sync_synchronize();
3717 mp->mm_txnid = txn->mt_txnid;
3718 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3719 unsigned meta_size = env->me_psize;
3720 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3721 ptr = (char *)mp - PAGEHDRSZ;
3722 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3723 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
3727 if (MDB_MSYNC(ptr, meta_size, rc)) {
3734 metab.mm_txnid = mp->mm_txnid;
3735 metab.mm_last_pg = mp->mm_last_pg;
3737 meta.mm_mapsize = mapsize;
3738 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3739 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3740 meta.mm_last_pg = txn->mt_next_pgno - 1;
3741 meta.mm_txnid = txn->mt_txnid;
3743 off = offsetof(MDB_meta, mm_mapsize);
3744 ptr = (char *)&meta + off;
3745 len = sizeof(MDB_meta) - off;
3746 off += (char *)mp - env->me_map;
3748 /* Write to the SYNC fd */
3749 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
3752 memset(&ov, 0, sizeof(ov));
3754 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3759 rc = pwrite(mfd, ptr, len, off);
3762 rc = rc < 0 ? ErrCode() : EIO;
3767 DPUTS("write failed, disk error?");
3768 /* On a failure, the pagecache still contains the new data.
3769 * Write some old data back, to prevent it from being used.
3770 * Use the non-SYNC fd; we know it will fail anyway.
3772 meta.mm_last_pg = metab.mm_last_pg;
3773 meta.mm_txnid = metab.mm_txnid;
3775 memset(&ov, 0, sizeof(ov));
3777 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3779 r2 = pwrite(env->me_fd, ptr, len, off);
3780 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3783 env->me_flags |= MDB_FATAL_ERROR;
3786 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3787 CACHEFLUSH(env->me_map + off, len, DCACHE);
3789 /* Memory ordering issues are irrelevant; since the entire writer
3790 * is wrapped by wmutex, all of these changes will become visible
3791 * after the wmutex is unlocked. Since the DB is multi-version,
3792 * readers will get consistent data regardless of how fresh or
3793 * how stale their view of these values is.
3796 env->me_txns->mti_txnid = txn->mt_txnid;
3801 /** Check both meta pages to see which one is newer.
3802 * @param[in] env the environment handle
3803 * @return newest #MDB_meta.
3806 mdb_env_pick_meta(const MDB_env *env)
3808 MDB_meta *const *metas = env->me_metas;
3809 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
3813 mdb_env_create(MDB_env **env)
3817 e = calloc(1, sizeof(MDB_env));
3821 e->me_maxreaders = DEFAULT_READERS;
3822 e->me_maxdbs = e->me_numdbs = CORE_DBS;
3823 e->me_fd = INVALID_HANDLE_VALUE;
3824 e->me_lfd = INVALID_HANDLE_VALUE;
3825 e->me_mfd = INVALID_HANDLE_VALUE;
3826 #ifdef MDB_USE_POSIX_SEM
3827 e->me_rmutex = SEM_FAILED;
3828 e->me_wmutex = SEM_FAILED;
3830 e->me_pid = getpid();
3831 GET_PAGESIZE(e->me_os_psize);
3832 VGMEMP_CREATE(e,0,0);
3838 mdb_env_map(MDB_env *env, void *addr)
3841 unsigned int flags = env->me_flags;
3845 LONG sizelo, sizehi;
3848 if (flags & MDB_RDONLY) {
3849 /* Don't set explicit map size, use whatever exists */
3854 msize = env->me_mapsize;
3855 sizelo = msize & 0xffffffff;
3856 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3858 /* Windows won't create mappings for zero length files.
3859 * and won't map more than the file size.
3860 * Just set the maxsize right now.
3862 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3863 || !SetEndOfFile(env->me_fd)
3864 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3868 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3869 PAGE_READWRITE : PAGE_READONLY,
3870 sizehi, sizelo, NULL);
3873 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3874 FILE_MAP_WRITE : FILE_MAP_READ,
3876 rc = env->me_map ? 0 : ErrCode();
3881 int prot = PROT_READ;
3882 if (flags & MDB_WRITEMAP) {
3884 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3887 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3889 if (env->me_map == MAP_FAILED) {
3894 if (flags & MDB_NORDAHEAD) {
3895 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3897 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3899 #ifdef POSIX_MADV_RANDOM
3900 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3901 #endif /* POSIX_MADV_RANDOM */
3902 #endif /* MADV_RANDOM */
3906 /* Can happen because the address argument to mmap() is just a
3907 * hint. mmap() can pick another, e.g. if the range is in use.
3908 * The MAP_FIXED flag would prevent that, but then mmap could
3909 * instead unmap existing pages to make room for the new map.
3911 if (addr && env->me_map != addr)
3912 return EBUSY; /* TODO: Make a new MDB_* error code? */
3914 p = (MDB_page *)env->me_map;
3915 env->me_metas[0] = METADATA(p);
3916 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3922 mdb_env_set_mapsize(MDB_env *env, size_t size)
3924 /* If env is already open, caller is responsible for making
3925 * sure there are no active txns.
3933 meta = mdb_env_pick_meta(env);
3935 size = meta->mm_mapsize;
3937 /* Silently round up to minimum if the size is too small */
3938 size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
3942 munmap(env->me_map, env->me_mapsize);
3943 env->me_mapsize = size;
3944 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3945 rc = mdb_env_map(env, old);
3949 env->me_mapsize = size;
3951 env->me_maxpg = env->me_mapsize / env->me_psize;
3956 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3960 env->me_maxdbs = dbs + CORE_DBS;
3965 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3967 if (env->me_map || readers < 1)
3969 env->me_maxreaders = readers;
3974 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3976 if (!env || !readers)
3978 *readers = env->me_maxreaders;
3983 mdb_fsize(HANDLE fd, size_t *size)
3986 LARGE_INTEGER fsize;
3988 if (!GetFileSizeEx(fd, &fsize))
3991 *size = fsize.QuadPart;
4003 #ifdef BROKEN_FDATASYNC
4004 #include <sys/utsname.h>
4005 #include <sys/vfs.h>
4008 /** Further setup required for opening an LMDB environment
4011 mdb_env_open2(MDB_env *env)
4013 unsigned int flags = env->me_flags;
4014 int i, newenv = 0, rc;
4018 /* See if we should use QueryLimited */
4020 if ((rc & 0xff) > 5)
4021 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4023 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4026 #ifdef BROKEN_FDATASYNC
4027 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4028 * https://lkml.org/lkml/2012/9/3/83
4029 * Kernels after 3.6-rc6 are known good.
4030 * https://lkml.org/lkml/2012/9/10/556
4031 * See if the DB is on ext3/ext4, then check for new enough kernel
4032 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4037 fstatfs(env->me_fd, &st);
4038 while (st.f_type == 0xEF53) {
4042 if (uts.release[0] < '3') {
4043 if (!strncmp(uts.release, "2.6.32.", 7)) {
4044 i = atoi(uts.release+7);
4046 break; /* 2.6.32.60 and newer is OK */
4047 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4048 i = atoi(uts.release+7);
4050 break; /* 2.6.34.15 and newer is OK */
4052 } else if (uts.release[0] == '3') {
4053 i = atoi(uts.release+2);
4055 break; /* 3.6 and newer is OK */
4057 i = atoi(uts.release+4);
4059 break; /* 3.5.4 and newer is OK */
4060 } else if (i == 2) {
4061 i = atoi(uts.release+4);
4063 break; /* 3.2.30 and newer is OK */
4065 } else { /* 4.x and newer is OK */
4068 env->me_flags |= MDB_FSYNCONLY;
4074 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4077 DPUTS("new mdbenv");
4079 env->me_psize = env->me_os_psize;
4080 if (env->me_psize > MAX_PAGESIZE)
4081 env->me_psize = MAX_PAGESIZE;
4082 memset(&meta, 0, sizeof(meta));
4083 mdb_env_init_meta0(env, &meta);
4084 meta.mm_mapsize = DEFAULT_MAPSIZE;
4086 env->me_psize = meta.mm_psize;
4089 /* Was a mapsize configured? */
4090 if (!env->me_mapsize) {
4091 env->me_mapsize = meta.mm_mapsize;
4094 /* Make sure mapsize >= committed data size. Even when using
4095 * mm_mapsize, which could be broken in old files (ITS#7789).
4097 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4098 if (env->me_mapsize < minsize)
4099 env->me_mapsize = minsize;
4101 meta.mm_mapsize = env->me_mapsize;
4103 if (newenv && !(flags & MDB_FIXEDMAP)) {
4104 /* mdb_env_map() may grow the datafile. Write the metapages
4105 * first, so the file will be valid if initialization fails.
4106 * Except with FIXEDMAP, since we do not yet know mm_address.
4107 * We could fill in mm_address later, but then a different
4108 * program might end up doing that - one with a memory layout
4109 * and map address which does not suit the main program.
4111 rc = mdb_env_init_meta(env, &meta);
4117 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4122 if (flags & MDB_FIXEDMAP)
4123 meta.mm_address = env->me_map;
4124 i = mdb_env_init_meta(env, &meta);
4125 if (i != MDB_SUCCESS) {
4130 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4131 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4133 #if !(MDB_MAXKEYSIZE)
4134 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4136 env->me_maxpg = env->me_mapsize / env->me_psize;
4140 MDB_meta *meta = mdb_env_pick_meta(env);
4141 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4143 DPRINTF(("opened database version %u, pagesize %u",
4144 meta->mm_version, env->me_psize));
4145 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4146 DPRINTF(("depth: %u", db->md_depth));
4147 DPRINTF(("entries: %"Z"u", db->md_entries));
4148 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
4149 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
4150 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
4151 DPRINTF(("root: %"Z"u", db->md_root));
4159 /** Release a reader thread's slot in the reader lock table.
4160 * This function is called automatically when a thread exits.
4161 * @param[in] ptr This points to the slot in the reader lock table.
4164 mdb_env_reader_dest(void *ptr)
4166 MDB_reader *reader = ptr;
4172 /** Junk for arranging thread-specific callbacks on Windows. This is
4173 * necessarily platform and compiler-specific. Windows supports up
4174 * to 1088 keys. Let's assume nobody opens more than 64 environments
4175 * in a single process, for now. They can override this if needed.
4177 #ifndef MAX_TLS_KEYS
4178 #define MAX_TLS_KEYS 64
4180 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4181 static int mdb_tls_nkeys;
4183 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4187 case DLL_PROCESS_ATTACH: break;
4188 case DLL_THREAD_ATTACH: break;
4189 case DLL_THREAD_DETACH:
4190 for (i=0; i<mdb_tls_nkeys; i++) {
4191 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4193 mdb_env_reader_dest(r);
4197 case DLL_PROCESS_DETACH: break;
4202 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4204 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4208 /* Force some symbol references.
4209 * _tls_used forces the linker to create the TLS directory if not already done
4210 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4212 #pragma comment(linker, "/INCLUDE:_tls_used")
4213 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4214 #pragma const_seg(".CRT$XLB")
4215 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4216 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4219 #pragma comment(linker, "/INCLUDE:__tls_used")
4220 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4221 #pragma data_seg(".CRT$XLB")
4222 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4224 #endif /* WIN 32/64 */
4225 #endif /* !__GNUC__ */
4228 /** Downgrade the exclusive lock on the region back to shared */
4230 mdb_env_share_locks(MDB_env *env, int *excl)
4233 MDB_meta *meta = mdb_env_pick_meta(env);
4235 env->me_txns->mti_txnid = meta->mm_txnid;
4240 /* First acquire a shared lock. The Unlock will
4241 * then release the existing exclusive lock.
4243 memset(&ov, 0, sizeof(ov));
4244 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4247 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4253 struct flock lock_info;
4254 /* The shared lock replaces the existing lock */
4255 memset((void *)&lock_info, 0, sizeof(lock_info));
4256 lock_info.l_type = F_RDLCK;
4257 lock_info.l_whence = SEEK_SET;
4258 lock_info.l_start = 0;
4259 lock_info.l_len = 1;
4260 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4261 (rc = ErrCode()) == EINTR) ;
4262 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4269 /** Try to get exclusive lock, otherwise shared.
4270 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4273 mdb_env_excl_lock(MDB_env *env, int *excl)
4277 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4281 memset(&ov, 0, sizeof(ov));
4282 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4289 struct flock lock_info;
4290 memset((void *)&lock_info, 0, sizeof(lock_info));
4291 lock_info.l_type = F_WRLCK;
4292 lock_info.l_whence = SEEK_SET;
4293 lock_info.l_start = 0;
4294 lock_info.l_len = 1;
4295 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4296 (rc = ErrCode()) == EINTR) ;
4300 # ifndef MDB_USE_POSIX_MUTEX
4301 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4304 lock_info.l_type = F_RDLCK;
4305 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4306 (rc = ErrCode()) == EINTR) ;
4316 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4318 * @(#) $Revision: 5.1 $
4319 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4320 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4322 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4326 * Please do not copyright this code. This code is in the public domain.
4328 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4329 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4330 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4331 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4332 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4333 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4334 * PERFORMANCE OF THIS SOFTWARE.
4337 * chongo <Landon Curt Noll> /\oo/\
4338 * http://www.isthe.com/chongo/
4340 * Share and Enjoy! :-)
4343 typedef unsigned long long mdb_hash_t;
4344 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4346 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4347 * @param[in] val value to hash
4348 * @param[in] hval initial value for hash
4349 * @return 64 bit hash
4351 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4352 * hval arg on the first call.
4355 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4357 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4358 unsigned char *end = s + val->mv_size;
4360 * FNV-1a hash each octet of the string
4363 /* xor the bottom with the current octet */
4364 hval ^= (mdb_hash_t)*s++;
4366 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4367 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4368 (hval << 7) + (hval << 8) + (hval << 40);
4370 /* return our new hash value */
4374 /** Hash the string and output the encoded hash.
4375 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4376 * very short name limits. We don't care about the encoding being reversible,
4377 * we just want to preserve as many bits of the input as possible in a
4378 * small printable string.
4379 * @param[in] str string to hash
4380 * @param[out] encbuf an array of 11 chars to hold the hash
4382 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4385 mdb_pack85(unsigned long l, char *out)
4389 for (i=0; i<5; i++) {
4390 *out++ = mdb_a85[l % 85];
4396 mdb_hash_enc(MDB_val *val, char *encbuf)
4398 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4400 mdb_pack85(h, encbuf);
4401 mdb_pack85(h>>32, encbuf+5);
4406 /** Open and/or initialize the lock region for the environment.
4407 * @param[in] env The LMDB environment.
4408 * @param[in] lpath The pathname of the file used for the lock region.
4409 * @param[in] mode The Unix permissions for the file, if we create it.
4410 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4411 * @return 0 on success, non-zero on failure.
4414 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4417 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4419 # define MDB_ERRCODE_ROFS EROFS
4420 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4421 # define MDB_CLOEXEC O_CLOEXEC
4424 # define MDB_CLOEXEC 0
4431 env->me_lfd = CreateFileA(lpath, GENERIC_READ|GENERIC_WRITE,
4432 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4433 FILE_ATTRIBUTE_NORMAL, NULL);
4435 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4437 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4439 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4444 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4445 /* Lose record locks when exec*() */
4446 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4447 fcntl(env->me_lfd, F_SETFD, fdflags);
4450 if (!(env->me_flags & MDB_NOTLS)) {
4451 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4454 env->me_flags |= MDB_ENV_TXKEY;
4456 /* Windows TLS callbacks need help finding their TLS info. */
4457 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4461 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4465 /* Try to get exclusive lock. If we succeed, then
4466 * nobody is using the lock region and we should initialize it.
4468 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4471 size = GetFileSize(env->me_lfd, NULL);
4473 size = lseek(env->me_lfd, 0, SEEK_END);
4474 if (size == -1) goto fail_errno;
4476 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4477 if (size < rsize && *excl > 0) {
4479 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4480 || !SetEndOfFile(env->me_lfd))
4483 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4487 size = rsize - sizeof(MDB_txninfo);
4488 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4493 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4495 if (!mh) goto fail_errno;
4496 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4498 if (!env->me_txns) goto fail_errno;
4500 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4502 if (m == MAP_FAILED) goto fail_errno;
4508 BY_HANDLE_FILE_INFORMATION stbuf;
4517 if (!mdb_sec_inited) {
4518 InitializeSecurityDescriptor(&mdb_null_sd,
4519 SECURITY_DESCRIPTOR_REVISION);
4520 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4521 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4522 mdb_all_sa.bInheritHandle = FALSE;
4523 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4526 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4527 idbuf.volume = stbuf.dwVolumeSerialNumber;
4528 idbuf.nhigh = stbuf.nFileIndexHigh;
4529 idbuf.nlow = stbuf.nFileIndexLow;
4530 val.mv_data = &idbuf;
4531 val.mv_size = sizeof(idbuf);
4532 mdb_hash_enc(&val, encbuf);
4533 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4534 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4535 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4536 if (!env->me_rmutex) goto fail_errno;
4537 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4538 if (!env->me_wmutex) goto fail_errno;
4539 #elif defined(MDB_USE_POSIX_SEM)
4548 #if defined(__NetBSD__)
4549 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4551 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4552 idbuf.dev = stbuf.st_dev;
4553 idbuf.ino = stbuf.st_ino;
4554 val.mv_data = &idbuf;
4555 val.mv_size = sizeof(idbuf);
4556 mdb_hash_enc(&val, encbuf);
4557 #ifdef MDB_SHORT_SEMNAMES
4558 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4560 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4561 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4562 /* Clean up after a previous run, if needed: Try to
4563 * remove both semaphores before doing anything else.
4565 sem_unlink(env->me_txns->mti_rmname);
4566 sem_unlink(env->me_txns->mti_wmname);
4567 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4568 O_CREAT|O_EXCL, mode, 1);
4569 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4570 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4571 O_CREAT|O_EXCL, mode, 1);
4572 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4573 #else /* MDB_USE_POSIX_MUTEX: */
4574 pthread_mutexattr_t mattr;
4576 if ((rc = pthread_mutexattr_init(&mattr))
4577 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4578 #ifdef MDB_ROBUST_SUPPORTED
4579 || (rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST))
4581 || (rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr))
4582 || (rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr)))
4584 pthread_mutexattr_destroy(&mattr);
4585 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4587 env->me_txns->mti_magic = MDB_MAGIC;
4588 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4589 env->me_txns->mti_txnid = 0;
4590 env->me_txns->mti_numreaders = 0;
4593 if (env->me_txns->mti_magic != MDB_MAGIC) {
4594 DPUTS("lock region has invalid magic");
4598 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4599 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4600 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4601 rc = MDB_VERSION_MISMATCH;
4605 if (rc && rc != EACCES && rc != EAGAIN) {
4609 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4610 if (!env->me_rmutex) goto fail_errno;
4611 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4612 if (!env->me_wmutex) goto fail_errno;
4613 #elif defined(MDB_USE_POSIX_SEM)
4614 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4615 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4616 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4617 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4628 /** The name of the lock file in the DB environment */
4629 #define LOCKNAME "/lock.mdb"
4630 /** The name of the data file in the DB environment */
4631 #define DATANAME "/data.mdb"
4632 /** The suffix of the lock file when no subdir is used */
4633 #define LOCKSUFF "-lock"
4634 /** Only a subset of the @ref mdb_env flags can be changed
4635 * at runtime. Changing other flags requires closing the
4636 * environment and re-opening it with the new flags.
4638 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4639 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
4640 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4642 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4643 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4647 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4649 int oflags, rc, len, excl = -1;
4650 char *lpath, *dpath;
4652 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4656 if (flags & MDB_NOSUBDIR) {
4657 rc = len + sizeof(LOCKSUFF) + len + 1;
4659 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4664 if (flags & MDB_NOSUBDIR) {
4665 dpath = lpath + len + sizeof(LOCKSUFF);
4666 sprintf(lpath, "%s" LOCKSUFF, path);
4667 strcpy(dpath, path);
4669 dpath = lpath + len + sizeof(LOCKNAME);
4670 sprintf(lpath, "%s" LOCKNAME, path);
4671 sprintf(dpath, "%s" DATANAME, path);
4675 flags |= env->me_flags;
4676 if (flags & MDB_RDONLY) {
4677 /* silently ignore WRITEMAP when we're only getting read access */
4678 flags &= ~MDB_WRITEMAP;
4680 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4681 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4684 env->me_flags = flags |= MDB_ENV_ACTIVE;
4688 env->me_path = strdup(path);
4689 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4690 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4691 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4692 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4696 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
4698 /* For RDONLY, get lockfile after we know datafile exists */
4699 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4700 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4706 if (F_ISSET(flags, MDB_RDONLY)) {
4707 oflags = GENERIC_READ;
4708 len = OPEN_EXISTING;
4710 oflags = GENERIC_READ|GENERIC_WRITE;
4713 mode = FILE_ATTRIBUTE_NORMAL;
4714 env->me_fd = CreateFileA(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4715 NULL, len, mode, NULL);
4717 if (F_ISSET(flags, MDB_RDONLY))
4720 oflags = O_RDWR | O_CREAT;
4722 env->me_fd = open(dpath, oflags, mode);
4724 if (env->me_fd == INVALID_HANDLE_VALUE) {
4729 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4730 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4735 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4736 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4737 env->me_mfd = env->me_fd;
4739 /* Synchronous fd for meta writes. Needed even with
4740 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4743 len = OPEN_EXISTING;
4744 env->me_mfd = CreateFileA(dpath, oflags,
4745 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4746 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4749 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4751 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4756 DPRINTF(("opened dbenv %p", (void *) env));
4758 rc = mdb_env_share_locks(env, &excl);
4762 if (!(flags & MDB_RDONLY)) {
4764 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
4765 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
4766 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
4767 (txn = calloc(1, size)))
4769 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
4770 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
4771 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
4772 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
4774 txn->mt_dbxs = env->me_dbxs;
4775 txn->mt_flags = MDB_TXN_FINISHED;
4785 mdb_env_close0(env, excl);
4791 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4793 mdb_env_close0(MDB_env *env, int excl)
4797 if (!(env->me_flags & MDB_ENV_ACTIVE))
4800 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4802 for (i = env->me_maxdbs; --i >= CORE_DBS; )
4803 free(env->me_dbxs[i].md_name.mv_data);
4808 free(env->me_dbiseqs);
4809 free(env->me_dbflags);
4811 free(env->me_dirty_list);
4813 mdb_midl_free(env->me_free_pgs);
4815 if (env->me_flags & MDB_ENV_TXKEY) {
4816 pthread_key_delete(env->me_txkey);
4818 /* Delete our key from the global list */
4819 for (i=0; i<mdb_tls_nkeys; i++)
4820 if (mdb_tls_keys[i] == env->me_txkey) {
4821 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4829 munmap(env->me_map, env->me_mapsize);
4831 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4832 (void) close(env->me_mfd);
4833 if (env->me_fd != INVALID_HANDLE_VALUE)
4834 (void) close(env->me_fd);
4836 MDB_PID_T pid = env->me_pid;
4837 /* Clearing readers is done in this function because
4838 * me_txkey with its destructor must be disabled first.
4840 * We skip the the reader mutex, so we touch only
4841 * data owned by this process (me_close_readers and
4842 * our readers), and clear each reader atomically.
4844 for (i = env->me_close_readers; --i >= 0; )
4845 if (env->me_txns->mti_readers[i].mr_pid == pid)
4846 env->me_txns->mti_readers[i].mr_pid = 0;
4848 if (env->me_rmutex) {
4849 CloseHandle(env->me_rmutex);
4850 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4852 /* Windows automatically destroys the mutexes when
4853 * the last handle closes.
4855 #elif defined(MDB_USE_POSIX_SEM)
4856 if (env->me_rmutex != SEM_FAILED) {
4857 sem_close(env->me_rmutex);
4858 if (env->me_wmutex != SEM_FAILED)
4859 sem_close(env->me_wmutex);
4860 /* If we have the filelock: If we are the
4861 * only remaining user, clean up semaphores.
4864 mdb_env_excl_lock(env, &excl);
4866 sem_unlink(env->me_txns->mti_rmname);
4867 sem_unlink(env->me_txns->mti_wmname);
4871 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4873 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4876 /* Unlock the lockfile. Windows would have unlocked it
4877 * after closing anyway, but not necessarily at once.
4879 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4882 (void) close(env->me_lfd);
4885 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4889 mdb_env_close(MDB_env *env)
4896 VGMEMP_DESTROY(env);
4897 while ((dp = env->me_dpages) != NULL) {
4898 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4899 env->me_dpages = dp->mp_next;
4903 mdb_env_close0(env, 0);
4907 /** Compare two items pointing at aligned size_t's */
4909 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4911 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4912 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4915 /** Compare two items pointing at aligned unsigned int's.
4917 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
4918 * but #mdb_cmp_clong() is called instead if the data type is size_t.
4921 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4923 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4924 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4927 /** Compare two items pointing at unsigned ints of unknown alignment.
4928 * Nodes and keys are guaranteed to be 2-byte aligned.
4931 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4933 #if BYTE_ORDER == LITTLE_ENDIAN
4934 unsigned short *u, *c;
4937 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4938 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4941 } while(!x && u > (unsigned short *)a->mv_data);
4944 unsigned short *u, *c, *end;
4947 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4948 u = (unsigned short *)a->mv_data;
4949 c = (unsigned short *)b->mv_data;
4952 } while(!x && u < end);
4957 /** Compare two items lexically */
4959 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4966 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4972 diff = memcmp(a->mv_data, b->mv_data, len);
4973 return diff ? diff : len_diff<0 ? -1 : len_diff;
4976 /** Compare two items in reverse byte order */
4978 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4980 const unsigned char *p1, *p2, *p1_lim;
4984 p1_lim = (const unsigned char *)a->mv_data;
4985 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4986 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4988 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4994 while (p1 > p1_lim) {
4995 diff = *--p1 - *--p2;
4999 return len_diff<0 ? -1 : len_diff;
5002 /** Search for key within a page, using binary search.
5003 * Returns the smallest entry larger or equal to the key.
5004 * If exactp is non-null, stores whether the found entry was an exact match
5005 * in *exactp (1 or 0).
5006 * Updates the cursor index with the index of the found entry.
5007 * If no entry larger or equal to the key is found, returns NULL.
5010 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5012 unsigned int i = 0, nkeys;
5015 MDB_page *mp = mc->mc_pg[mc->mc_top];
5016 MDB_node *node = NULL;
5021 nkeys = NUMKEYS(mp);
5023 DPRINTF(("searching %u keys in %s %spage %"Z"u",
5024 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5027 low = IS_LEAF(mp) ? 0 : 1;
5029 cmp = mc->mc_dbx->md_cmp;
5031 /* Branch pages have no data, so if using integer keys,
5032 * alignment is guaranteed. Use faster mdb_cmp_int.
5034 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5035 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
5042 nodekey.mv_size = mc->mc_db->md_pad;
5043 node = NODEPTR(mp, 0); /* fake */
5044 while (low <= high) {
5045 i = (low + high) >> 1;
5046 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5047 rc = cmp(key, &nodekey);
5048 DPRINTF(("found leaf index %u [%s], rc = %i",
5049 i, DKEY(&nodekey), rc));
5058 while (low <= high) {
5059 i = (low + high) >> 1;
5061 node = NODEPTR(mp, i);
5062 nodekey.mv_size = NODEKSZ(node);
5063 nodekey.mv_data = NODEKEY(node);
5065 rc = cmp(key, &nodekey);
5068 DPRINTF(("found leaf index %u [%s], rc = %i",
5069 i, DKEY(&nodekey), rc));
5071 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
5072 i, DKEY(&nodekey), NODEPGNO(node), rc));
5083 if (rc > 0) { /* Found entry is less than the key. */
5084 i++; /* Skip to get the smallest entry larger than key. */
5086 node = NODEPTR(mp, i);
5089 *exactp = (rc == 0 && nkeys > 0);
5090 /* store the key index */
5091 mc->mc_ki[mc->mc_top] = i;
5093 /* There is no entry larger or equal to the key. */
5096 /* nodeptr is fake for LEAF2 */
5102 mdb_cursor_adjust(MDB_cursor *mc, func)
5106 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5107 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5114 /** Pop a page off the top of the cursor's stack. */
5116 mdb_cursor_pop(MDB_cursor *mc)
5119 DPRINTF(("popping page %"Z"u off db %d cursor %p",
5120 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5128 /** Push a page onto the top of the cursor's stack. */
5130 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5132 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
5133 DDBI(mc), (void *) mc));
5135 if (mc->mc_snum >= CURSOR_STACK) {
5136 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5137 return MDB_CURSOR_FULL;
5140 mc->mc_top = mc->mc_snum++;
5141 mc->mc_pg[mc->mc_top] = mp;
5142 mc->mc_ki[mc->mc_top] = 0;
5147 /** Find the address of the page corresponding to a given page number.
5148 * @param[in] txn the transaction for this access.
5149 * @param[in] pgno the page number for the page to retrieve.
5150 * @param[out] ret address of a pointer where the page's address will be stored.
5151 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5152 * @return 0 on success, non-zero on failure.
5155 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
5157 MDB_env *env = txn->mt_env;
5161 if (! (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_WRITEMAP))) {
5165 MDB_ID2L dl = tx2->mt_u.dirty_list;
5167 /* Spilled pages were dirtied in this txn and flushed
5168 * because the dirty list got full. Bring this page
5169 * back in from the map (but don't unspill it here,
5170 * leave that unless page_touch happens again).
5172 if (tx2->mt_spill_pgs) {
5173 MDB_ID pn = pgno << 1;
5174 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5175 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5176 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5181 unsigned x = mdb_mid2l_search(dl, pgno);
5182 if (x <= dl[0].mid && dl[x].mid == pgno) {
5188 } while ((tx2 = tx2->mt_parent) != NULL);
5191 if (pgno < txn->mt_next_pgno) {
5193 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5195 DPRINTF(("page %"Z"u not found", pgno));
5196 txn->mt_flags |= MDB_TXN_ERROR;
5197 return MDB_PAGE_NOTFOUND;
5207 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
5208 * The cursor is at the root page, set up the rest of it.
5211 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
5213 MDB_page *mp = mc->mc_pg[mc->mc_top];
5217 while (IS_BRANCH(mp)) {
5221 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
5222 mdb_cassert(mc, NUMKEYS(mp) > 1);
5223 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
5225 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
5227 if (flags & MDB_PS_LAST)
5228 i = NUMKEYS(mp) - 1;
5231 node = mdb_node_search(mc, key, &exact);
5233 i = NUMKEYS(mp) - 1;
5235 i = mc->mc_ki[mc->mc_top];
5237 mdb_cassert(mc, i > 0);
5241 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
5244 mdb_cassert(mc, i < NUMKEYS(mp));
5245 node = NODEPTR(mp, i);
5247 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5250 mc->mc_ki[mc->mc_top] = i;
5251 if ((rc = mdb_cursor_push(mc, mp)))
5254 if (flags & MDB_PS_MODIFY) {
5255 if ((rc = mdb_page_touch(mc)) != 0)
5257 mp = mc->mc_pg[mc->mc_top];
5262 DPRINTF(("internal error, index points to a %02X page!?",
5264 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5265 return MDB_CORRUPTED;
5268 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
5269 key ? DKEY(key) : "null"));
5270 mc->mc_flags |= C_INITIALIZED;
5271 mc->mc_flags &= ~C_EOF;
5276 /** Search for the lowest key under the current branch page.
5277 * This just bypasses a NUMKEYS check in the current page
5278 * before calling mdb_page_search_root(), because the callers
5279 * are all in situations where the current page is known to
5283 mdb_page_search_lowest(MDB_cursor *mc)
5285 MDB_page *mp = mc->mc_pg[mc->mc_top];
5286 MDB_node *node = NODEPTR(mp, 0);
5289 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5292 mc->mc_ki[mc->mc_top] = 0;
5293 if ((rc = mdb_cursor_push(mc, mp)))
5295 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5298 /** Search for the page a given key should be in.
5299 * Push it and its parent pages on the cursor stack.
5300 * @param[in,out] mc the cursor for this operation.
5301 * @param[in] key the key to search for, or NULL for first/last page.
5302 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5303 * are touched (updated with new page numbers).
5304 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5305 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5306 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5307 * @return 0 on success, non-zero on failure.
5310 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5315 /* Make sure the txn is still viable, then find the root from
5316 * the txn's db table and set it as the root of the cursor's stack.
5318 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
5319 DPUTS("transaction may not be used now");
5322 /* Make sure we're using an up-to-date root */
5323 if (*mc->mc_dbflag & DB_STALE) {
5325 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5327 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5328 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5335 MDB_node *leaf = mdb_node_search(&mc2,
5336 &mc->mc_dbx->md_name, &exact);
5338 return MDB_NOTFOUND;
5339 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
5340 return MDB_INCOMPATIBLE; /* not a named DB */
5341 rc = mdb_node_read(mc->mc_txn, leaf, &data);
5344 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5346 /* The txn may not know this DBI, or another process may
5347 * have dropped and recreated the DB with other flags.
5349 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5350 return MDB_INCOMPATIBLE;
5351 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5353 *mc->mc_dbflag &= ~DB_STALE;
5355 root = mc->mc_db->md_root;
5357 if (root == P_INVALID) { /* Tree is empty. */
5358 DPUTS("tree is empty");
5359 return MDB_NOTFOUND;
5363 mdb_cassert(mc, root > 1);
5364 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5365 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
5371 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5372 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5374 if (flags & MDB_PS_MODIFY) {
5375 if ((rc = mdb_page_touch(mc)))
5379 if (flags & MDB_PS_ROOTONLY)
5382 return mdb_page_search_root(mc, key, flags);
5386 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5388 MDB_txn *txn = mc->mc_txn;
5389 pgno_t pg = mp->mp_pgno;
5390 unsigned x = 0, ovpages = mp->mp_pages;
5391 MDB_env *env = txn->mt_env;
5392 MDB_IDL sl = txn->mt_spill_pgs;
5393 MDB_ID pn = pg << 1;
5396 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5397 /* If the page is dirty or on the spill list we just acquired it,
5398 * so we should give it back to our current free list, if any.
5399 * Otherwise put it onto the list of pages we freed in this txn.
5401 * Won't create me_pghead: me_pglast must be inited along with it.
5402 * Unsupported in nested txns: They would need to hide the page
5403 * range in ancestor txns' dirty and spilled lists.
5405 if (env->me_pghead &&
5407 ((mp->mp_flags & P_DIRTY) ||
5408 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5412 MDB_ID2 *dl, ix, iy;
5413 rc = mdb_midl_need(&env->me_pghead, ovpages);
5416 if (!(mp->mp_flags & P_DIRTY)) {
5417 /* This page is no longer spilled */
5424 /* Remove from dirty list */
5425 dl = txn->mt_u.dirty_list;
5427 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5433 mdb_cassert(mc, x > 1);
5435 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5436 txn->mt_flags |= MDB_TXN_ERROR;
5437 return MDB_CORRUPTED;
5440 if (!(env->me_flags & MDB_WRITEMAP))
5441 mdb_dpage_free(env, mp);
5443 /* Insert in me_pghead */
5444 mop = env->me_pghead;
5445 j = mop[0] + ovpages;
5446 for (i = mop[0]; i && mop[i] < pg; i--)
5452 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5456 mc->mc_db->md_overflow_pages -= ovpages;
5460 /** Return the data associated with a given node.
5461 * @param[in] txn The transaction for this operation.
5462 * @param[in] leaf The node being read.
5463 * @param[out] data Updated to point to the node's data.
5464 * @return 0 on success, non-zero on failure.
5467 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5469 MDB_page *omp; /* overflow page */
5473 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5474 data->mv_size = NODEDSZ(leaf);
5475 data->mv_data = NODEDATA(leaf);
5479 /* Read overflow data.
5481 data->mv_size = NODEDSZ(leaf);
5482 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5483 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5484 DPRINTF(("read overflow page %"Z"u failed", pgno));
5487 data->mv_data = METADATA(omp);
5493 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5494 MDB_val *key, MDB_val *data)
5501 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5503 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
5506 if (txn->mt_flags & MDB_TXN_BLOCKED)
5509 mdb_cursor_init(&mc, txn, dbi, &mx);
5510 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5513 /** Find a sibling for a page.
5514 * Replaces the page at the top of the cursor's stack with the
5515 * specified sibling, if one exists.
5516 * @param[in] mc The cursor for this operation.
5517 * @param[in] move_right Non-zero if the right sibling is requested,
5518 * otherwise the left sibling.
5519 * @return 0 on success, non-zero on failure.
5522 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5528 if (mc->mc_snum < 2) {
5529 return MDB_NOTFOUND; /* root has no siblings */
5533 DPRINTF(("parent page is page %"Z"u, index %u",
5534 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5536 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5537 : (mc->mc_ki[mc->mc_top] == 0)) {
5538 DPRINTF(("no more keys left, moving to %s sibling",
5539 move_right ? "right" : "left"));
5540 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5541 /* undo cursor_pop before returning */
5548 mc->mc_ki[mc->mc_top]++;
5550 mc->mc_ki[mc->mc_top]--;
5551 DPRINTF(("just moving to %s index key %u",
5552 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5554 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5556 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5557 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5558 /* mc will be inconsistent if caller does mc_snum++ as above */
5559 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5563 mdb_cursor_push(mc, mp);
5565 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5570 /** Move the cursor to the next data item. */
5572 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5578 if (mc->mc_flags & C_EOF) {
5579 return MDB_NOTFOUND;
5582 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5584 mp = mc->mc_pg[mc->mc_top];
5586 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5587 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5588 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5589 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5590 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5591 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5592 if (rc == MDB_SUCCESS)
5593 MDB_GET_KEY(leaf, key);
5598 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5599 if (op == MDB_NEXT_DUP)
5600 return MDB_NOTFOUND;
5604 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5605 mdb_dbg_pgno(mp), (void *) mc));
5606 if (mc->mc_flags & C_DEL)
5609 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5610 DPUTS("=====> move to next sibling page");
5611 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5612 mc->mc_flags |= C_EOF;
5615 mp = mc->mc_pg[mc->mc_top];
5616 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5618 mc->mc_ki[mc->mc_top]++;
5621 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5622 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5625 key->mv_size = mc->mc_db->md_pad;
5626 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5630 mdb_cassert(mc, IS_LEAF(mp));
5631 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5633 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5634 mdb_xcursor_init1(mc, leaf);
5637 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5640 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5641 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5642 if (rc != MDB_SUCCESS)
5647 MDB_GET_KEY(leaf, key);
5651 /** Move the cursor to the previous data item. */
5653 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5659 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5661 mp = mc->mc_pg[mc->mc_top];
5663 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5664 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5665 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5666 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5667 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5668 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5669 if (rc == MDB_SUCCESS) {
5670 MDB_GET_KEY(leaf, key);
5671 mc->mc_flags &= ~C_EOF;
5677 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5678 if (op == MDB_PREV_DUP)
5679 return MDB_NOTFOUND;
5683 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5684 mdb_dbg_pgno(mp), (void *) mc));
5686 if (mc->mc_ki[mc->mc_top] == 0) {
5687 DPUTS("=====> move to prev sibling page");
5688 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5691 mp = mc->mc_pg[mc->mc_top];
5692 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5693 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5695 mc->mc_ki[mc->mc_top]--;
5697 mc->mc_flags &= ~C_EOF;
5699 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5700 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5703 key->mv_size = mc->mc_db->md_pad;
5704 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5708 mdb_cassert(mc, IS_LEAF(mp));
5709 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5711 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5712 mdb_xcursor_init1(mc, leaf);
5715 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5718 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5719 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5720 if (rc != MDB_SUCCESS)
5725 MDB_GET_KEY(leaf, key);
5729 /** Set the cursor on a specific data item. */
5731 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5732 MDB_cursor_op op, int *exactp)
5736 MDB_node *leaf = NULL;
5739 if (key->mv_size == 0)
5740 return MDB_BAD_VALSIZE;
5743 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5745 /* See if we're already on the right page */
5746 if (mc->mc_flags & C_INITIALIZED) {
5749 mp = mc->mc_pg[mc->mc_top];
5751 mc->mc_ki[mc->mc_top] = 0;
5752 return MDB_NOTFOUND;
5754 if (mp->mp_flags & P_LEAF2) {
5755 nodekey.mv_size = mc->mc_db->md_pad;
5756 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5758 leaf = NODEPTR(mp, 0);
5759 MDB_GET_KEY2(leaf, nodekey);
5761 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5763 /* Probably happens rarely, but first node on the page
5764 * was the one we wanted.
5766 mc->mc_ki[mc->mc_top] = 0;
5773 unsigned int nkeys = NUMKEYS(mp);
5775 if (mp->mp_flags & P_LEAF2) {
5776 nodekey.mv_data = LEAF2KEY(mp,
5777 nkeys-1, nodekey.mv_size);
5779 leaf = NODEPTR(mp, nkeys-1);
5780 MDB_GET_KEY2(leaf, nodekey);
5782 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5784 /* last node was the one we wanted */
5785 mc->mc_ki[mc->mc_top] = nkeys-1;
5791 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5792 /* This is definitely the right page, skip search_page */
5793 if (mp->mp_flags & P_LEAF2) {
5794 nodekey.mv_data = LEAF2KEY(mp,
5795 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5797 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5798 MDB_GET_KEY2(leaf, nodekey);
5800 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5802 /* current node was the one we wanted */
5812 /* If any parents have right-sibs, search.
5813 * Otherwise, there's nothing further.
5815 for (i=0; i<mc->mc_top; i++)
5817 NUMKEYS(mc->mc_pg[i])-1)
5819 if (i == mc->mc_top) {
5820 /* There are no other pages */
5821 mc->mc_ki[mc->mc_top] = nkeys;
5822 return MDB_NOTFOUND;
5826 /* There are no other pages */
5827 mc->mc_ki[mc->mc_top] = 0;
5828 if (op == MDB_SET_RANGE && !exactp) {
5832 return MDB_NOTFOUND;
5836 rc = mdb_page_search(mc, key, 0);
5837 if (rc != MDB_SUCCESS)
5840 mp = mc->mc_pg[mc->mc_top];
5841 mdb_cassert(mc, IS_LEAF(mp));
5844 leaf = mdb_node_search(mc, key, exactp);
5845 if (exactp != NULL && !*exactp) {
5846 /* MDB_SET specified and not an exact match. */
5847 return MDB_NOTFOUND;
5851 DPUTS("===> inexact leaf not found, goto sibling");
5852 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5853 mc->mc_flags |= C_EOF;
5854 return rc; /* no entries matched */
5856 mp = mc->mc_pg[mc->mc_top];
5857 mdb_cassert(mc, IS_LEAF(mp));
5858 leaf = NODEPTR(mp, 0);
5862 mc->mc_flags |= C_INITIALIZED;
5863 mc->mc_flags &= ~C_EOF;
5866 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5867 key->mv_size = mc->mc_db->md_pad;
5868 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5873 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5874 mdb_xcursor_init1(mc, leaf);
5877 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5878 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5879 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5882 if (op == MDB_GET_BOTH) {
5888 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5889 if (rc != MDB_SUCCESS)
5892 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5895 if ((rc = mdb_node_read(mc->mc_txn, leaf, &olddata)) != MDB_SUCCESS)
5897 dcmp = mc->mc_dbx->md_dcmp;
5898 #if UINT_MAX < SIZE_MAX
5899 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
5900 dcmp = mdb_cmp_clong;
5902 rc = dcmp(data, &olddata);
5904 if (op == MDB_GET_BOTH || rc > 0)
5905 return MDB_NOTFOUND;
5912 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5913 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5918 /* The key already matches in all other cases */
5919 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5920 MDB_GET_KEY(leaf, key);
5921 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5926 /** Move the cursor to the first item in the database. */
5928 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5934 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5936 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5937 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5938 if (rc != MDB_SUCCESS)
5941 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5943 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5944 mc->mc_flags |= C_INITIALIZED;
5945 mc->mc_flags &= ~C_EOF;
5947 mc->mc_ki[mc->mc_top] = 0;
5949 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5950 key->mv_size = mc->mc_db->md_pad;
5951 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5956 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5957 mdb_xcursor_init1(mc, leaf);
5958 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5962 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5966 MDB_GET_KEY(leaf, key);
5970 /** Move the cursor to the last item in the database. */
5972 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5978 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5980 if (!(mc->mc_flags & C_EOF)) {
5982 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5983 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5984 if (rc != MDB_SUCCESS)
5987 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5990 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5991 mc->mc_flags |= C_INITIALIZED|C_EOF;
5992 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5994 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5995 key->mv_size = mc->mc_db->md_pad;
5996 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
6001 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6002 mdb_xcursor_init1(mc, leaf);
6003 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6007 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
6012 MDB_GET_KEY(leaf, key);
6017 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6022 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
6027 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
6031 case MDB_GET_CURRENT:
6032 if (!(mc->mc_flags & C_INITIALIZED)) {
6035 MDB_page *mp = mc->mc_pg[mc->mc_top];
6036 int nkeys = NUMKEYS(mp);
6037 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
6038 mc->mc_ki[mc->mc_top] = nkeys;
6044 key->mv_size = mc->mc_db->md_pad;
6045 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6047 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6048 MDB_GET_KEY(leaf, key);
6050 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6051 if (mc->mc_flags & C_DEL)
6052 mdb_xcursor_init1(mc, leaf);
6053 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
6055 rc = mdb_node_read(mc->mc_txn, leaf, data);
6062 case MDB_GET_BOTH_RANGE:
6067 if (mc->mc_xcursor == NULL) {
6068 rc = MDB_INCOMPATIBLE;
6078 rc = mdb_cursor_set(mc, key, data, op,
6079 op == MDB_SET_RANGE ? NULL : &exact);
6082 case MDB_GET_MULTIPLE:
6083 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6087 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6088 rc = MDB_INCOMPATIBLE;
6092 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6093 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6096 case MDB_NEXT_MULTIPLE:
6101 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6102 rc = MDB_INCOMPATIBLE;
6105 if (!(mc->mc_flags & C_INITIALIZED))
6106 rc = mdb_cursor_first(mc, key, data);
6108 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6109 if (rc == MDB_SUCCESS) {
6110 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6113 mx = &mc->mc_xcursor->mx_cursor;
6114 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
6116 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
6117 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
6125 case MDB_NEXT_NODUP:
6126 if (!(mc->mc_flags & C_INITIALIZED))
6127 rc = mdb_cursor_first(mc, key, data);
6129 rc = mdb_cursor_next(mc, key, data, op);
6133 case MDB_PREV_NODUP:
6134 if (!(mc->mc_flags & C_INITIALIZED)) {
6135 rc = mdb_cursor_last(mc, key, data);
6138 mc->mc_flags |= C_INITIALIZED;
6139 mc->mc_ki[mc->mc_top]++;
6141 rc = mdb_cursor_prev(mc, key, data, op);
6144 rc = mdb_cursor_first(mc, key, data);
6147 mfunc = mdb_cursor_first;
6149 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6153 if (mc->mc_xcursor == NULL) {
6154 rc = MDB_INCOMPATIBLE;
6158 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6159 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6160 MDB_GET_KEY(leaf, key);
6161 rc = mdb_node_read(mc->mc_txn, leaf, data);
6165 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6169 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
6172 rc = mdb_cursor_last(mc, key, data);
6175 mfunc = mdb_cursor_last;
6178 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
6183 if (mc->mc_flags & C_DEL)
6184 mc->mc_flags ^= C_DEL;
6189 /** Touch all the pages in the cursor stack. Set mc_top.
6190 * Makes sure all the pages are writable, before attempting a write operation.
6191 * @param[in] mc The cursor to operate on.
6194 mdb_cursor_touch(MDB_cursor *mc)
6196 int rc = MDB_SUCCESS;
6198 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & DB_DIRTY)) {
6201 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6203 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
6204 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
6207 *mc->mc_dbflag |= DB_DIRTY;
6212 rc = mdb_page_touch(mc);
6213 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
6214 mc->mc_top = mc->mc_snum-1;
6219 /** Do not spill pages to disk if txn is getting full, may fail instead */
6220 #define MDB_NOSPILL 0x8000
6223 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6227 MDB_node *leaf = NULL;
6228 MDB_page *fp, *mp, *sub_root = NULL;
6230 MDB_val xdata, *rdata, dkey, olddata;
6232 int do_sub = 0, insert_key, insert_data;
6233 unsigned int mcount = 0, dcount = 0, nospill;
6236 unsigned int nflags;
6239 if (mc == NULL || key == NULL)
6242 env = mc->mc_txn->mt_env;
6244 /* Check this first so counter will always be zero on any
6247 if (flags & MDB_MULTIPLE) {
6248 dcount = data[1].mv_size;
6249 data[1].mv_size = 0;
6250 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
6251 return MDB_INCOMPATIBLE;
6254 nospill = flags & MDB_NOSPILL;
6255 flags &= ~MDB_NOSPILL;
6257 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6258 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6260 if (key->mv_size-1 >= ENV_MAXKEY(env))
6261 return MDB_BAD_VALSIZE;
6263 #if SIZE_MAX > MAXDATASIZE
6264 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
6265 return MDB_BAD_VALSIZE;
6267 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
6268 return MDB_BAD_VALSIZE;
6271 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
6272 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
6276 if (flags == MDB_CURRENT) {
6277 if (!(mc->mc_flags & C_INITIALIZED))
6280 } else if (mc->mc_db->md_root == P_INVALID) {
6281 /* new database, cursor has nothing to point to */
6284 mc->mc_flags &= ~C_INITIALIZED;
6289 if (flags & MDB_APPEND) {
6291 rc = mdb_cursor_last(mc, &k2, &d2);
6293 rc = mc->mc_dbx->md_cmp(key, &k2);
6296 mc->mc_ki[mc->mc_top]++;
6298 /* new key is <= last key */
6303 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6305 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6306 DPRINTF(("duplicate key [%s]", DKEY(key)));
6308 return MDB_KEYEXIST;
6310 if (rc && rc != MDB_NOTFOUND)
6314 if (mc->mc_flags & C_DEL)
6315 mc->mc_flags ^= C_DEL;
6317 /* Cursor is positioned, check for room in the dirty list */
6319 if (flags & MDB_MULTIPLE) {
6321 xdata.mv_size = data->mv_size * dcount;
6325 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6329 if (rc == MDB_NO_ROOT) {
6331 /* new database, write a root leaf page */
6332 DPUTS("allocating new root leaf page");
6333 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6336 mdb_cursor_push(mc, np);
6337 mc->mc_db->md_root = np->mp_pgno;
6338 mc->mc_db->md_depth++;
6339 *mc->mc_dbflag |= DB_DIRTY;
6340 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6342 np->mp_flags |= P_LEAF2;
6343 mc->mc_flags |= C_INITIALIZED;
6345 /* make sure all cursor pages are writable */
6346 rc2 = mdb_cursor_touch(mc);
6351 insert_key = insert_data = rc;
6353 /* The key does not exist */
6354 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6355 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6356 LEAFSIZE(key, data) > env->me_nodemax)
6358 /* Too big for a node, insert in sub-DB. Set up an empty
6359 * "old sub-page" for prep_subDB to expand to a full page.
6361 fp_flags = P_LEAF|P_DIRTY;
6363 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6364 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6365 olddata.mv_size = PAGEHDRSZ;
6369 /* there's only a key anyway, so this is a no-op */
6370 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6372 unsigned int ksize = mc->mc_db->md_pad;
6373 if (key->mv_size != ksize)
6374 return MDB_BAD_VALSIZE;
6375 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6376 memcpy(ptr, key->mv_data, ksize);
6378 /* if overwriting slot 0 of leaf, need to
6379 * update branch key if there is a parent page
6381 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6382 unsigned short top = mc->mc_top;
6384 /* slot 0 is always an empty key, find real slot */
6385 while (mc->mc_top && !mc->mc_ki[mc->mc_top])
6387 if (mc->mc_ki[mc->mc_top])
6388 rc2 = mdb_update_key(mc, key);
6399 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6400 olddata.mv_size = NODEDSZ(leaf);
6401 olddata.mv_data = NODEDATA(leaf);
6404 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6405 /* Prepare (sub-)page/sub-DB to accept the new item,
6406 * if needed. fp: old sub-page or a header faking
6407 * it. mp: new (sub-)page. offset: growth in page
6408 * size. xdata: node data with new page or DB.
6410 unsigned i, offset = 0;
6411 mp = fp = xdata.mv_data = env->me_pbuf;
6412 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6414 /* Was a single item before, must convert now */
6415 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6417 /* Just overwrite the current item */
6418 if (flags == MDB_CURRENT)
6420 dcmp = mc->mc_dbx->md_dcmp;
6421 #if UINT_MAX < SIZE_MAX
6422 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6423 dcmp = mdb_cmp_clong;
6425 /* does data match? */
6426 if (!dcmp(data, &olddata)) {
6427 if (flags & MDB_NODUPDATA)
6428 return MDB_KEYEXIST;
6433 /* Back up original data item */
6434 dkey.mv_size = olddata.mv_size;
6435 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6437 /* Make sub-page header for the dup items, with dummy body */
6438 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6439 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6440 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6441 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6442 fp->mp_flags |= P_LEAF2;
6443 fp->mp_pad = data->mv_size;
6444 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6446 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6447 (dkey.mv_size & 1) + (data->mv_size & 1);
6449 fp->mp_upper = xdata.mv_size - PAGEBASE;
6450 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6451 } else if (leaf->mn_flags & F_SUBDATA) {
6452 /* Data is on sub-DB, just store it */
6453 flags |= F_DUPDATA|F_SUBDATA;
6456 /* Data is on sub-page */
6457 fp = olddata.mv_data;
6460 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6461 offset = EVEN(NODESIZE + sizeof(indx_t) +
6465 offset = fp->mp_pad;
6466 if (SIZELEFT(fp) < offset) {
6467 offset *= 4; /* space for 4 more */
6470 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6472 fp->mp_flags |= P_DIRTY;
6473 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6474 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6478 xdata.mv_size = olddata.mv_size + offset;
6481 fp_flags = fp->mp_flags;
6482 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6483 /* Too big for a sub-page, convert to sub-DB */
6484 fp_flags &= ~P_SUBP;
6486 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6487 fp_flags |= P_LEAF2;
6488 dummy.md_pad = fp->mp_pad;
6489 dummy.md_flags = MDB_DUPFIXED;
6490 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6491 dummy.md_flags |= MDB_INTEGERKEY;
6497 dummy.md_branch_pages = 0;
6498 dummy.md_leaf_pages = 1;
6499 dummy.md_overflow_pages = 0;
6500 dummy.md_entries = NUMKEYS(fp);
6501 xdata.mv_size = sizeof(MDB_db);
6502 xdata.mv_data = &dummy;
6503 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6505 offset = env->me_psize - olddata.mv_size;
6506 flags |= F_DUPDATA|F_SUBDATA;
6507 dummy.md_root = mp->mp_pgno;
6511 mp->mp_flags = fp_flags | P_DIRTY;
6512 mp->mp_pad = fp->mp_pad;
6513 mp->mp_lower = fp->mp_lower;
6514 mp->mp_upper = fp->mp_upper + offset;
6515 if (fp_flags & P_LEAF2) {
6516 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6518 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6519 olddata.mv_size - fp->mp_upper - PAGEBASE);
6520 for (i=0; i<NUMKEYS(fp); i++)
6521 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6529 mdb_node_del(mc, 0);
6533 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
6534 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
6535 return MDB_INCOMPATIBLE;
6536 /* overflow page overwrites need special handling */
6537 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6540 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6542 memcpy(&pg, olddata.mv_data, sizeof(pg));
6543 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6545 ovpages = omp->mp_pages;
6547 /* Is the ov page large enough? */
6548 if (ovpages >= dpages) {
6549 if (!(omp->mp_flags & P_DIRTY) &&
6550 (level || (env->me_flags & MDB_WRITEMAP)))
6552 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6555 level = 0; /* dirty in this txn or clean */
6558 if (omp->mp_flags & P_DIRTY) {
6559 /* yes, overwrite it. Note in this case we don't
6560 * bother to try shrinking the page if the new data
6561 * is smaller than the overflow threshold.
6564 /* It is writable only in a parent txn */
6565 size_t sz = (size_t) env->me_psize * ovpages, off;
6566 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6572 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6573 mdb_cassert(mc, rc2 == 0);
6574 if (!(flags & MDB_RESERVE)) {
6575 /* Copy end of page, adjusting alignment so
6576 * compiler may copy words instead of bytes.
6578 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6579 memcpy((size_t *)((char *)np + off),
6580 (size_t *)((char *)omp + off), sz - off);
6583 memcpy(np, omp, sz); /* Copy beginning of page */
6586 SETDSZ(leaf, data->mv_size);
6587 if (F_ISSET(flags, MDB_RESERVE))
6588 data->mv_data = METADATA(omp);
6590 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6594 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6596 } else if (data->mv_size == olddata.mv_size) {
6597 /* same size, just replace it. Note that we could
6598 * also reuse this node if the new data is smaller,
6599 * but instead we opt to shrink the node in that case.
6601 if (F_ISSET(flags, MDB_RESERVE))
6602 data->mv_data = olddata.mv_data;
6603 else if (!(mc->mc_flags & C_SUB))
6604 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6606 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6611 mdb_node_del(mc, 0);
6617 nflags = flags & NODE_ADD_FLAGS;
6618 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6619 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6620 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6621 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6623 nflags |= MDB_SPLIT_REPLACE;
6624 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6626 /* There is room already in this leaf page. */
6627 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6628 if (rc == 0 && insert_key) {
6629 /* Adjust other cursors pointing to mp */
6630 MDB_cursor *m2, *m3;
6631 MDB_dbi dbi = mc->mc_dbi;
6632 unsigned i = mc->mc_top;
6633 MDB_page *mp = mc->mc_pg[i];
6635 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6636 if (mc->mc_flags & C_SUB)
6637 m3 = &m2->mc_xcursor->mx_cursor;
6640 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6641 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6648 if (rc == MDB_SUCCESS) {
6649 /* Now store the actual data in the child DB. Note that we're
6650 * storing the user data in the keys field, so there are strict
6651 * size limits on dupdata. The actual data fields of the child
6652 * DB are all zero size.
6655 int xflags, new_dupdata;
6660 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6661 if (flags & MDB_CURRENT) {
6662 xflags = MDB_CURRENT|MDB_NOSPILL;
6664 mdb_xcursor_init1(mc, leaf);
6665 xflags = (flags & MDB_NODUPDATA) ?
6666 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6669 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
6670 new_dupdata = (int)dkey.mv_size;
6671 /* converted, write the original data first */
6673 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6676 /* we've done our job */
6679 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
6680 /* Adjust other cursors pointing to mp */
6682 MDB_xcursor *mx = mc->mc_xcursor;
6683 unsigned i = mc->mc_top;
6684 MDB_page *mp = mc->mc_pg[i];
6686 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6687 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6688 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6689 if (m2->mc_pg[i] == mp) {
6690 if (m2->mc_ki[i] == mc->mc_ki[i]) {
6691 mdb_xcursor_init2(m2, mx, new_dupdata);
6692 } else if (!insert_key) {
6693 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[i]);
6694 if (!(n2->mn_flags & F_SUBDATA))
6695 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
6700 ecount = mc->mc_xcursor->mx_db.md_entries;
6701 if (flags & MDB_APPENDDUP)
6702 xflags |= MDB_APPEND;
6703 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6704 if (flags & F_SUBDATA) {
6705 void *db = NODEDATA(leaf);
6706 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6708 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6710 /* Increment count unless we just replaced an existing item. */
6712 mc->mc_db->md_entries++;
6714 /* Invalidate txn if we created an empty sub-DB */
6717 /* If we succeeded and the key didn't exist before,
6718 * make sure the cursor is marked valid.
6720 mc->mc_flags |= C_INITIALIZED;
6722 if (flags & MDB_MULTIPLE) {
6725 /* let caller know how many succeeded, if any */
6726 data[1].mv_size = mcount;
6727 if (mcount < dcount) {
6728 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6729 insert_key = insert_data = 0;
6736 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6739 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6744 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6750 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6751 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6753 if (!(mc->mc_flags & C_INITIALIZED))
6756 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6757 return MDB_NOTFOUND;
6759 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6762 rc = mdb_cursor_touch(mc);
6766 mp = mc->mc_pg[mc->mc_top];
6769 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6771 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6772 if (flags & MDB_NODUPDATA) {
6773 /* mdb_cursor_del0() will subtract the final entry */
6774 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6776 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6777 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6779 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6782 /* If sub-DB still has entries, we're done */
6783 if (mc->mc_xcursor->mx_db.md_entries) {
6784 if (leaf->mn_flags & F_SUBDATA) {
6785 /* update subDB info */
6786 void *db = NODEDATA(leaf);
6787 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6790 /* shrink fake page */
6791 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6792 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6793 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6794 /* fix other sub-DB cursors pointed at fake pages on this page */
6795 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6796 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6797 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6798 if (m2->mc_pg[mc->mc_top] == mp) {
6799 if (m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top]) {
6800 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6802 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
6803 if (!(n2->mn_flags & F_SUBDATA))
6804 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
6809 mc->mc_db->md_entries--;
6810 mc->mc_flags |= C_DEL;
6813 /* otherwise fall thru and delete the sub-DB */
6816 if (leaf->mn_flags & F_SUBDATA) {
6817 /* add all the child DB's pages to the free list */
6818 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6823 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
6824 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
6825 rc = MDB_INCOMPATIBLE;
6829 /* add overflow pages to free list */
6830 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6834 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6835 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6836 (rc = mdb_ovpage_free(mc, omp)))
6841 return mdb_cursor_del0(mc);
6844 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6848 /** Allocate and initialize new pages for a database.
6849 * @param[in] mc a cursor on the database being added to.
6850 * @param[in] flags flags defining what type of page is being allocated.
6851 * @param[in] num the number of pages to allocate. This is usually 1,
6852 * unless allocating overflow pages for a large record.
6853 * @param[out] mp Address of a page, or NULL on failure.
6854 * @return 0 on success, non-zero on failure.
6857 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6862 if ((rc = mdb_page_alloc(mc, num, &np)))
6864 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6865 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6866 np->mp_flags = flags | P_DIRTY;
6867 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
6868 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
6871 mc->mc_db->md_branch_pages++;
6872 else if (IS_LEAF(np))
6873 mc->mc_db->md_leaf_pages++;
6874 else if (IS_OVERFLOW(np)) {
6875 mc->mc_db->md_overflow_pages += num;
6883 /** Calculate the size of a leaf node.
6884 * The size depends on the environment's page size; if a data item
6885 * is too large it will be put onto an overflow page and the node
6886 * size will only include the key and not the data. Sizes are always
6887 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6888 * of the #MDB_node headers.
6889 * @param[in] env The environment handle.
6890 * @param[in] key The key for the node.
6891 * @param[in] data The data for the node.
6892 * @return The number of bytes needed to store the node.
6895 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6899 sz = LEAFSIZE(key, data);
6900 if (sz > env->me_nodemax) {
6901 /* put on overflow page */
6902 sz -= data->mv_size - sizeof(pgno_t);
6905 return EVEN(sz + sizeof(indx_t));
6908 /** Calculate the size of a branch node.
6909 * The size should depend on the environment's page size but since
6910 * we currently don't support spilling large keys onto overflow
6911 * pages, it's simply the size of the #MDB_node header plus the
6912 * size of the key. Sizes are always rounded up to an even number
6913 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6914 * @param[in] env The environment handle.
6915 * @param[in] key The key for the node.
6916 * @return The number of bytes needed to store the node.
6919 mdb_branch_size(MDB_env *env, MDB_val *key)
6924 if (sz > env->me_nodemax) {
6925 /* put on overflow page */
6926 /* not implemented */
6927 /* sz -= key->size - sizeof(pgno_t); */
6930 return sz + sizeof(indx_t);
6933 /** Add a node to the page pointed to by the cursor.
6934 * @param[in] mc The cursor for this operation.
6935 * @param[in] indx The index on the page where the new node should be added.
6936 * @param[in] key The key for the new node.
6937 * @param[in] data The data for the new node, if any.
6938 * @param[in] pgno The page number, if adding a branch node.
6939 * @param[in] flags Flags for the node.
6940 * @return 0 on success, non-zero on failure. Possible errors are:
6942 * <li>ENOMEM - failed to allocate overflow pages for the node.
6943 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6944 * should never happen since all callers already calculate the
6945 * page's free space before calling this function.
6949 mdb_node_add(MDB_cursor *mc, indx_t indx,
6950 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6953 size_t node_size = NODESIZE;
6957 MDB_page *mp = mc->mc_pg[mc->mc_top];
6958 MDB_page *ofp = NULL; /* overflow page */
6962 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
6964 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6965 IS_LEAF(mp) ? "leaf" : "branch",
6966 IS_SUBP(mp) ? "sub-" : "",
6967 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
6968 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6971 /* Move higher keys up one slot. */
6972 int ksize = mc->mc_db->md_pad, dif;
6973 char *ptr = LEAF2KEY(mp, indx, ksize);
6974 dif = NUMKEYS(mp) - indx;
6976 memmove(ptr+ksize, ptr, dif*ksize);
6977 /* insert new key */
6978 memcpy(ptr, key->mv_data, ksize);
6980 /* Just using these for counting */
6981 mp->mp_lower += sizeof(indx_t);
6982 mp->mp_upper -= ksize - sizeof(indx_t);
6986 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6988 node_size += key->mv_size;
6990 mdb_cassert(mc, key && data);
6991 if (F_ISSET(flags, F_BIGDATA)) {
6992 /* Data already on overflow page. */
6993 node_size += sizeof(pgno_t);
6994 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
6995 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6997 /* Put data on overflow page. */
6998 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6999 data->mv_size, node_size+data->mv_size));
7000 node_size = EVEN(node_size + sizeof(pgno_t));
7001 if ((ssize_t)node_size > room)
7003 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
7005 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
7009 node_size += data->mv_size;
7012 node_size = EVEN(node_size);
7013 if ((ssize_t)node_size > room)
7017 /* Move higher pointers up one slot. */
7018 for (i = NUMKEYS(mp); i > indx; i--)
7019 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
7021 /* Adjust free space offsets. */
7022 ofs = mp->mp_upper - node_size;
7023 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
7024 mp->mp_ptrs[indx] = ofs;
7026 mp->mp_lower += sizeof(indx_t);
7028 /* Write the node data. */
7029 node = NODEPTR(mp, indx);
7030 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
7031 node->mn_flags = flags;
7033 SETDSZ(node,data->mv_size);
7038 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7041 ndata = NODEDATA(node);
7043 if (F_ISSET(flags, F_BIGDATA))
7044 memcpy(ndata, data->mv_data, sizeof(pgno_t));
7045 else if (F_ISSET(flags, MDB_RESERVE))
7046 data->mv_data = ndata;
7048 memcpy(ndata, data->mv_data, data->mv_size);
7050 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
7051 ndata = METADATA(ofp);
7052 if (F_ISSET(flags, MDB_RESERVE))
7053 data->mv_data = ndata;
7055 memcpy(ndata, data->mv_data, data->mv_size);
7062 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
7063 mdb_dbg_pgno(mp), NUMKEYS(mp)));
7064 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
7065 DPRINTF(("node size = %"Z"u", node_size));
7066 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7067 return MDB_PAGE_FULL;
7070 /** Delete the specified node from a page.
7071 * @param[in] mc Cursor pointing to the node to delete.
7072 * @param[in] ksize The size of a node. Only used if the page is
7073 * part of a #MDB_DUPFIXED database.
7076 mdb_node_del(MDB_cursor *mc, int ksize)
7078 MDB_page *mp = mc->mc_pg[mc->mc_top];
7079 indx_t indx = mc->mc_ki[mc->mc_top];
7081 indx_t i, j, numkeys, ptr;
7085 DPRINTF(("delete node %u on %s page %"Z"u", indx,
7086 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
7087 numkeys = NUMKEYS(mp);
7088 mdb_cassert(mc, indx < numkeys);
7091 int x = numkeys - 1 - indx;
7092 base = LEAF2KEY(mp, indx, ksize);
7094 memmove(base, base + ksize, x * ksize);
7095 mp->mp_lower -= sizeof(indx_t);
7096 mp->mp_upper += ksize - sizeof(indx_t);
7100 node = NODEPTR(mp, indx);
7101 sz = NODESIZE + node->mn_ksize;
7103 if (F_ISSET(node->mn_flags, F_BIGDATA))
7104 sz += sizeof(pgno_t);
7106 sz += NODEDSZ(node);
7110 ptr = mp->mp_ptrs[indx];
7111 for (i = j = 0; i < numkeys; i++) {
7113 mp->mp_ptrs[j] = mp->mp_ptrs[i];
7114 if (mp->mp_ptrs[i] < ptr)
7115 mp->mp_ptrs[j] += sz;
7120 base = (char *)mp + mp->mp_upper + PAGEBASE;
7121 memmove(base + sz, base, ptr - mp->mp_upper);
7123 mp->mp_lower -= sizeof(indx_t);
7127 /** Compact the main page after deleting a node on a subpage.
7128 * @param[in] mp The main page to operate on.
7129 * @param[in] indx The index of the subpage on the main page.
7132 mdb_node_shrink(MDB_page *mp, indx_t indx)
7137 indx_t delta, nsize, len, ptr;
7140 node = NODEPTR(mp, indx);
7141 sp = (MDB_page *)NODEDATA(node);
7142 delta = SIZELEFT(sp);
7143 nsize = NODEDSZ(node) - delta;
7145 /* Prepare to shift upward, set len = length(subpage part to shift) */
7149 return; /* do not make the node uneven-sized */
7151 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
7152 for (i = NUMKEYS(sp); --i >= 0; )
7153 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
7156 sp->mp_upper = sp->mp_lower;
7157 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
7158 SETDSZ(node, nsize);
7160 /* Shift <lower nodes...initial part of subpage> upward */
7161 base = (char *)mp + mp->mp_upper + PAGEBASE;
7162 memmove(base + delta, base, (char *)sp + len - base);
7164 ptr = mp->mp_ptrs[indx];
7165 for (i = NUMKEYS(mp); --i >= 0; ) {
7166 if (mp->mp_ptrs[i] <= ptr)
7167 mp->mp_ptrs[i] += delta;
7169 mp->mp_upper += delta;
7172 /** Initial setup of a sorted-dups cursor.
7173 * Sorted duplicates are implemented as a sub-database for the given key.
7174 * The duplicate data items are actually keys of the sub-database.
7175 * Operations on the duplicate data items are performed using a sub-cursor
7176 * initialized when the sub-database is first accessed. This function does
7177 * the preliminary setup of the sub-cursor, filling in the fields that
7178 * depend only on the parent DB.
7179 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7182 mdb_xcursor_init0(MDB_cursor *mc)
7184 MDB_xcursor *mx = mc->mc_xcursor;
7186 mx->mx_cursor.mc_xcursor = NULL;
7187 mx->mx_cursor.mc_txn = mc->mc_txn;
7188 mx->mx_cursor.mc_db = &mx->mx_db;
7189 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
7190 mx->mx_cursor.mc_dbi = mc->mc_dbi;
7191 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
7192 mx->mx_cursor.mc_snum = 0;
7193 mx->mx_cursor.mc_top = 0;
7194 mx->mx_cursor.mc_flags = C_SUB;
7195 mx->mx_dbx.md_name.mv_size = 0;
7196 mx->mx_dbx.md_name.mv_data = NULL;
7197 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
7198 mx->mx_dbx.md_dcmp = NULL;
7199 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
7202 /** Final setup of a sorted-dups cursor.
7203 * Sets up the fields that depend on the data from the main cursor.
7204 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7205 * @param[in] node The data containing the #MDB_db record for the
7206 * sorted-dup database.
7209 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
7211 MDB_xcursor *mx = mc->mc_xcursor;
7213 if (node->mn_flags & F_SUBDATA) {
7214 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
7215 mx->mx_cursor.mc_pg[0] = 0;
7216 mx->mx_cursor.mc_snum = 0;
7217 mx->mx_cursor.mc_top = 0;
7218 mx->mx_cursor.mc_flags = C_SUB;
7220 MDB_page *fp = NODEDATA(node);
7221 mx->mx_db.md_pad = 0;
7222 mx->mx_db.md_flags = 0;
7223 mx->mx_db.md_depth = 1;
7224 mx->mx_db.md_branch_pages = 0;
7225 mx->mx_db.md_leaf_pages = 1;
7226 mx->mx_db.md_overflow_pages = 0;
7227 mx->mx_db.md_entries = NUMKEYS(fp);
7228 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
7229 mx->mx_cursor.mc_snum = 1;
7230 mx->mx_cursor.mc_top = 0;
7231 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
7232 mx->mx_cursor.mc_pg[0] = fp;
7233 mx->mx_cursor.mc_ki[0] = 0;
7234 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7235 mx->mx_db.md_flags = MDB_DUPFIXED;
7236 mx->mx_db.md_pad = fp->mp_pad;
7237 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7238 mx->mx_db.md_flags |= MDB_INTEGERKEY;
7241 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7242 mx->mx_db.md_root));
7243 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
7244 #if UINT_MAX < SIZE_MAX
7245 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
7246 mx->mx_dbx.md_cmp = mdb_cmp_clong;
7251 /** Fixup a sorted-dups cursor due to underlying update.
7252 * Sets up some fields that depend on the data from the main cursor.
7253 * Almost the same as init1, but skips initialization steps if the
7254 * xcursor had already been used.
7255 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
7256 * @param[in] src_mx The xcursor of an up-to-date cursor.
7257 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
7260 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
7262 MDB_xcursor *mx = mc->mc_xcursor;
7265 mx->mx_cursor.mc_snum = 1;
7266 mx->mx_cursor.mc_top = 0;
7267 mx->mx_cursor.mc_flags |= C_INITIALIZED;
7268 mx->mx_cursor.mc_ki[0] = 0;
7269 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
7270 #if UINT_MAX < SIZE_MAX
7271 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
7273 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
7276 mx->mx_db = src_mx->mx_db;
7277 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
7278 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7279 mx->mx_db.md_root));
7282 /** Initialize a cursor for a given transaction and database. */
7284 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
7287 mc->mc_backup = NULL;
7290 mc->mc_db = &txn->mt_dbs[dbi];
7291 mc->mc_dbx = &txn->mt_dbxs[dbi];
7292 mc->mc_dbflag = &txn->mt_dbflags[dbi];
7298 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
7299 mdb_tassert(txn, mx != NULL);
7300 mc->mc_xcursor = mx;
7301 mdb_xcursor_init0(mc);
7303 mc->mc_xcursor = NULL;
7305 if (*mc->mc_dbflag & DB_STALE) {
7306 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
7311 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
7314 size_t size = sizeof(MDB_cursor);
7316 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
7319 if (txn->mt_flags & MDB_TXN_BLOCKED)
7322 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7325 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
7326 size += sizeof(MDB_xcursor);
7328 if ((mc = malloc(size)) != NULL) {
7329 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
7330 if (txn->mt_cursors) {
7331 mc->mc_next = txn->mt_cursors[dbi];
7332 txn->mt_cursors[dbi] = mc;
7333 mc->mc_flags |= C_UNTRACK;
7345 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
7347 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
7350 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
7353 if (txn->mt_flags & MDB_TXN_BLOCKED)
7356 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
7360 /* Return the count of duplicate data items for the current key */
7362 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7366 if (mc == NULL || countp == NULL)
7369 if (mc->mc_xcursor == NULL)
7370 return MDB_INCOMPATIBLE;
7372 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
7375 if (!(mc->mc_flags & C_INITIALIZED))
7378 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
7379 return MDB_NOTFOUND;
7381 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7382 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7385 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7388 *countp = mc->mc_xcursor->mx_db.md_entries;
7394 mdb_cursor_close(MDB_cursor *mc)
7396 if (mc && !mc->mc_backup) {
7397 /* remove from txn, if tracked */
7398 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7399 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7400 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7402 *prev = mc->mc_next;
7409 mdb_cursor_txn(MDB_cursor *mc)
7411 if (!mc) return NULL;
7416 mdb_cursor_dbi(MDB_cursor *mc)
7421 /** Replace the key for a branch node with a new key.
7422 * @param[in] mc Cursor pointing to the node to operate on.
7423 * @param[in] key The new key to use.
7424 * @return 0 on success, non-zero on failure.
7427 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7433 int delta, ksize, oksize;
7434 indx_t ptr, i, numkeys, indx;
7437 indx = mc->mc_ki[mc->mc_top];
7438 mp = mc->mc_pg[mc->mc_top];
7439 node = NODEPTR(mp, indx);
7440 ptr = mp->mp_ptrs[indx];
7444 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7445 k2.mv_data = NODEKEY(node);
7446 k2.mv_size = node->mn_ksize;
7447 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7449 mdb_dkey(&k2, kbuf2),
7455 /* Sizes must be 2-byte aligned. */
7456 ksize = EVEN(key->mv_size);
7457 oksize = EVEN(node->mn_ksize);
7458 delta = ksize - oksize;
7460 /* Shift node contents if EVEN(key length) changed. */
7462 if (delta > 0 && SIZELEFT(mp) < delta) {
7464 /* not enough space left, do a delete and split */
7465 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7466 pgno = NODEPGNO(node);
7467 mdb_node_del(mc, 0);
7468 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7471 numkeys = NUMKEYS(mp);
7472 for (i = 0; i < numkeys; i++) {
7473 if (mp->mp_ptrs[i] <= ptr)
7474 mp->mp_ptrs[i] -= delta;
7477 base = (char *)mp + mp->mp_upper + PAGEBASE;
7478 len = ptr - mp->mp_upper + NODESIZE;
7479 memmove(base - delta, base, len);
7480 mp->mp_upper -= delta;
7482 node = NODEPTR(mp, indx);
7485 /* But even if no shift was needed, update ksize */
7486 if (node->mn_ksize != key->mv_size)
7487 node->mn_ksize = key->mv_size;
7490 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7496 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7498 /** Move a node from csrc to cdst.
7501 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
7508 unsigned short flags;
7512 /* Mark src and dst as dirty. */
7513 if ((rc = mdb_page_touch(csrc)) ||
7514 (rc = mdb_page_touch(cdst)))
7517 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7518 key.mv_size = csrc->mc_db->md_pad;
7519 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7521 data.mv_data = NULL;
7525 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7526 mdb_cassert(csrc, !((size_t)srcnode & 1));
7527 srcpg = NODEPGNO(srcnode);
7528 flags = srcnode->mn_flags;
7529 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7530 unsigned int snum = csrc->mc_snum;
7532 /* must find the lowest key below src */
7533 rc = mdb_page_search_lowest(csrc);
7536 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7537 key.mv_size = csrc->mc_db->md_pad;
7538 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7540 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7541 key.mv_size = NODEKSZ(s2);
7542 key.mv_data = NODEKEY(s2);
7544 csrc->mc_snum = snum--;
7545 csrc->mc_top = snum;
7547 key.mv_size = NODEKSZ(srcnode);
7548 key.mv_data = NODEKEY(srcnode);
7550 data.mv_size = NODEDSZ(srcnode);
7551 data.mv_data = NODEDATA(srcnode);
7553 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7554 unsigned int snum = cdst->mc_snum;
7557 /* must find the lowest key below dst */
7558 mdb_cursor_copy(cdst, &mn);
7559 rc = mdb_page_search_lowest(&mn);
7562 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7563 bkey.mv_size = mn.mc_db->md_pad;
7564 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7566 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7567 bkey.mv_size = NODEKSZ(s2);
7568 bkey.mv_data = NODEKEY(s2);
7570 mn.mc_snum = snum--;
7573 rc = mdb_update_key(&mn, &bkey);
7578 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7579 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7580 csrc->mc_ki[csrc->mc_top],
7582 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7583 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7585 /* Add the node to the destination page.
7587 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7588 if (rc != MDB_SUCCESS)
7591 /* Delete the node from the source page.
7593 mdb_node_del(csrc, key.mv_size);
7596 /* Adjust other cursors pointing to mp */
7597 MDB_cursor *m2, *m3;
7598 MDB_dbi dbi = csrc->mc_dbi;
7599 MDB_page *mpd, *mps;
7601 mps = csrc->mc_pg[csrc->mc_top];
7602 /* If we're adding on the left, bump others up */
7603 if (!cdst->mc_ki[csrc->mc_top]) {
7604 mpd = cdst->mc_pg[csrc->mc_top];
7605 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7606 if (csrc->mc_flags & C_SUB)
7607 m3 = &m2->mc_xcursor->mx_cursor;
7611 m3->mc_pg[csrc->mc_top] == mpd &&
7612 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
7613 m3->mc_ki[csrc->mc_top]++;
7616 m3->mc_pg[csrc->mc_top] == mps &&
7617 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
7618 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7619 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7620 m3->mc_ki[csrc->mc_top-1]++;
7624 /* Adding on the right, bump others down */
7626 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7627 if (csrc->mc_flags & C_SUB)
7628 m3 = &m2->mc_xcursor->mx_cursor;
7631 if (m3 == csrc) continue;
7632 if (m3->mc_pg[csrc->mc_top] == mps) {
7633 if (!m3->mc_ki[csrc->mc_top]) {
7634 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7635 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7636 m3->mc_ki[csrc->mc_top-1]--;
7638 m3->mc_ki[csrc->mc_top]--;
7645 /* Update the parent separators.
7647 if (csrc->mc_ki[csrc->mc_top] == 0) {
7648 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7649 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7650 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7652 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7653 key.mv_size = NODEKSZ(srcnode);
7654 key.mv_data = NODEKEY(srcnode);
7656 DPRINTF(("update separator for source page %"Z"u to [%s]",
7657 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7658 mdb_cursor_copy(csrc, &mn);
7661 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7664 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7666 indx_t ix = csrc->mc_ki[csrc->mc_top];
7667 nullkey.mv_size = 0;
7668 csrc->mc_ki[csrc->mc_top] = 0;
7669 rc = mdb_update_key(csrc, &nullkey);
7670 csrc->mc_ki[csrc->mc_top] = ix;
7671 mdb_cassert(csrc, rc == MDB_SUCCESS);
7675 if (cdst->mc_ki[cdst->mc_top] == 0) {
7676 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7677 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7678 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7680 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7681 key.mv_size = NODEKSZ(srcnode);
7682 key.mv_data = NODEKEY(srcnode);
7684 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7685 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7686 mdb_cursor_copy(cdst, &mn);
7689 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7692 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7694 indx_t ix = cdst->mc_ki[cdst->mc_top];
7695 nullkey.mv_size = 0;
7696 cdst->mc_ki[cdst->mc_top] = 0;
7697 rc = mdb_update_key(cdst, &nullkey);
7698 cdst->mc_ki[cdst->mc_top] = ix;
7699 mdb_cassert(cdst, rc == MDB_SUCCESS);
7706 /** Merge one page into another.
7707 * The nodes from the page pointed to by \b csrc will
7708 * be copied to the page pointed to by \b cdst and then
7709 * the \b csrc page will be freed.
7710 * @param[in] csrc Cursor pointing to the source page.
7711 * @param[in] cdst Cursor pointing to the destination page.
7712 * @return 0 on success, non-zero on failure.
7715 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7717 MDB_page *psrc, *pdst;
7724 psrc = csrc->mc_pg[csrc->mc_top];
7725 pdst = cdst->mc_pg[cdst->mc_top];
7727 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7729 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7730 mdb_cassert(csrc, cdst->mc_snum > 1);
7732 /* Mark dst as dirty. */
7733 if ((rc = mdb_page_touch(cdst)))
7736 /* Move all nodes from src to dst.
7738 j = nkeys = NUMKEYS(pdst);
7739 if (IS_LEAF2(psrc)) {
7740 key.mv_size = csrc->mc_db->md_pad;
7741 key.mv_data = METADATA(psrc);
7742 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7743 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7744 if (rc != MDB_SUCCESS)
7746 key.mv_data = (char *)key.mv_data + key.mv_size;
7749 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7750 srcnode = NODEPTR(psrc, i);
7751 if (i == 0 && IS_BRANCH(psrc)) {
7754 mdb_cursor_copy(csrc, &mn);
7755 /* must find the lowest key below src */
7756 rc = mdb_page_search_lowest(&mn);
7759 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7760 key.mv_size = mn.mc_db->md_pad;
7761 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7763 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7764 key.mv_size = NODEKSZ(s2);
7765 key.mv_data = NODEKEY(s2);
7768 key.mv_size = srcnode->mn_ksize;
7769 key.mv_data = NODEKEY(srcnode);
7772 data.mv_size = NODEDSZ(srcnode);
7773 data.mv_data = NODEDATA(srcnode);
7774 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7775 if (rc != MDB_SUCCESS)
7780 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7781 pdst->mp_pgno, NUMKEYS(pdst),
7782 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7784 /* Unlink the src page from parent and add to free list.
7787 mdb_node_del(csrc, 0);
7788 if (csrc->mc_ki[csrc->mc_top] == 0) {
7790 rc = mdb_update_key(csrc, &key);
7798 psrc = csrc->mc_pg[csrc->mc_top];
7799 /* If not operating on FreeDB, allow this page to be reused
7800 * in this txn. Otherwise just add to free list.
7802 rc = mdb_page_loose(csrc, psrc);
7806 csrc->mc_db->md_leaf_pages--;
7808 csrc->mc_db->md_branch_pages--;
7810 /* Adjust other cursors pointing to mp */
7811 MDB_cursor *m2, *m3;
7812 MDB_dbi dbi = csrc->mc_dbi;
7813 unsigned int top = csrc->mc_top;
7815 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7816 if (csrc->mc_flags & C_SUB)
7817 m3 = &m2->mc_xcursor->mx_cursor;
7820 if (m3 == csrc) continue;
7821 if (m3->mc_snum < csrc->mc_snum) continue;
7822 if (m3->mc_pg[top] == psrc) {
7823 m3->mc_pg[top] = pdst;
7824 m3->mc_ki[top] += nkeys;
7825 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
7830 unsigned int snum = cdst->mc_snum;
7831 uint16_t depth = cdst->mc_db->md_depth;
7832 mdb_cursor_pop(cdst);
7833 rc = mdb_rebalance(cdst);
7834 /* Did the tree height change? */
7835 if (depth != cdst->mc_db->md_depth)
7836 snum += cdst->mc_db->md_depth - depth;
7837 cdst->mc_snum = snum;
7838 cdst->mc_top = snum-1;
7843 /** Copy the contents of a cursor.
7844 * @param[in] csrc The cursor to copy from.
7845 * @param[out] cdst The cursor to copy to.
7848 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7852 cdst->mc_txn = csrc->mc_txn;
7853 cdst->mc_dbi = csrc->mc_dbi;
7854 cdst->mc_db = csrc->mc_db;
7855 cdst->mc_dbx = csrc->mc_dbx;
7856 cdst->mc_snum = csrc->mc_snum;
7857 cdst->mc_top = csrc->mc_top;
7858 cdst->mc_flags = csrc->mc_flags;
7860 for (i=0; i<csrc->mc_snum; i++) {
7861 cdst->mc_pg[i] = csrc->mc_pg[i];
7862 cdst->mc_ki[i] = csrc->mc_ki[i];
7866 /** Rebalance the tree after a delete operation.
7867 * @param[in] mc Cursor pointing to the page where rebalancing
7869 * @return 0 on success, non-zero on failure.
7872 mdb_rebalance(MDB_cursor *mc)
7876 unsigned int ptop, minkeys, thresh;
7880 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
7885 thresh = FILL_THRESHOLD;
7887 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7888 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7889 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7890 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7892 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
7893 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7894 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7895 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7899 if (mc->mc_snum < 2) {
7900 MDB_page *mp = mc->mc_pg[0];
7902 DPUTS("Can't rebalance a subpage, ignoring");
7905 if (NUMKEYS(mp) == 0) {
7906 DPUTS("tree is completely empty");
7907 mc->mc_db->md_root = P_INVALID;
7908 mc->mc_db->md_depth = 0;
7909 mc->mc_db->md_leaf_pages = 0;
7910 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7913 /* Adjust cursors pointing to mp */
7916 mc->mc_flags &= ~C_INITIALIZED;
7918 MDB_cursor *m2, *m3;
7919 MDB_dbi dbi = mc->mc_dbi;
7921 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7922 if (mc->mc_flags & C_SUB)
7923 m3 = &m2->mc_xcursor->mx_cursor;
7926 if (m3->mc_snum < mc->mc_snum) continue;
7927 if (m3->mc_pg[0] == mp) {
7930 m3->mc_flags &= ~C_INITIALIZED;
7934 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7936 DPUTS("collapsing root page!");
7937 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7940 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7941 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7944 mc->mc_db->md_depth--;
7945 mc->mc_db->md_branch_pages--;
7946 mc->mc_ki[0] = mc->mc_ki[1];
7947 for (i = 1; i<mc->mc_db->md_depth; i++) {
7948 mc->mc_pg[i] = mc->mc_pg[i+1];
7949 mc->mc_ki[i] = mc->mc_ki[i+1];
7952 /* Adjust other cursors pointing to mp */
7953 MDB_cursor *m2, *m3;
7954 MDB_dbi dbi = mc->mc_dbi;
7956 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7957 if (mc->mc_flags & C_SUB)
7958 m3 = &m2->mc_xcursor->mx_cursor;
7961 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7962 if (m3->mc_pg[0] == mp) {
7963 for (i=0; i<m3->mc_snum; i++) {
7964 m3->mc_pg[i] = m3->mc_pg[i+1];
7965 m3->mc_ki[i] = m3->mc_ki[i+1];
7973 DPUTS("root page doesn't need rebalancing");
7977 /* The parent (branch page) must have at least 2 pointers,
7978 * otherwise the tree is invalid.
7980 ptop = mc->mc_top-1;
7981 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
7983 /* Leaf page fill factor is below the threshold.
7984 * Try to move keys from left or right neighbor, or
7985 * merge with a neighbor page.
7990 mdb_cursor_copy(mc, &mn);
7991 mn.mc_xcursor = NULL;
7993 oldki = mc->mc_ki[mc->mc_top];
7994 if (mc->mc_ki[ptop] == 0) {
7995 /* We're the leftmost leaf in our parent.
7997 DPUTS("reading right neighbor");
7999 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8000 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
8003 mn.mc_ki[mn.mc_top] = 0;
8004 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
8006 /* There is at least one neighbor to the left.
8008 DPUTS("reading left neighbor");
8010 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8011 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
8014 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
8015 mc->mc_ki[mc->mc_top] = 0;
8018 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
8019 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
8020 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
8022 /* If the neighbor page is above threshold and has enough keys,
8023 * move one key from it. Otherwise we should try to merge them.
8024 * (A branch page must never have less than 2 keys.)
8026 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
8027 rc = mdb_node_move(&mn, mc);
8028 if (!mc->mc_ki[mc->mc_top]) {
8029 /* if we inserted on left, bump position up */
8033 if (mc->mc_ki[ptop] == 0) {
8034 rc = mdb_page_merge(&mn, mc);
8037 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
8038 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
8039 /* We want mdb_rebalance to find mn when doing fixups */
8040 if (mc->mc_flags & C_SUB) {
8041 dummy.mc_next = mc->mc_txn->mt_cursors[mc->mc_dbi];
8042 mc->mc_txn->mt_cursors[mc->mc_dbi] = &dummy;
8043 dummy.mc_xcursor = (MDB_xcursor *)&mn;
8045 mn.mc_next = mc->mc_txn->mt_cursors[mc->mc_dbi];
8046 mc->mc_txn->mt_cursors[mc->mc_dbi] = &mn;
8048 rc = mdb_page_merge(mc, &mn);
8049 if (mc->mc_flags & C_SUB)
8050 mc->mc_txn->mt_cursors[mc->mc_dbi] = dummy.mc_next;
8052 mc->mc_txn->mt_cursors[mc->mc_dbi] = mn.mc_next;
8053 mdb_cursor_copy(&mn, mc);
8055 mc->mc_flags &= ~C_EOF;
8057 mc->mc_ki[mc->mc_top] = oldki;
8061 /** Complete a delete operation started by #mdb_cursor_del(). */
8063 mdb_cursor_del0(MDB_cursor *mc)
8069 MDB_cursor *m2, *m3;
8070 MDB_dbi dbi = mc->mc_dbi;
8072 ki = mc->mc_ki[mc->mc_top];
8073 mp = mc->mc_pg[mc->mc_top];
8074 mdb_node_del(mc, mc->mc_db->md_pad);
8075 mc->mc_db->md_entries--;
8077 /* Adjust other cursors pointing to mp */
8078 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8079 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8080 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8082 if (m3 == mc || m3->mc_snum < mc->mc_snum)
8084 if (m3->mc_pg[mc->mc_top] == mp) {
8085 if (m3->mc_ki[mc->mc_top] >= ki) {
8086 m3->mc_flags |= C_DEL;
8087 if (m3->mc_ki[mc->mc_top] > ki)
8088 m3->mc_ki[mc->mc_top]--;
8089 else if (mc->mc_db->md_flags & MDB_DUPSORT)
8090 m3->mc_xcursor->mx_cursor.mc_flags |= C_EOF;
8095 rc = mdb_rebalance(mc);
8097 if (rc == MDB_SUCCESS) {
8098 /* DB is totally empty now, just bail out.
8099 * Other cursors adjustments were already done
8100 * by mdb_rebalance and aren't needed here.
8105 mp = mc->mc_pg[mc->mc_top];
8106 nkeys = NUMKEYS(mp);
8108 /* Adjust other cursors pointing to mp */
8109 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
8110 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8111 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8113 if (m3->mc_snum < mc->mc_snum)
8115 if (m3->mc_pg[mc->mc_top] == mp) {
8116 /* if m3 points past last node in page, find next sibling */
8117 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8118 rc = mdb_cursor_sibling(m3, 1);
8119 if (rc == MDB_NOTFOUND) {
8120 m3->mc_flags |= C_EOF;
8126 mc->mc_flags |= C_DEL;
8130 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8135 mdb_del(MDB_txn *txn, MDB_dbi dbi,
8136 MDB_val *key, MDB_val *data)
8138 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8141 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8142 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8144 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
8145 /* must ignore any data */
8149 return mdb_del0(txn, dbi, key, data, 0);
8153 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
8154 MDB_val *key, MDB_val *data, unsigned flags)
8159 MDB_val rdata, *xdata;
8163 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
8165 mdb_cursor_init(&mc, txn, dbi, &mx);
8174 flags |= MDB_NODUPDATA;
8176 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
8178 /* let mdb_page_split know about this cursor if needed:
8179 * delete will trigger a rebalance; if it needs to move
8180 * a node from one page to another, it will have to
8181 * update the parent's separator key(s). If the new sepkey
8182 * is larger than the current one, the parent page may
8183 * run out of space, triggering a split. We need this
8184 * cursor to be consistent until the end of the rebalance.
8186 mc.mc_flags |= C_UNTRACK;
8187 mc.mc_next = txn->mt_cursors[dbi];
8188 txn->mt_cursors[dbi] = &mc;
8189 rc = mdb_cursor_del(&mc, flags);
8190 txn->mt_cursors[dbi] = mc.mc_next;
8195 /** Split a page and insert a new node.
8196 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
8197 * The cursor will be updated to point to the actual page and index where
8198 * the node got inserted after the split.
8199 * @param[in] newkey The key for the newly inserted node.
8200 * @param[in] newdata The data for the newly inserted node.
8201 * @param[in] newpgno The page number, if the new node is a branch node.
8202 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
8203 * @return 0 on success, non-zero on failure.
8206 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
8207 unsigned int nflags)
8210 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
8213 int i, j, split_indx, nkeys, pmax;
8214 MDB_env *env = mc->mc_txn->mt_env;
8216 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
8217 MDB_page *copy = NULL;
8218 MDB_page *mp, *rp, *pp;
8223 mp = mc->mc_pg[mc->mc_top];
8224 newindx = mc->mc_ki[mc->mc_top];
8225 nkeys = NUMKEYS(mp);
8227 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
8228 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
8229 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
8231 /* Create a right sibling. */
8232 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
8234 rp->mp_pad = mp->mp_pad;
8235 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
8237 if (mc->mc_snum < 2) {
8238 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
8240 /* shift current top to make room for new parent */
8241 mc->mc_pg[1] = mc->mc_pg[0];
8242 mc->mc_ki[1] = mc->mc_ki[0];
8245 mc->mc_db->md_root = pp->mp_pgno;
8246 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
8247 new_root = mc->mc_db->md_depth++;
8249 /* Add left (implicit) pointer. */
8250 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
8251 /* undo the pre-push */
8252 mc->mc_pg[0] = mc->mc_pg[1];
8253 mc->mc_ki[0] = mc->mc_ki[1];
8254 mc->mc_db->md_root = mp->mp_pgno;
8255 mc->mc_db->md_depth--;
8262 ptop = mc->mc_top-1;
8263 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
8266 mc->mc_flags |= C_SPLITTING;
8267 mdb_cursor_copy(mc, &mn);
8268 mn.mc_pg[mn.mc_top] = rp;
8269 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
8271 if (nflags & MDB_APPEND) {
8272 mn.mc_ki[mn.mc_top] = 0;
8274 split_indx = newindx;
8278 split_indx = (nkeys+1) / 2;
8283 unsigned int lsize, rsize, ksize;
8284 /* Move half of the keys to the right sibling */
8285 x = mc->mc_ki[mc->mc_top] - split_indx;
8286 ksize = mc->mc_db->md_pad;
8287 split = LEAF2KEY(mp, split_indx, ksize);
8288 rsize = (nkeys - split_indx) * ksize;
8289 lsize = (nkeys - split_indx) * sizeof(indx_t);
8290 mp->mp_lower -= lsize;
8291 rp->mp_lower += lsize;
8292 mp->mp_upper += rsize - lsize;
8293 rp->mp_upper -= rsize - lsize;
8294 sepkey.mv_size = ksize;
8295 if (newindx == split_indx) {
8296 sepkey.mv_data = newkey->mv_data;
8298 sepkey.mv_data = split;
8301 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
8302 memcpy(rp->mp_ptrs, split, rsize);
8303 sepkey.mv_data = rp->mp_ptrs;
8304 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
8305 memcpy(ins, newkey->mv_data, ksize);
8306 mp->mp_lower += sizeof(indx_t);
8307 mp->mp_upper -= ksize - sizeof(indx_t);
8310 memcpy(rp->mp_ptrs, split, x * ksize);
8311 ins = LEAF2KEY(rp, x, ksize);
8312 memcpy(ins, newkey->mv_data, ksize);
8313 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
8314 rp->mp_lower += sizeof(indx_t);
8315 rp->mp_upper -= ksize - sizeof(indx_t);
8316 mc->mc_ki[mc->mc_top] = x;
8317 mc->mc_pg[mc->mc_top] = rp;
8321 int psize, nsize, k;
8322 /* Maximum free space in an empty page */
8323 pmax = env->me_psize - PAGEHDRSZ;
8325 nsize = mdb_leaf_size(env, newkey, newdata);
8327 nsize = mdb_branch_size(env, newkey);
8328 nsize = EVEN(nsize);
8330 /* grab a page to hold a temporary copy */
8331 copy = mdb_page_malloc(mc->mc_txn, 1);
8336 copy->mp_pgno = mp->mp_pgno;
8337 copy->mp_flags = mp->mp_flags;
8338 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
8339 copy->mp_upper = env->me_psize - PAGEBASE;
8341 /* prepare to insert */
8342 for (i=0, j=0; i<nkeys; i++) {
8344 copy->mp_ptrs[j++] = 0;
8346 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
8349 /* When items are relatively large the split point needs
8350 * to be checked, because being off-by-one will make the
8351 * difference between success or failure in mdb_node_add.
8353 * It's also relevant if a page happens to be laid out
8354 * such that one half of its nodes are all "small" and
8355 * the other half of its nodes are "large." If the new
8356 * item is also "large" and falls on the half with
8357 * "large" nodes, it also may not fit.
8359 * As a final tweak, if the new item goes on the last
8360 * spot on the page (and thus, onto the new page), bias
8361 * the split so the new page is emptier than the old page.
8362 * This yields better packing during sequential inserts.
8364 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
8365 /* Find split point */
8367 if (newindx <= split_indx || newindx >= nkeys) {
8369 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
8374 for (; i!=k; i+=j) {
8379 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8380 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
8382 if (F_ISSET(node->mn_flags, F_BIGDATA))
8383 psize += sizeof(pgno_t);
8385 psize += NODEDSZ(node);
8387 psize = EVEN(psize);
8389 if (psize > pmax || i == k-j) {
8390 split_indx = i + (j<0);
8395 if (split_indx == newindx) {
8396 sepkey.mv_size = newkey->mv_size;
8397 sepkey.mv_data = newkey->mv_data;
8399 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
8400 sepkey.mv_size = node->mn_ksize;
8401 sepkey.mv_data = NODEKEY(node);
8406 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
8408 /* Copy separator key to the parent.
8410 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
8414 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
8419 if (mn.mc_snum == mc->mc_snum) {
8420 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
8421 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
8422 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
8423 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
8428 /* Right page might now have changed parent.
8429 * Check if left page also changed parent.
8431 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8432 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8433 for (i=0; i<ptop; i++) {
8434 mc->mc_pg[i] = mn.mc_pg[i];
8435 mc->mc_ki[i] = mn.mc_ki[i];
8437 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8438 if (mn.mc_ki[ptop]) {
8439 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8441 /* find right page's left sibling */
8442 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8443 mdb_cursor_sibling(mc, 0);
8448 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8451 mc->mc_flags ^= C_SPLITTING;
8452 if (rc != MDB_SUCCESS) {
8455 if (nflags & MDB_APPEND) {
8456 mc->mc_pg[mc->mc_top] = rp;
8457 mc->mc_ki[mc->mc_top] = 0;
8458 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8461 for (i=0; i<mc->mc_top; i++)
8462 mc->mc_ki[i] = mn.mc_ki[i];
8463 } else if (!IS_LEAF2(mp)) {
8465 mc->mc_pg[mc->mc_top] = rp;
8470 rkey.mv_data = newkey->mv_data;
8471 rkey.mv_size = newkey->mv_size;
8477 /* Update index for the new key. */
8478 mc->mc_ki[mc->mc_top] = j;
8480 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8481 rkey.mv_data = NODEKEY(node);
8482 rkey.mv_size = node->mn_ksize;
8484 xdata.mv_data = NODEDATA(node);
8485 xdata.mv_size = NODEDSZ(node);
8488 pgno = NODEPGNO(node);
8489 flags = node->mn_flags;
8492 if (!IS_LEAF(mp) && j == 0) {
8493 /* First branch index doesn't need key data. */
8497 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8503 mc->mc_pg[mc->mc_top] = copy;
8508 } while (i != split_indx);
8510 nkeys = NUMKEYS(copy);
8511 for (i=0; i<nkeys; i++)
8512 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8513 mp->mp_lower = copy->mp_lower;
8514 mp->mp_upper = copy->mp_upper;
8515 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8516 env->me_psize - copy->mp_upper - PAGEBASE);
8518 /* reset back to original page */
8519 if (newindx < split_indx) {
8520 mc->mc_pg[mc->mc_top] = mp;
8521 if (nflags & MDB_RESERVE) {
8522 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
8523 if (!(node->mn_flags & F_BIGDATA))
8524 newdata->mv_data = NODEDATA(node);
8527 mc->mc_pg[mc->mc_top] = rp;
8529 /* Make sure mc_ki is still valid.
8531 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8532 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8533 for (i=0; i<=ptop; i++) {
8534 mc->mc_pg[i] = mn.mc_pg[i];
8535 mc->mc_ki[i] = mn.mc_ki[i];
8542 /* Adjust other cursors pointing to mp */
8543 MDB_cursor *m2, *m3;
8544 MDB_dbi dbi = mc->mc_dbi;
8545 int fixup = NUMKEYS(mp);
8547 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8548 if (mc->mc_flags & C_SUB)
8549 m3 = &m2->mc_xcursor->mx_cursor;
8554 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8556 if (m3->mc_flags & C_SPLITTING)
8561 for (k=new_root; k>=0; k--) {
8562 m3->mc_ki[k+1] = m3->mc_ki[k];
8563 m3->mc_pg[k+1] = m3->mc_pg[k];
8565 if (m3->mc_ki[0] >= split_indx) {
8570 m3->mc_pg[0] = mc->mc_pg[0];
8574 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8575 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8576 m3->mc_ki[mc->mc_top]++;
8577 if (m3->mc_ki[mc->mc_top] >= fixup) {
8578 m3->mc_pg[mc->mc_top] = rp;
8579 m3->mc_ki[mc->mc_top] -= fixup;
8580 m3->mc_ki[ptop] = mn.mc_ki[ptop];
8582 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8583 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8588 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8591 if (copy) /* tmp page */
8592 mdb_page_free(env, copy);
8594 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8599 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8600 MDB_val *key, MDB_val *data, unsigned int flags)
8605 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8608 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
8611 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8612 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8614 mdb_cursor_init(&mc, txn, dbi, &mx);
8615 return mdb_cursor_put(&mc, key, data, flags);
8619 #define MDB_WBUF (1024*1024)
8622 /** State needed for a compacting copy. */
8623 typedef struct mdb_copy {
8624 pthread_mutex_t mc_mutex;
8625 pthread_cond_t mc_cond;
8632 pgno_t mc_next_pgno;
8635 volatile int mc_new;
8640 /** Dedicated writer thread for compacting copy. */
8641 static THREAD_RET ESECT CALL_CONV
8642 mdb_env_copythr(void *arg)
8646 int toggle = 0, wsize, rc;
8649 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8652 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8655 pthread_mutex_lock(&my->mc_mutex);
8657 pthread_cond_signal(&my->mc_cond);
8660 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8661 if (my->mc_new < 0) {
8666 wsize = my->mc_wlen[toggle];
8667 ptr = my->mc_wbuf[toggle];
8670 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8674 } else if (len > 0) {
8688 /* If there's an overflow page tail, write it too */
8689 if (my->mc_olen[toggle]) {
8690 wsize = my->mc_olen[toggle];
8691 ptr = my->mc_over[toggle];
8692 my->mc_olen[toggle] = 0;
8695 my->mc_wlen[toggle] = 0;
8697 pthread_cond_signal(&my->mc_cond);
8699 pthread_cond_signal(&my->mc_cond);
8700 pthread_mutex_unlock(&my->mc_mutex);
8701 return (THREAD_RET)0;
8705 /** Tell the writer thread there's a buffer ready to write */
8707 mdb_env_cthr_toggle(mdb_copy *my, int st)
8709 int toggle = my->mc_toggle ^ 1;
8710 pthread_mutex_lock(&my->mc_mutex);
8711 if (my->mc_status) {
8712 pthread_mutex_unlock(&my->mc_mutex);
8713 return my->mc_status;
8715 while (my->mc_new == 1)
8716 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8718 my->mc_toggle = toggle;
8719 pthread_cond_signal(&my->mc_cond);
8720 pthread_mutex_unlock(&my->mc_mutex);
8724 /** Depth-first tree traversal for compacting copy. */
8726 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8729 MDB_txn *txn = my->mc_txn;
8731 MDB_page *mo, *mp, *leaf;
8736 /* Empty DB, nothing to do */
8737 if (*pg == P_INVALID)
8744 rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
8747 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8751 /* Make cursor pages writable */
8752 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8756 for (i=0; i<mc.mc_top; i++) {
8757 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8758 mc.mc_pg[i] = (MDB_page *)ptr;
8759 ptr += my->mc_env->me_psize;
8762 /* This is writable space for a leaf page. Usually not needed. */
8763 leaf = (MDB_page *)ptr;
8765 toggle = my->mc_toggle;
8766 while (mc.mc_snum > 0) {
8768 mp = mc.mc_pg[mc.mc_top];
8772 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8773 for (i=0; i<n; i++) {
8774 ni = NODEPTR(mp, i);
8775 if (ni->mn_flags & F_BIGDATA) {
8779 /* Need writable leaf */
8781 mc.mc_pg[mc.mc_top] = leaf;
8782 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8784 ni = NODEPTR(mp, i);
8787 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8788 rc = mdb_page_get(txn, pg, &omp, NULL);
8791 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8792 rc = mdb_env_cthr_toggle(my, 1);
8795 toggle = my->mc_toggle;
8797 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8798 memcpy(mo, omp, my->mc_env->me_psize);
8799 mo->mp_pgno = my->mc_next_pgno;
8800 my->mc_next_pgno += omp->mp_pages;
8801 my->mc_wlen[toggle] += my->mc_env->me_psize;
8802 if (omp->mp_pages > 1) {
8803 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
8804 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
8805 rc = mdb_env_cthr_toggle(my, 1);
8808 toggle = my->mc_toggle;
8810 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
8811 } else if (ni->mn_flags & F_SUBDATA) {
8814 /* Need writable leaf */
8816 mc.mc_pg[mc.mc_top] = leaf;
8817 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8819 ni = NODEPTR(mp, i);
8822 memcpy(&db, NODEDATA(ni), sizeof(db));
8823 my->mc_toggle = toggle;
8824 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
8827 toggle = my->mc_toggle;
8828 memcpy(NODEDATA(ni), &db, sizeof(db));
8833 mc.mc_ki[mc.mc_top]++;
8834 if (mc.mc_ki[mc.mc_top] < n) {
8837 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
8839 rc = mdb_page_get(txn, pg, &mp, NULL);
8844 mc.mc_ki[mc.mc_top] = 0;
8845 if (IS_BRANCH(mp)) {
8846 /* Whenever we advance to a sibling branch page,
8847 * we must proceed all the way down to its first leaf.
8849 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
8852 mc.mc_pg[mc.mc_top] = mp;
8856 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8857 rc = mdb_env_cthr_toggle(my, 1);
8860 toggle = my->mc_toggle;
8862 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8863 mdb_page_copy(mo, mp, my->mc_env->me_psize);
8864 mo->mp_pgno = my->mc_next_pgno++;
8865 my->mc_wlen[toggle] += my->mc_env->me_psize;
8867 /* Update parent if there is one */
8868 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
8869 SETPGNO(ni, mo->mp_pgno);
8870 mdb_cursor_pop(&mc);
8872 /* Otherwise we're done */
8882 /** Copy environment with compaction. */
8884 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
8889 MDB_txn *txn = NULL;
8894 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
8895 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
8896 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
8897 if (my.mc_wbuf[0] == NULL)
8900 pthread_mutex_init(&my.mc_mutex, NULL);
8901 pthread_cond_init(&my.mc_cond, NULL);
8902 #ifdef HAVE_MEMALIGN
8903 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
8904 if (my.mc_wbuf[0] == NULL)
8907 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_os_psize, MDB_WBUF*2);
8912 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
8913 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
8918 my.mc_next_pgno = NUM_METAS;
8924 THREAD_CREATE(thr, mdb_env_copythr, &my);
8926 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8930 mp = (MDB_page *)my.mc_wbuf[0];
8931 memset(mp, 0, NUM_METAS * env->me_psize);
8933 mp->mp_flags = P_META;
8934 mm = (MDB_meta *)METADATA(mp);
8935 mdb_env_init_meta0(env, mm);
8936 mm->mm_address = env->me_metas[0]->mm_address;
8938 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
8940 mp->mp_flags = P_META;
8941 *(MDB_meta *)METADATA(mp) = *mm;
8942 mm = (MDB_meta *)METADATA(mp);
8944 /* Count the number of free pages, subtract from lastpg to find
8945 * number of active pages
8948 MDB_ID freecount = 0;
8951 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
8952 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
8953 freecount += *(MDB_ID *)data.mv_data;
8954 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
8955 txn->mt_dbs[FREE_DBI].md_leaf_pages +
8956 txn->mt_dbs[FREE_DBI].md_overflow_pages;
8958 /* Set metapage 1 */
8959 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
8960 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
8961 if (mm->mm_last_pg > NUM_METAS-1) {
8962 mm->mm_dbs[MAIN_DBI].md_root = mm->mm_last_pg;
8965 mm->mm_dbs[MAIN_DBI].md_root = P_INVALID;
8968 my.mc_wlen[0] = env->me_psize * NUM_METAS;
8970 pthread_mutex_lock(&my.mc_mutex);
8972 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8973 pthread_mutex_unlock(&my.mc_mutex);
8974 rc = mdb_env_cwalk(&my, &txn->mt_dbs[MAIN_DBI].md_root, 0);
8975 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
8976 rc = mdb_env_cthr_toggle(&my, 1);
8977 mdb_env_cthr_toggle(&my, -1);
8978 pthread_mutex_lock(&my.mc_mutex);
8980 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8981 pthread_mutex_unlock(&my.mc_mutex);
8986 CloseHandle(my.mc_cond);
8987 CloseHandle(my.mc_mutex);
8988 _aligned_free(my.mc_wbuf[0]);
8990 pthread_cond_destroy(&my.mc_cond);
8991 pthread_mutex_destroy(&my.mc_mutex);
8992 free(my.mc_wbuf[0]);
8997 /** Copy environment as-is. */
8999 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
9001 MDB_txn *txn = NULL;
9002 mdb_mutexref_t wmutex = NULL;
9008 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9012 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9015 /* Do the lock/unlock of the reader mutex before starting the
9016 * write txn. Otherwise other read txns could block writers.
9018 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9023 /* We must start the actual read txn after blocking writers */
9024 mdb_txn_end(txn, MDB_END_RESET_TMP);
9026 /* Temporarily block writers until we snapshot the meta pages */
9027 wmutex = env->me_wmutex;
9028 if (LOCK_MUTEX(rc, env, wmutex))
9031 rc = mdb_txn_renew0(txn);
9033 UNLOCK_MUTEX(wmutex);
9038 wsize = env->me_psize * NUM_METAS;
9042 DO_WRITE(rc, fd, ptr, w2, len);
9046 } else if (len > 0) {
9052 /* Non-blocking or async handles are not supported */
9058 UNLOCK_MUTEX(wmutex);
9063 w2 = txn->mt_next_pgno * env->me_psize;
9066 if ((rc = mdb_fsize(env->me_fd, &fsize)))
9073 if (wsize > MAX_WRITE)
9077 DO_WRITE(rc, fd, ptr, w2, len);
9081 } else if (len > 0) {
9098 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
9100 if (flags & MDB_CP_COMPACT)
9101 return mdb_env_copyfd1(env, fd);
9103 return mdb_env_copyfd0(env, fd);
9107 mdb_env_copyfd(MDB_env *env, HANDLE fd)
9109 return mdb_env_copyfd2(env, fd, 0);
9113 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
9117 HANDLE newfd = INVALID_HANDLE_VALUE;
9119 if (env->me_flags & MDB_NOSUBDIR) {
9120 lpath = (char *)path;
9123 len += sizeof(DATANAME);
9124 lpath = malloc(len);
9127 sprintf(lpath, "%s" DATANAME, path);
9130 /* The destination path must exist, but the destination file must not.
9131 * We don't want the OS to cache the writes, since the source data is
9132 * already in the OS cache.
9135 newfd = CreateFileA(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
9136 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
9138 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
9140 if (newfd == INVALID_HANDLE_VALUE) {
9145 if (env->me_psize >= env->me_os_psize) {
9147 /* Set O_DIRECT if the file system supports it */
9148 if ((rc = fcntl(newfd, F_GETFL)) != -1)
9149 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
9151 #ifdef F_NOCACHE /* __APPLE__ */
9152 rc = fcntl(newfd, F_NOCACHE, 1);
9160 rc = mdb_env_copyfd2(env, newfd, flags);
9163 if (!(env->me_flags & MDB_NOSUBDIR))
9165 if (newfd != INVALID_HANDLE_VALUE)
9166 if (close(newfd) < 0 && rc == MDB_SUCCESS)
9173 mdb_env_copy(MDB_env *env, const char *path)
9175 return mdb_env_copy2(env, path, 0);
9179 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
9181 if (flag & ~CHANGEABLE)
9184 env->me_flags |= flag;
9186 env->me_flags &= ~flag;
9191 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
9196 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
9201 mdb_env_set_userctx(MDB_env *env, void *ctx)
9205 env->me_userctx = ctx;
9210 mdb_env_get_userctx(MDB_env *env)
9212 return env ? env->me_userctx : NULL;
9216 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
9221 env->me_assert_func = func;
9227 mdb_env_get_path(MDB_env *env, const char **arg)
9232 *arg = env->me_path;
9237 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
9246 /** Common code for #mdb_stat() and #mdb_env_stat().
9247 * @param[in] env the environment to operate in.
9248 * @param[in] db the #MDB_db record containing the stats to return.
9249 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
9250 * @return 0, this function always succeeds.
9253 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
9255 arg->ms_psize = env->me_psize;
9256 arg->ms_depth = db->md_depth;
9257 arg->ms_branch_pages = db->md_branch_pages;
9258 arg->ms_leaf_pages = db->md_leaf_pages;
9259 arg->ms_overflow_pages = db->md_overflow_pages;
9260 arg->ms_entries = db->md_entries;
9266 mdb_env_stat(MDB_env *env, MDB_stat *arg)
9270 if (env == NULL || arg == NULL)
9273 meta = mdb_env_pick_meta(env);
9275 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
9279 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
9283 if (env == NULL || arg == NULL)
9286 meta = mdb_env_pick_meta(env);
9287 arg->me_mapaddr = meta->mm_address;
9288 arg->me_last_pgno = meta->mm_last_pg;
9289 arg->me_last_txnid = meta->mm_txnid;
9291 arg->me_mapsize = env->me_mapsize;
9292 arg->me_maxreaders = env->me_maxreaders;
9293 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
9297 /** Set the default comparison functions for a database.
9298 * Called immediately after a database is opened to set the defaults.
9299 * The user can then override them with #mdb_set_compare() or
9300 * #mdb_set_dupsort().
9301 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
9302 * @param[in] dbi A database handle returned by #mdb_dbi_open()
9305 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
9307 uint16_t f = txn->mt_dbs[dbi].md_flags;
9309 txn->mt_dbxs[dbi].md_cmp =
9310 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
9311 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
9313 txn->mt_dbxs[dbi].md_dcmp =
9314 !(f & MDB_DUPSORT) ? 0 :
9315 ((f & MDB_INTEGERDUP)
9316 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
9317 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
9320 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
9326 int rc, dbflag, exact;
9327 unsigned int unused = 0, seq;
9330 if (flags & ~VALID_FLAGS)
9332 if (txn->mt_flags & MDB_TXN_BLOCKED)
9338 if (flags & PERSISTENT_FLAGS) {
9339 uint16_t f2 = flags & PERSISTENT_FLAGS;
9340 /* make sure flag changes get committed */
9341 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
9342 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
9343 txn->mt_flags |= MDB_TXN_DIRTY;
9346 mdb_default_cmp(txn, MAIN_DBI);
9350 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
9351 mdb_default_cmp(txn, MAIN_DBI);
9354 /* Is the DB already open? */
9356 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
9357 if (!txn->mt_dbxs[i].md_name.mv_size) {
9358 /* Remember this free slot */
9359 if (!unused) unused = i;
9362 if (len == txn->mt_dbxs[i].md_name.mv_size &&
9363 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
9369 /* If no free slot and max hit, fail */
9370 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
9371 return MDB_DBS_FULL;
9373 /* Cannot mix named databases with some mainDB flags */
9374 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
9375 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
9377 /* Find the DB info */
9378 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
9381 key.mv_data = (void *)name;
9382 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
9383 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
9384 if (rc == MDB_SUCCESS) {
9385 /* make sure this is actually a DB */
9386 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
9387 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
9388 return MDB_INCOMPATIBLE;
9389 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
9390 /* Create if requested */
9391 data.mv_size = sizeof(MDB_db);
9392 data.mv_data = &dummy;
9393 memset(&dummy, 0, sizeof(dummy));
9394 dummy.md_root = P_INVALID;
9395 dummy.md_flags = flags & PERSISTENT_FLAGS;
9396 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
9400 /* OK, got info, add to table */
9401 if (rc == MDB_SUCCESS) {
9402 unsigned int slot = unused ? unused : txn->mt_numdbs;
9403 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
9404 txn->mt_dbxs[slot].md_name.mv_size = len;
9405 txn->mt_dbxs[slot].md_rel = NULL;
9406 txn->mt_dbflags[slot] = dbflag;
9407 /* txn-> and env-> are the same in read txns, use
9408 * tmp variable to avoid undefined assignment
9410 seq = ++txn->mt_env->me_dbiseqs[slot];
9411 txn->mt_dbiseqs[slot] = seq;
9413 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
9415 mdb_default_cmp(txn, slot);
9425 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9427 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
9430 if (txn->mt_flags & MDB_TXN_BLOCKED)
9433 if (txn->mt_dbflags[dbi] & DB_STALE) {
9436 /* Stale, must read the DB's root. cursor_init does it for us. */
9437 mdb_cursor_init(&mc, txn, dbi, &mx);
9439 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9442 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9445 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
9447 ptr = env->me_dbxs[dbi].md_name.mv_data;
9448 /* If there was no name, this was already closed */
9450 env->me_dbxs[dbi].md_name.mv_data = NULL;
9451 env->me_dbxs[dbi].md_name.mv_size = 0;
9452 env->me_dbflags[dbi] = 0;
9453 env->me_dbiseqs[dbi]++;
9458 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9460 /* We could return the flags for the FREE_DBI too but what's the point? */
9461 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9463 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9467 /** Add all the DB's pages to the free list.
9468 * @param[in] mc Cursor on the DB to free.
9469 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9470 * @return 0 on success, non-zero on failure.
9473 mdb_drop0(MDB_cursor *mc, int subs)
9477 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9478 if (rc == MDB_SUCCESS) {
9479 MDB_txn *txn = mc->mc_txn;
9484 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
9485 * This also avoids any P_LEAF2 pages, which have no nodes.
9487 if (mc->mc_flags & C_SUB)
9490 mdb_cursor_copy(mc, &mx);
9491 while (mc->mc_snum > 0) {
9492 MDB_page *mp = mc->mc_pg[mc->mc_top];
9493 unsigned n = NUMKEYS(mp);
9495 for (i=0; i<n; i++) {
9496 ni = NODEPTR(mp, i);
9497 if (ni->mn_flags & F_BIGDATA) {
9500 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9501 rc = mdb_page_get(txn, pg, &omp, NULL);
9504 mdb_cassert(mc, IS_OVERFLOW(omp));
9505 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9509 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9510 mdb_xcursor_init1(mc, ni);
9511 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9517 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9519 for (i=0; i<n; i++) {
9521 ni = NODEPTR(mp, i);
9524 mdb_midl_xappend(txn->mt_free_pgs, pg);
9529 mc->mc_ki[mc->mc_top] = i;
9530 rc = mdb_cursor_sibling(mc, 1);
9532 if (rc != MDB_NOTFOUND)
9534 /* no more siblings, go back to beginning
9535 * of previous level.
9539 for (i=1; i<mc->mc_snum; i++) {
9541 mc->mc_pg[i] = mx.mc_pg[i];
9546 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9549 txn->mt_flags |= MDB_TXN_ERROR;
9550 } else if (rc == MDB_NOTFOUND) {
9556 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9558 MDB_cursor *mc, *m2;
9561 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9564 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9567 if (TXN_DBI_CHANGED(txn, dbi))
9570 rc = mdb_cursor_open(txn, dbi, &mc);
9574 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9575 /* Invalidate the dropped DB's cursors */
9576 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9577 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9581 /* Can't delete the main DB */
9582 if (del && dbi >= CORE_DBS) {
9583 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
9585 txn->mt_dbflags[dbi] = DB_STALE;
9586 mdb_dbi_close(txn->mt_env, dbi);
9588 txn->mt_flags |= MDB_TXN_ERROR;
9591 /* reset the DB record, mark it dirty */
9592 txn->mt_dbflags[dbi] |= DB_DIRTY;
9593 txn->mt_dbs[dbi].md_depth = 0;
9594 txn->mt_dbs[dbi].md_branch_pages = 0;
9595 txn->mt_dbs[dbi].md_leaf_pages = 0;
9596 txn->mt_dbs[dbi].md_overflow_pages = 0;
9597 txn->mt_dbs[dbi].md_entries = 0;
9598 txn->mt_dbs[dbi].md_root = P_INVALID;
9600 txn->mt_flags |= MDB_TXN_DIRTY;
9603 mdb_cursor_close(mc);
9607 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9609 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9612 txn->mt_dbxs[dbi].md_cmp = cmp;
9616 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9618 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9621 txn->mt_dbxs[dbi].md_dcmp = cmp;
9625 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9627 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9630 txn->mt_dbxs[dbi].md_rel = rel;
9634 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9636 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9639 txn->mt_dbxs[dbi].md_relctx = ctx;
9644 mdb_env_get_maxkeysize(MDB_env *env)
9646 return ENV_MAXKEY(env);
9650 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9652 unsigned int i, rdrs;
9655 int rc = 0, first = 1;
9659 if (!env->me_txns) {
9660 return func("(no reader locks)\n", ctx);
9662 rdrs = env->me_txns->mti_numreaders;
9663 mr = env->me_txns->mti_readers;
9664 for (i=0; i<rdrs; i++) {
9666 txnid_t txnid = mr[i].mr_txnid;
9667 sprintf(buf, txnid == (txnid_t)-1 ?
9668 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9669 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9672 rc = func(" pid thread txnid\n", ctx);
9676 rc = func(buf, ctx);
9682 rc = func("(no active readers)\n", ctx);
9687 /** Insert pid into list if not already present.
9688 * return -1 if already present.
9691 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9693 /* binary search of pid in list */
9695 unsigned cursor = 1;
9697 unsigned n = ids[0];
9700 unsigned pivot = n >> 1;
9701 cursor = base + pivot + 1;
9702 val = pid - ids[cursor];
9707 } else if ( val > 0 ) {
9712 /* found, so it's a duplicate */
9721 for (n = ids[0]; n > cursor; n--)
9728 mdb_reader_check(MDB_env *env, int *dead)
9734 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
9737 /** As #mdb_reader_check(). rlocked = <caller locked the reader mutex>. */
9739 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
9741 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
9742 unsigned int i, j, rdrs;
9744 MDB_PID_T *pids, pid;
9745 int rc = MDB_SUCCESS, count = 0;
9747 rdrs = env->me_txns->mti_numreaders;
9748 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
9752 mr = env->me_txns->mti_readers;
9753 for (i=0; i<rdrs; i++) {
9755 if (pid && pid != env->me_pid) {
9756 if (mdb_pid_insert(pids, pid) == 0) {
9757 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9758 /* Stale reader found */
9761 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
9762 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
9764 rdrs = 0; /* the above checked all readers */
9766 /* Recheck, a new process may have reused pid */
9767 if (mdb_reader_pid(env, Pidcheck, pid))
9772 if (mr[j].mr_pid == pid) {
9773 DPRINTF(("clear stale reader pid %u txn %"Z"d",
9774 (unsigned) pid, mr[j].mr_txnid));
9779 UNLOCK_MUTEX(rmutex);
9790 #ifdef MDB_ROBUST_SUPPORTED
9791 /** Handle #LOCK_MUTEX0() failure.
9792 * Try to repair the lock file if the mutex owner died.
9793 * @param[in] env the environment handle
9794 * @param[in] mutex LOCK_MUTEX0() mutex
9795 * @param[in] rc LOCK_MUTEX0() error (nonzero)
9796 * @return 0 on success with the mutex locked, or an error code on failure.
9799 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
9804 if (rc == MDB_OWNERDEAD) {
9805 /* We own the mutex. Clean up after dead previous owner. */
9807 rlocked = (mutex == env->me_rmutex);
9809 /* Keep mti_txnid updated, otherwise next writer can
9810 * overwrite data which latest meta page refers to.
9812 meta = mdb_env_pick_meta(env);
9813 env->me_txns->mti_txnid = meta->mm_txnid;
9814 /* env is hosed if the dead thread was ours */
9816 env->me_flags |= MDB_FATAL_ERROR;
9821 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
9822 (rc ? "this process' env is hosed" : "recovering")));
9823 rc2 = mdb_reader_check0(env, rlocked, NULL);
9825 rc2 = mdb_mutex_consistent(mutex);
9826 if (rc || (rc = rc2)) {
9827 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
9828 UNLOCK_MUTEX(mutex);
9834 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
9839 #endif /* MDB_ROBUST_SUPPORTED */