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