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 written in this txn */
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 */
1086 #define DB_DUPDATA 0x20 /**< DB is #MDB_DUPSORT data */
1088 /** In write txns, array of cursors for each DB */
1089 MDB_cursor **mt_cursors;
1090 /** Array of flags for each DB */
1091 unsigned char *mt_dbflags;
1092 /** Number of DB records in use, or 0 when the txn is finished.
1093 * This number only ever increments until the txn finishes; we
1094 * don't decrement it when individual DB handles are closed.
1098 /** @defgroup mdb_txn Transaction Flags
1102 /** #mdb_txn_begin() flags */
1103 #define MDB_TXN_BEGIN_FLAGS MDB_RDONLY
1104 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1105 /* internal txn flags */
1106 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1107 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1108 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1109 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1110 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1111 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1112 /** most operations on the txn are currently illegal */
1113 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1115 unsigned int mt_flags; /**< @ref mdb_txn */
1116 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1117 * Includes ancestor txns' dirty pages not hidden by other txns'
1118 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1119 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1121 unsigned int mt_dirty_room;
1124 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1125 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1126 * raise this on a 64 bit machine.
1128 #define CURSOR_STACK 32
1132 /** Cursors are used for all DB operations.
1133 * A cursor holds a path of (page pointer, key index) from the DB
1134 * root to a position in the DB, plus other state. #MDB_DUPSORT
1135 * cursors include an xcursor to the current data item. Write txns
1136 * track their cursors and keep them up to date when data moves.
1137 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1138 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1141 /** Next cursor on this DB in this txn */
1142 MDB_cursor *mc_next;
1143 /** Backup of the original cursor if this cursor is a shadow */
1144 MDB_cursor *mc_backup;
1145 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1146 struct MDB_xcursor *mc_xcursor;
1147 /** The transaction that owns this cursor */
1149 /** The database handle this cursor operates on */
1151 /** The database record for this cursor */
1153 /** The database auxiliary record for this cursor */
1155 /** The @ref mt_dbflag for this database */
1156 unsigned char *mc_dbflag;
1157 unsigned short mc_snum; /**< number of pushed pages */
1158 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1159 /** @defgroup mdb_cursor Cursor Flags
1161 * Cursor state flags.
1164 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1165 #define C_EOF 0x02 /**< No more data */
1166 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1167 #define C_DEL 0x08 /**< last op was a cursor_del */
1168 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1170 unsigned int mc_flags; /**< @ref mdb_cursor */
1171 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1172 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1175 /** Context for sorted-dup records.
1176 * We could have gone to a fully recursive design, with arbitrarily
1177 * deep nesting of sub-databases. But for now we only handle these
1178 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1180 typedef struct MDB_xcursor {
1181 /** A sub-cursor for traversing the Dup DB */
1182 MDB_cursor mx_cursor;
1183 /** The database record for this Dup DB */
1185 /** The auxiliary DB record for this Dup DB */
1187 /** The @ref mt_dbflag for this Dup DB */
1188 unsigned char mx_dbflag;
1191 /** Check if there is an inited xcursor, so #XCURSOR_REFRESH() is proper */
1192 #define XCURSOR_INITED(mc) \
1193 ((mc)->mc_xcursor && ((mc)->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
1195 /** Update sub-page pointer, if any, in \b mc->mc_xcursor. Needed
1196 * when the node which contains the sub-page may have moved. Called
1197 * with \b mp = mc->mc_pg[mc->mc_top], \b ki = mc->mc_ki[mc->mc_top].
1199 #define XCURSOR_REFRESH(mc, mp, ki) do { \
1200 MDB_page *xr_pg = (mp); \
1201 MDB_node *xr_node = NODEPTR(xr_pg, ki); \
1202 if ((xr_node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) \
1203 (mc)->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(xr_node); \
1206 /** State of FreeDB old pages, stored in the MDB_env */
1207 typedef struct MDB_pgstate {
1208 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1209 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1212 /** The database environment. */
1214 HANDLE me_fd; /**< The main data file */
1215 HANDLE me_lfd; /**< The lock file */
1216 HANDLE me_mfd; /**< just for writing the meta pages */
1217 /** Failed to update the meta page. Probably an I/O error. */
1218 #define MDB_FATAL_ERROR 0x80000000U
1219 /** Some fields are initialized. */
1220 #define MDB_ENV_ACTIVE 0x20000000U
1221 /** me_txkey is set */
1222 #define MDB_ENV_TXKEY 0x10000000U
1223 /** fdatasync is unreliable */
1224 #define MDB_FSYNCONLY 0x08000000U
1225 uint32_t me_flags; /**< @ref mdb_env */
1226 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1227 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1228 unsigned int me_maxreaders; /**< size of the reader table */
1229 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1230 volatile int me_close_readers;
1231 MDB_dbi me_numdbs; /**< number of DBs opened */
1232 MDB_dbi me_maxdbs; /**< size of the DB table */
1233 MDB_PID_T me_pid; /**< process ID of this env */
1234 char *me_path; /**< path to the DB files */
1235 char *me_map; /**< the memory map of the data file */
1236 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1237 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1238 void *me_pbuf; /**< scratch area for DUPSORT put() */
1239 MDB_txn *me_txn; /**< current write transaction */
1240 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1241 size_t me_mapsize; /**< size of the data memory map */
1242 off_t me_size; /**< current file size */
1243 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1244 MDB_dbx *me_dbxs; /**< array of static DB info */
1245 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1246 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1247 pthread_key_t me_txkey; /**< thread-key for readers */
1248 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1249 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1250 # define me_pglast me_pgstate.mf_pglast
1251 # define me_pghead me_pgstate.mf_pghead
1252 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1253 /** IDL of pages that became unused in a write txn */
1254 MDB_IDL me_free_pgs;
1255 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1256 MDB_ID2L me_dirty_list;
1257 /** Max number of freelist items that can fit in a single overflow page */
1259 /** Max size of a node on a page */
1260 unsigned int me_nodemax;
1261 #if !(MDB_MAXKEYSIZE)
1262 unsigned int me_maxkey; /**< max size of a key */
1264 int me_live_reader; /**< have liveness lock in reader table */
1266 int me_pidquery; /**< Used in OpenProcess */
1268 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1269 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1270 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1272 mdb_mutex_t me_rmutex;
1273 mdb_mutex_t me_wmutex;
1275 void *me_userctx; /**< User-settable context */
1276 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1279 /** Nested transaction */
1280 typedef struct MDB_ntxn {
1281 MDB_txn mnt_txn; /**< the transaction */
1282 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1285 /** max number of pages to commit in one writev() call */
1286 #define MDB_COMMIT_PAGES 64
1287 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1288 #undef MDB_COMMIT_PAGES
1289 #define MDB_COMMIT_PAGES IOV_MAX
1292 /** max bytes to write in one call */
1293 #define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
1295 /** Check \b txn and \b dbi arguments to a function */
1296 #define TXN_DBI_EXIST(txn, dbi, validity) \
1297 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1299 /** Check for misused \b dbi handles */
1300 #define TXN_DBI_CHANGED(txn, dbi) \
1301 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1303 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1304 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1305 static int mdb_page_touch(MDB_cursor *mc);
1307 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1308 "reset-tmp", "fail-begin", "fail-beginchild"}
1310 /* mdb_txn_end operation number, for logging */
1311 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1312 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1314 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1315 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1316 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1317 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1318 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1320 static int mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
1321 static int mdb_page_search_root(MDB_cursor *mc,
1322 MDB_val *key, int modify);
1323 #define MDB_PS_MODIFY 1
1324 #define MDB_PS_ROOTONLY 2
1325 #define MDB_PS_FIRST 4
1326 #define MDB_PS_LAST 8
1327 static int mdb_page_search(MDB_cursor *mc,
1328 MDB_val *key, int flags);
1329 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1331 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1332 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1333 pgno_t newpgno, unsigned int nflags);
1335 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1336 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1337 static int mdb_env_write_meta(MDB_txn *txn);
1338 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1339 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1341 static void mdb_env_close0(MDB_env *env, int excl);
1343 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1344 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1345 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1346 static void mdb_node_del(MDB_cursor *mc, int ksize);
1347 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1348 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1349 static int mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
1350 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1351 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1353 static int mdb_rebalance(MDB_cursor *mc);
1354 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1356 static void mdb_cursor_pop(MDB_cursor *mc);
1357 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1359 static int mdb_cursor_del0(MDB_cursor *mc);
1360 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1361 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1362 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1363 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1364 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1366 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1367 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1369 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1370 static void mdb_xcursor_init0(MDB_cursor *mc);
1371 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1372 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1374 static int mdb_drop0(MDB_cursor *mc, int subs);
1375 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1376 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1379 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1382 /** Compare two items pointing at size_t's of unknown alignment. */
1383 #ifdef MISALIGNED_OK
1384 # define mdb_cmp_clong mdb_cmp_long
1386 # define mdb_cmp_clong mdb_cmp_cint
1390 static SECURITY_DESCRIPTOR mdb_null_sd;
1391 static SECURITY_ATTRIBUTES mdb_all_sa;
1392 static int mdb_sec_inited;
1394 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize);
1397 /** Return the library version info. */
1399 mdb_version(int *major, int *minor, int *patch)
1401 if (major) *major = MDB_VERSION_MAJOR;
1402 if (minor) *minor = MDB_VERSION_MINOR;
1403 if (patch) *patch = MDB_VERSION_PATCH;
1404 return MDB_VERSION_STRING;
1407 /** Table of descriptions for LMDB @ref errors */
1408 static char *const mdb_errstr[] = {
1409 "MDB_KEYEXIST: Key/data pair already exists",
1410 "MDB_NOTFOUND: No matching key/data pair found",
1411 "MDB_PAGE_NOTFOUND: Requested page not found",
1412 "MDB_CORRUPTED: Located page was wrong type",
1413 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1414 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1415 "MDB_INVALID: File is not an LMDB file",
1416 "MDB_MAP_FULL: Environment mapsize limit reached",
1417 "MDB_DBS_FULL: Environment maxdbs limit reached",
1418 "MDB_READERS_FULL: Environment maxreaders limit reached",
1419 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1420 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1421 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1422 "MDB_PAGE_FULL: Internal error - page has no more space",
1423 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1424 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1425 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1426 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1427 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1428 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1432 mdb_strerror(int err)
1435 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1436 * This works as long as no function between the call to mdb_strerror
1437 * and the actual use of the message uses more than 4K of stack.
1439 #define MSGSIZE 1024
1440 #define PADSIZE 4096
1441 char buf[MSGSIZE+PADSIZE], *ptr = buf;
1445 return ("Successful return: 0");
1447 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1448 i = err - MDB_KEYEXIST;
1449 return mdb_errstr[i];
1453 /* These are the C-runtime error codes we use. The comment indicates
1454 * their numeric value, and the Win32 error they would correspond to
1455 * if the error actually came from a Win32 API. A major mess, we should
1456 * have used LMDB-specific error codes for everything.
1459 case ENOENT: /* 2, FILE_NOT_FOUND */
1460 case EIO: /* 5, ACCESS_DENIED */
1461 case ENOMEM: /* 12, INVALID_ACCESS */
1462 case EACCES: /* 13, INVALID_DATA */
1463 case EBUSY: /* 16, CURRENT_DIRECTORY */
1464 case EINVAL: /* 22, BAD_COMMAND */
1465 case ENOSPC: /* 28, OUT_OF_PAPER */
1466 return strerror(err);
1471 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1472 FORMAT_MESSAGE_IGNORE_INSERTS,
1473 NULL, err, 0, ptr, MSGSIZE, (va_list *)buf+MSGSIZE);
1476 return strerror(err);
1480 /** assert(3) variant in cursor context */
1481 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1482 /** assert(3) variant in transaction context */
1483 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1484 /** assert(3) variant in environment context */
1485 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1488 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1489 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1492 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1493 const char *func, const char *file, int line)
1496 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1497 file, line, expr_txt, func);
1498 if (env->me_assert_func)
1499 env->me_assert_func(env, buf);
1500 fprintf(stderr, "%s\n", buf);
1504 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1508 /** Return the page number of \b mp which may be sub-page, for debug output */
1510 mdb_dbg_pgno(MDB_page *mp)
1513 COPY_PGNO(ret, mp->mp_pgno);
1517 /** Display a key in hexadecimal and return the address of the result.
1518 * @param[in] key the key to display
1519 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1520 * @return The key in hexadecimal form.
1523 mdb_dkey(MDB_val *key, char *buf)
1526 unsigned char *c = key->mv_data;
1532 if (key->mv_size > DKBUF_MAXKEYSIZE)
1533 return "MDB_MAXKEYSIZE";
1534 /* may want to make this a dynamic check: if the key is mostly
1535 * printable characters, print it as-is instead of converting to hex.
1539 for (i=0; i<key->mv_size; i++)
1540 ptr += sprintf(ptr, "%02x", *c++);
1542 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1548 mdb_leafnode_type(MDB_node *n)
1550 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1551 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1552 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1555 /** Display all the keys in the page. */
1557 mdb_page_list(MDB_page *mp)
1559 pgno_t pgno = mdb_dbg_pgno(mp);
1560 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1562 unsigned int i, nkeys, nsize, total = 0;
1566 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1567 case P_BRANCH: type = "Branch page"; break;
1568 case P_LEAF: type = "Leaf page"; break;
1569 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1570 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1571 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1573 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1574 pgno, mp->mp_pages, state);
1577 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1578 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1581 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1585 nkeys = NUMKEYS(mp);
1586 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1588 for (i=0; i<nkeys; i++) {
1589 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1590 key.mv_size = nsize = mp->mp_pad;
1591 key.mv_data = LEAF2KEY(mp, i, nsize);
1593 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1596 node = NODEPTR(mp, i);
1597 key.mv_size = node->mn_ksize;
1598 key.mv_data = node->mn_data;
1599 nsize = NODESIZE + key.mv_size;
1600 if (IS_BRANCH(mp)) {
1601 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1605 if (F_ISSET(node->mn_flags, F_BIGDATA))
1606 nsize += sizeof(pgno_t);
1608 nsize += NODEDSZ(node);
1610 nsize += sizeof(indx_t);
1611 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1612 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1614 total = EVEN(total);
1616 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1617 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1621 mdb_cursor_chk(MDB_cursor *mc)
1627 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1628 for (i=0; i<mc->mc_top; i++) {
1630 node = NODEPTR(mp, mc->mc_ki[i]);
1631 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1634 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1636 if (XCURSOR_INITED(mc)) {
1637 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1638 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1639 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1647 /** Count all the pages in each DB and in the freelist
1648 * and make sure it matches the actual number of pages
1650 * All named DBs must be open for a correct count.
1652 static void mdb_audit(MDB_txn *txn)
1656 MDB_ID freecount, count;
1661 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1662 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1663 freecount += *(MDB_ID *)data.mv_data;
1664 mdb_tassert(txn, rc == MDB_NOTFOUND);
1667 for (i = 0; i<txn->mt_numdbs; i++) {
1669 if (!(txn->mt_dbflags[i] & DB_VALID))
1671 mdb_cursor_init(&mc, txn, i, &mx);
1672 if (txn->mt_dbs[i].md_root == P_INVALID)
1674 count += txn->mt_dbs[i].md_branch_pages +
1675 txn->mt_dbs[i].md_leaf_pages +
1676 txn->mt_dbs[i].md_overflow_pages;
1677 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1678 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1679 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1682 mp = mc.mc_pg[mc.mc_top];
1683 for (j=0; j<NUMKEYS(mp); j++) {
1684 MDB_node *leaf = NODEPTR(mp, j);
1685 if (leaf->mn_flags & F_SUBDATA) {
1687 memcpy(&db, NODEDATA(leaf), sizeof(db));
1688 count += db.md_branch_pages + db.md_leaf_pages +
1689 db.md_overflow_pages;
1693 mdb_tassert(txn, rc == MDB_NOTFOUND);
1696 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1697 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1698 txn->mt_txnid, freecount, count+NUM_METAS,
1699 freecount+count+NUM_METAS, txn->mt_next_pgno);
1705 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1707 return txn->mt_dbxs[dbi].md_cmp(a, b);
1711 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1713 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1714 #if UINT_MAX < SIZE_MAX
1715 if (dcmp == mdb_cmp_int && a->mv_size == sizeof(size_t))
1716 dcmp = mdb_cmp_clong;
1721 /** Allocate memory for a page.
1722 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1725 mdb_page_malloc(MDB_txn *txn, unsigned num)
1727 MDB_env *env = txn->mt_env;
1728 MDB_page *ret = env->me_dpages;
1729 size_t psize = env->me_psize, sz = psize, off;
1730 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1731 * For a single page alloc, we init everything after the page header.
1732 * For multi-page, we init the final page; if the caller needed that
1733 * many pages they will be filling in at least up to the last page.
1737 VGMEMP_ALLOC(env, ret, sz);
1738 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1739 env->me_dpages = ret->mp_next;
1742 psize -= off = PAGEHDRSZ;
1747 if ((ret = malloc(sz)) != NULL) {
1748 VGMEMP_ALLOC(env, ret, sz);
1749 if (!(env->me_flags & MDB_NOMEMINIT)) {
1750 memset((char *)ret + off, 0, psize);
1754 txn->mt_flags |= MDB_TXN_ERROR;
1758 /** Free a single page.
1759 * Saves single pages to a list, for future reuse.
1760 * (This is not used for multi-page overflow pages.)
1763 mdb_page_free(MDB_env *env, MDB_page *mp)
1765 mp->mp_next = env->me_dpages;
1766 VGMEMP_FREE(env, mp);
1767 env->me_dpages = mp;
1770 /** Free a dirty page */
1772 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1774 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1775 mdb_page_free(env, dp);
1777 /* large pages just get freed directly */
1778 VGMEMP_FREE(env, dp);
1783 /** Return all dirty pages to dpage list */
1785 mdb_dlist_free(MDB_txn *txn)
1787 MDB_env *env = txn->mt_env;
1788 MDB_ID2L dl = txn->mt_u.dirty_list;
1789 unsigned i, n = dl[0].mid;
1791 for (i = 1; i <= n; i++) {
1792 mdb_dpage_free(env, dl[i].mptr);
1797 /** Loosen or free a single page.
1798 * Saves single pages to a list for future reuse
1799 * in this same txn. It has been pulled from the freeDB
1800 * and already resides on the dirty list, but has been
1801 * deleted. Use these pages first before pulling again
1804 * If the page wasn't dirtied in this txn, just add it
1805 * to this txn's free list.
1808 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1811 pgno_t pgno = mp->mp_pgno;
1812 MDB_txn *txn = mc->mc_txn;
1814 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1815 if (txn->mt_parent) {
1816 MDB_ID2 *dl = txn->mt_u.dirty_list;
1817 /* If txn has a parent, make sure the page is in our
1821 unsigned x = mdb_mid2l_search(dl, pgno);
1822 if (x <= dl[0].mid && dl[x].mid == pgno) {
1823 if (mp != dl[x].mptr) { /* bad cursor? */
1824 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1825 txn->mt_flags |= MDB_TXN_ERROR;
1826 return MDB_CORRUPTED;
1833 /* no parent txn, so it's just ours */
1838 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1840 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1841 txn->mt_loose_pgs = mp;
1842 txn->mt_loose_count++;
1843 mp->mp_flags |= P_LOOSE;
1845 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1853 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1854 * @param[in] mc A cursor handle for the current operation.
1855 * @param[in] pflags Flags of the pages to update:
1856 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1857 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1858 * @return 0 on success, non-zero on failure.
1861 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1863 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1864 MDB_txn *txn = mc->mc_txn;
1865 MDB_cursor *m3, *m0 = mc;
1870 int rc = MDB_SUCCESS, level;
1872 /* Mark pages seen by cursors */
1873 if (mc->mc_flags & C_UNTRACK)
1874 mc = NULL; /* will find mc in mt_cursors */
1875 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1876 for (; mc; mc=mc->mc_next) {
1877 if (!(mc->mc_flags & C_INITIALIZED))
1879 for (m3 = mc;; m3 = &mx->mx_cursor) {
1881 for (j=0; j<m3->mc_snum; j++) {
1883 if ((mp->mp_flags & Mask) == pflags)
1884 mp->mp_flags ^= P_KEEP;
1886 mx = m3->mc_xcursor;
1887 /* Proceed to mx if it is at a sub-database */
1888 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1890 if (! (mp && (mp->mp_flags & P_LEAF)))
1892 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1893 if (!(leaf->mn_flags & F_SUBDATA))
1902 /* Mark dirty root pages */
1903 for (i=0; i<txn->mt_numdbs; i++) {
1904 if (txn->mt_dbflags[i] & DB_DIRTY) {
1905 pgno_t pgno = txn->mt_dbs[i].md_root;
1906 if (pgno == P_INVALID)
1908 if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
1910 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1911 dp->mp_flags ^= P_KEEP;
1919 static int mdb_page_flush(MDB_txn *txn, int keep);
1921 /** Spill pages from the dirty list back to disk.
1922 * This is intended to prevent running into #MDB_TXN_FULL situations,
1923 * but note that they may still occur in a few cases:
1924 * 1) our estimate of the txn size could be too small. Currently this
1925 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1926 * 2) child txns may run out of space if their parents dirtied a
1927 * lot of pages and never spilled them. TODO: we probably should do
1928 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1929 * the parent's dirty_room is below a given threshold.
1931 * Otherwise, if not using nested txns, it is expected that apps will
1932 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1933 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1934 * If the txn never references them again, they can be left alone.
1935 * If the txn only reads them, they can be used without any fuss.
1936 * If the txn writes them again, they can be dirtied immediately without
1937 * going thru all of the work of #mdb_page_touch(). Such references are
1938 * handled by #mdb_page_unspill().
1940 * Also note, we never spill DB root pages, nor pages of active cursors,
1941 * because we'll need these back again soon anyway. And in nested txns,
1942 * we can't spill a page in a child txn if it was already spilled in a
1943 * parent txn. That would alter the parent txns' data even though
1944 * the child hasn't committed yet, and we'd have no way to undo it if
1945 * the child aborted.
1947 * @param[in] m0 cursor A cursor handle identifying the transaction and
1948 * database for which we are checking space.
1949 * @param[in] key For a put operation, the key being stored.
1950 * @param[in] data For a put operation, the data being stored.
1951 * @return 0 on success, non-zero on failure.
1954 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1956 MDB_txn *txn = m0->mc_txn;
1958 MDB_ID2L dl = txn->mt_u.dirty_list;
1959 unsigned int i, j, need;
1962 if (m0->mc_flags & C_SUB)
1965 /* Estimate how much space this op will take */
1966 i = m0->mc_db->md_depth;
1967 /* Named DBs also dirty the main DB */
1968 if (m0->mc_dbi >= CORE_DBS)
1969 i += txn->mt_dbs[MAIN_DBI].md_depth;
1970 /* For puts, roughly factor in the key+data size */
1972 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1973 i += i; /* double it for good measure */
1976 if (txn->mt_dirty_room > i)
1979 if (!txn->mt_spill_pgs) {
1980 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1981 if (!txn->mt_spill_pgs)
1984 /* purge deleted slots */
1985 MDB_IDL sl = txn->mt_spill_pgs;
1986 unsigned int num = sl[0];
1988 for (i=1; i<=num; i++) {
1995 /* Preserve pages which may soon be dirtied again */
1996 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1999 /* Less aggressive spill - we originally spilled the entire dirty list,
2000 * with a few exceptions for cursor pages and DB root pages. But this
2001 * turns out to be a lot of wasted effort because in a large txn many
2002 * of those pages will need to be used again. So now we spill only 1/8th
2003 * of the dirty pages. Testing revealed this to be a good tradeoff,
2004 * better than 1/2, 1/4, or 1/10.
2006 if (need < MDB_IDL_UM_MAX / 8)
2007 need = MDB_IDL_UM_MAX / 8;
2009 /* Save the page IDs of all the pages we're flushing */
2010 /* flush from the tail forward, this saves a lot of shifting later on. */
2011 for (i=dl[0].mid; i && need; i--) {
2012 MDB_ID pn = dl[i].mid << 1;
2014 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2016 /* Can't spill twice, make sure it's not already in a parent's
2019 if (txn->mt_parent) {
2021 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2022 if (tx2->mt_spill_pgs) {
2023 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2024 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2025 dp->mp_flags |= P_KEEP;
2033 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2037 mdb_midl_sort(txn->mt_spill_pgs);
2039 /* Flush the spilled part of dirty list */
2040 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2043 /* Reset any dirty pages we kept that page_flush didn't see */
2044 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2047 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2051 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2053 mdb_find_oldest(MDB_txn *txn)
2056 txnid_t mr, oldest = txn->mt_txnid - 1;
2057 if (txn->mt_env->me_txns) {
2058 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2059 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2070 /** Add a page to the txn's dirty list */
2072 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2075 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2077 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2078 insert = mdb_mid2l_append;
2080 insert = mdb_mid2l_insert;
2082 mid.mid = mp->mp_pgno;
2084 rc = insert(txn->mt_u.dirty_list, &mid);
2085 mdb_tassert(txn, rc == 0);
2086 txn->mt_dirty_room--;
2089 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2090 * me_pghead and mt_next_pgno.
2092 * If there are free pages available from older transactions, they
2093 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2094 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2095 * and move me_pglast to say which records were consumed. Only this
2096 * function can create me_pghead and move me_pglast/mt_next_pgno.
2097 * @param[in] mc cursor A cursor handle identifying the transaction and
2098 * database for which we are allocating.
2099 * @param[in] num the number of pages to allocate.
2100 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2101 * will always be satisfied by a single contiguous chunk of memory.
2102 * @return 0 on success, non-zero on failure.
2105 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2107 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2108 /* Get at most <Max_retries> more freeDB records once me_pghead
2109 * has enough pages. If not enough, use new pages from the map.
2110 * If <Paranoid> and mc is updating the freeDB, only get new
2111 * records if me_pghead is empty. Then the freelist cannot play
2112 * catch-up with itself by growing while trying to save it.
2114 enum { Paranoid = 1, Max_retries = 500 };
2116 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2118 int rc, retry = num * 60;
2119 MDB_txn *txn = mc->mc_txn;
2120 MDB_env *env = txn->mt_env;
2121 pgno_t pgno, *mop = env->me_pghead;
2122 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2124 txnid_t oldest = 0, last;
2129 /* If there are any loose pages, just use them */
2130 if (num == 1 && txn->mt_loose_pgs) {
2131 np = txn->mt_loose_pgs;
2132 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2133 txn->mt_loose_count--;
2134 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
2142 /* If our dirty list is already full, we can't do anything */
2143 if (txn->mt_dirty_room == 0) {
2148 for (op = MDB_FIRST;; op = MDB_NEXT) {
2153 /* Seek a big enough contiguous page range. Prefer
2154 * pages at the tail, just truncating the list.
2160 if (mop[i-n2] == pgno+n2)
2167 if (op == MDB_FIRST) { /* 1st iteration */
2168 /* Prepare to fetch more and coalesce */
2169 last = env->me_pglast;
2170 oldest = env->me_pgoldest;
2171 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2174 key.mv_data = &last; /* will look up last+1 */
2175 key.mv_size = sizeof(last);
2177 if (Paranoid && mc->mc_dbi == FREE_DBI)
2180 if (Paranoid && retry < 0 && mop_len)
2184 /* Do not fetch more if the record will be too recent */
2185 if (oldest <= last) {
2187 oldest = mdb_find_oldest(txn);
2188 env->me_pgoldest = oldest;
2194 rc = mdb_cursor_get(&m2, &key, NULL, op);
2196 if (rc == MDB_NOTFOUND)
2200 last = *(txnid_t*)key.mv_data;
2201 if (oldest <= last) {
2203 oldest = mdb_find_oldest(txn);
2204 env->me_pgoldest = oldest;
2210 np = m2.mc_pg[m2.mc_top];
2211 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2212 if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
2215 idl = (MDB_ID *) data.mv_data;
2218 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2223 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2225 mop = env->me_pghead;
2227 env->me_pglast = last;
2229 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2230 last, txn->mt_dbs[FREE_DBI].md_root, i));
2232 DPRINTF(("IDL %"Z"u", idl[j]));
2234 /* Merge in descending sorted order */
2235 mdb_midl_xmerge(mop, idl);
2239 /* Use new pages from the map when nothing suitable in the freeDB */
2241 pgno = txn->mt_next_pgno;
2242 if (pgno + num >= env->me_maxpg) {
2243 DPUTS("DB size maxed out");
2249 if (env->me_flags & MDB_WRITEMAP) {
2250 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2252 if (!(np = mdb_page_malloc(txn, num))) {
2258 mop[0] = mop_len -= num;
2259 /* Move any stragglers down */
2260 for (j = i-num; j < mop_len; )
2261 mop[++j] = mop[++i];
2263 txn->mt_next_pgno = pgno + num;
2266 mdb_page_dirty(txn, np);
2272 txn->mt_flags |= MDB_TXN_ERROR;
2276 /** Copy the used portions of a non-overflow page.
2277 * @param[in] dst page to copy into
2278 * @param[in] src page to copy from
2279 * @param[in] psize size of a page
2282 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2284 enum { Align = sizeof(pgno_t) };
2285 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2287 /* If page isn't full, just copy the used portion. Adjust
2288 * alignment so memcpy may copy words instead of bytes.
2290 if ((unused &= -Align) && !IS_LEAF2(src)) {
2291 upper = (upper + PAGEBASE) & -Align;
2292 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2293 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2296 memcpy(dst, src, psize - unused);
2300 /** Pull a page off the txn's spill list, if present.
2301 * If a page being referenced was spilled to disk in this txn, bring
2302 * it back and make it dirty/writable again.
2303 * @param[in] txn the transaction handle.
2304 * @param[in] mp the page being referenced. It must not be dirty.
2305 * @param[out] ret the writable page, if any. ret is unchanged if
2306 * mp wasn't spilled.
2309 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2311 MDB_env *env = txn->mt_env;
2314 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2316 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2317 if (!tx2->mt_spill_pgs)
2319 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2320 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2323 if (txn->mt_dirty_room == 0)
2324 return MDB_TXN_FULL;
2325 if (IS_OVERFLOW(mp))
2329 if (env->me_flags & MDB_WRITEMAP) {
2332 np = mdb_page_malloc(txn, num);
2336 memcpy(np, mp, num * env->me_psize);
2338 mdb_page_copy(np, mp, env->me_psize);
2341 /* If in current txn, this page is no longer spilled.
2342 * If it happens to be the last page, truncate the spill list.
2343 * Otherwise mark it as deleted by setting the LSB.
2345 if (x == txn->mt_spill_pgs[0])
2346 txn->mt_spill_pgs[0]--;
2348 txn->mt_spill_pgs[x] |= 1;
2349 } /* otherwise, if belonging to a parent txn, the
2350 * page remains spilled until child commits
2353 mdb_page_dirty(txn, np);
2354 np->mp_flags |= P_DIRTY;
2362 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2363 * @param[in] mc cursor pointing to the page to be touched
2364 * @return 0 on success, non-zero on failure.
2367 mdb_page_touch(MDB_cursor *mc)
2369 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2370 MDB_txn *txn = mc->mc_txn;
2371 MDB_cursor *m2, *m3;
2375 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2376 if (txn->mt_flags & MDB_TXN_SPILLS) {
2378 rc = mdb_page_unspill(txn, mp, &np);
2384 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2385 (rc = mdb_page_alloc(mc, 1, &np)))
2388 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2389 mp->mp_pgno, pgno));
2390 mdb_cassert(mc, mp->mp_pgno != pgno);
2391 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2392 /* Update the parent page, if any, to point to the new page */
2394 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2395 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2396 SETPGNO(node, pgno);
2398 mc->mc_db->md_root = pgno;
2400 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2401 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2403 /* If txn has a parent, make sure the page is in our
2407 unsigned x = mdb_mid2l_search(dl, pgno);
2408 if (x <= dl[0].mid && dl[x].mid == pgno) {
2409 if (mp != dl[x].mptr) { /* bad cursor? */
2410 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2411 txn->mt_flags |= MDB_TXN_ERROR;
2412 return MDB_CORRUPTED;
2417 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2419 np = mdb_page_malloc(txn, 1);
2424 rc = mdb_mid2l_insert(dl, &mid);
2425 mdb_cassert(mc, rc == 0);
2430 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2432 np->mp_flags |= P_DIRTY;
2435 /* Adjust cursors pointing to mp */
2436 mc->mc_pg[mc->mc_top] = np;
2437 m2 = txn->mt_cursors[mc->mc_dbi];
2438 if (mc->mc_flags & C_SUB) {
2439 for (; m2; m2=m2->mc_next) {
2440 m3 = &m2->mc_xcursor->mx_cursor;
2441 if (m3->mc_snum < mc->mc_snum) continue;
2442 if (m3->mc_pg[mc->mc_top] == mp)
2443 m3->mc_pg[mc->mc_top] = np;
2446 for (; m2; m2=m2->mc_next) {
2447 if (m2->mc_snum < mc->mc_snum) continue;
2448 if (m2 == mc) continue;
2449 if (m2->mc_pg[mc->mc_top] == mp) {
2450 m2->mc_pg[mc->mc_top] = np;
2451 if (XCURSOR_INITED(m2) && IS_LEAF(np))
2452 XCURSOR_REFRESH(m2, np, m2->mc_ki[mc->mc_top]);
2459 txn->mt_flags |= MDB_TXN_ERROR;
2464 mdb_env_sync(MDB_env *env, int force)
2467 if (env->me_flags & MDB_RDONLY)
2469 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2470 if (env->me_flags & MDB_WRITEMAP) {
2471 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2472 ? MS_ASYNC : MS_SYNC;
2473 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2476 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2480 #ifdef BROKEN_FDATASYNC
2481 if (env->me_flags & MDB_FSYNCONLY) {
2482 if (fsync(env->me_fd))
2486 if (MDB_FDATASYNC(env->me_fd))
2493 /** Back up parent txn's cursors, then grab the originals for tracking */
2495 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2497 MDB_cursor *mc, *bk;
2502 for (i = src->mt_numdbs; --i >= 0; ) {
2503 if ((mc = src->mt_cursors[i]) != NULL) {
2504 size = sizeof(MDB_cursor);
2506 size += sizeof(MDB_xcursor);
2507 for (; mc; mc = bk->mc_next) {
2513 mc->mc_db = &dst->mt_dbs[i];
2514 /* Kill pointers into src to reduce abuse: The
2515 * user may not use mc until dst ends. But we need a valid
2516 * txn pointer here for cursor fixups to keep working.
2519 mc->mc_dbflag = &dst->mt_dbflags[i];
2520 if ((mx = mc->mc_xcursor) != NULL) {
2521 *(MDB_xcursor *)(bk+1) = *mx;
2522 mx->mx_cursor.mc_txn = dst;
2524 mc->mc_next = dst->mt_cursors[i];
2525 dst->mt_cursors[i] = mc;
2532 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2533 * @param[in] txn the transaction handle.
2534 * @param[in] merge true to keep changes to parent cursors, false to revert.
2535 * @return 0 on success, non-zero on failure.
2538 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2540 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2544 for (i = txn->mt_numdbs; --i >= 0; ) {
2545 for (mc = cursors[i]; mc; mc = next) {
2547 if ((bk = mc->mc_backup) != NULL) {
2549 /* Commit changes to parent txn */
2550 mc->mc_next = bk->mc_next;
2551 mc->mc_backup = bk->mc_backup;
2552 mc->mc_txn = bk->mc_txn;
2553 mc->mc_db = bk->mc_db;
2554 mc->mc_dbflag = bk->mc_dbflag;
2555 if ((mx = mc->mc_xcursor) != NULL)
2556 mx->mx_cursor.mc_txn = bk->mc_txn;
2558 /* Abort nested txn */
2560 if ((mx = mc->mc_xcursor) != NULL)
2561 *mx = *(MDB_xcursor *)(bk+1);
2565 /* Only malloced cursors are permanently tracked. */
2572 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2578 Pidset = F_SETLK, Pidcheck = F_GETLK
2582 /** Set or check a pid lock. Set returns 0 on success.
2583 * Check returns 0 if the process is certainly dead, nonzero if it may
2584 * be alive (the lock exists or an error happened so we do not know).
2586 * On Windows Pidset is a no-op, we merely check for the existence
2587 * of the process with the given pid. On POSIX we use a single byte
2588 * lock on the lockfile, set at an offset equal to the pid.
2591 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2593 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2596 if (op == Pidcheck) {
2597 h = OpenProcess(env->me_pidquery, FALSE, pid);
2598 /* No documented "no such process" code, but other program use this: */
2600 return ErrCode() != ERROR_INVALID_PARAMETER;
2601 /* A process exists until all handles to it close. Has it exited? */
2602 ret = WaitForSingleObject(h, 0) != 0;
2609 struct flock lock_info;
2610 memset(&lock_info, 0, sizeof(lock_info));
2611 lock_info.l_type = F_WRLCK;
2612 lock_info.l_whence = SEEK_SET;
2613 lock_info.l_start = pid;
2614 lock_info.l_len = 1;
2615 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2616 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2618 } else if ((rc = ErrCode()) == EINTR) {
2626 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2627 * @param[in] txn the transaction handle to initialize
2628 * @return 0 on success, non-zero on failure.
2631 mdb_txn_renew0(MDB_txn *txn)
2633 MDB_env *env = txn->mt_env;
2634 MDB_txninfo *ti = env->me_txns;
2636 unsigned int i, nr, flags = txn->mt_flags;
2638 int rc, new_notls = 0;
2640 if ((flags &= MDB_TXN_RDONLY) != 0) {
2642 meta = mdb_env_pick_meta(env);
2643 txn->mt_txnid = meta->mm_txnid;
2644 txn->mt_u.reader = NULL;
2646 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2647 pthread_getspecific(env->me_txkey);
2649 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2650 return MDB_BAD_RSLOT;
2652 MDB_PID_T pid = env->me_pid;
2653 MDB_THR_T tid = pthread_self();
2654 mdb_mutexref_t rmutex = env->me_rmutex;
2656 if (!env->me_live_reader) {
2657 rc = mdb_reader_pid(env, Pidset, pid);
2660 env->me_live_reader = 1;
2663 if (LOCK_MUTEX(rc, env, rmutex))
2665 nr = ti->mti_numreaders;
2666 for (i=0; i<nr; i++)
2667 if (ti->mti_readers[i].mr_pid == 0)
2669 if (i == env->me_maxreaders) {
2670 UNLOCK_MUTEX(rmutex);
2671 return MDB_READERS_FULL;
2673 r = &ti->mti_readers[i];
2674 /* Claim the reader slot, carefully since other code
2675 * uses the reader table un-mutexed: First reset the
2676 * slot, next publish it in mti_numreaders. After
2677 * that, it is safe for mdb_env_close() to touch it.
2678 * When it will be closed, we can finally claim it.
2681 r->mr_txnid = (txnid_t)-1;
2684 ti->mti_numreaders = ++nr;
2685 env->me_close_readers = nr;
2687 UNLOCK_MUTEX(rmutex);
2689 new_notls = (env->me_flags & MDB_NOTLS);
2690 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2695 do /* LY: Retry on a race, ITS#7970. */
2696 r->mr_txnid = ti->mti_txnid;
2697 while(r->mr_txnid != ti->mti_txnid);
2698 txn->mt_txnid = r->mr_txnid;
2699 txn->mt_u.reader = r;
2700 meta = env->me_metas[txn->mt_txnid & 1];
2704 /* Not yet touching txn == env->me_txn0, it may be active */
2706 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2708 txn->mt_txnid = ti->mti_txnid;
2709 meta = env->me_metas[txn->mt_txnid & 1];
2711 meta = mdb_env_pick_meta(env);
2712 txn->mt_txnid = meta->mm_txnid;
2716 if (txn->mt_txnid == mdb_debug_start)
2719 txn->mt_child = NULL;
2720 txn->mt_loose_pgs = NULL;
2721 txn->mt_loose_count = 0;
2722 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2723 txn->mt_u.dirty_list = env->me_dirty_list;
2724 txn->mt_u.dirty_list[0].mid = 0;
2725 txn->mt_free_pgs = env->me_free_pgs;
2726 txn->mt_free_pgs[0] = 0;
2727 txn->mt_spill_pgs = NULL;
2729 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2732 /* Copy the DB info and flags */
2733 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
2735 /* Moved to here to avoid a data race in read TXNs */
2736 txn->mt_next_pgno = meta->mm_last_pg+1;
2738 txn->mt_flags = flags;
2741 txn->mt_numdbs = env->me_numdbs;
2742 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
2743 x = env->me_dbflags[i];
2744 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2745 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
2747 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
2748 txn->mt_dbflags[FREE_DBI] = DB_VALID;
2750 if (env->me_flags & MDB_FATAL_ERROR) {
2751 DPUTS("environment had fatal error, must shutdown!");
2753 } else if (env->me_maxpg < txn->mt_next_pgno) {
2754 rc = MDB_MAP_RESIZED;
2758 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
2763 mdb_txn_renew(MDB_txn *txn)
2767 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
2770 rc = mdb_txn_renew0(txn);
2771 if (rc == MDB_SUCCESS) {
2772 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2773 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2774 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2780 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2784 int rc, size, tsize;
2786 flags &= MDB_TXN_BEGIN_FLAGS;
2787 flags |= env->me_flags & MDB_WRITEMAP;
2789 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
2793 /* Nested transactions: Max 1 child, write txns only, no writemap */
2794 flags |= parent->mt_flags;
2795 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
2796 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2798 /* Child txns save MDB_pgstate and use own copy of cursors */
2799 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
2800 size += tsize = sizeof(MDB_ntxn);
2801 } else if (flags & MDB_RDONLY) {
2802 size = env->me_maxdbs * (sizeof(MDB_db)+1);
2803 size += tsize = sizeof(MDB_txn);
2805 /* Reuse preallocated write txn. However, do not touch it until
2806 * mdb_txn_renew0() succeeds, since it currently may be active.
2811 if ((txn = calloc(1, size)) == NULL) {
2812 DPRINTF(("calloc: %s", strerror(errno)));
2815 txn->mt_dbxs = env->me_dbxs; /* static */
2816 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2817 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
2818 txn->mt_flags = flags;
2823 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2824 txn->mt_dbiseqs = parent->mt_dbiseqs;
2825 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2826 if (!txn->mt_u.dirty_list ||
2827 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2829 free(txn->mt_u.dirty_list);
2833 txn->mt_txnid = parent->mt_txnid;
2834 txn->mt_dirty_room = parent->mt_dirty_room;
2835 txn->mt_u.dirty_list[0].mid = 0;
2836 txn->mt_spill_pgs = NULL;
2837 txn->mt_next_pgno = parent->mt_next_pgno;
2838 parent->mt_flags |= MDB_TXN_HAS_CHILD;
2839 parent->mt_child = txn;
2840 txn->mt_parent = parent;
2841 txn->mt_numdbs = parent->mt_numdbs;
2842 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2843 /* Copy parent's mt_dbflags, but clear DB_NEW */
2844 for (i=0; i<txn->mt_numdbs; i++)
2845 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2847 ntxn = (MDB_ntxn *)txn;
2848 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2849 if (env->me_pghead) {
2850 size = MDB_IDL_SIZEOF(env->me_pghead);
2851 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2853 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2858 rc = mdb_cursor_shadow(parent, txn);
2860 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
2861 } else { /* MDB_RDONLY */
2862 txn->mt_dbiseqs = env->me_dbiseqs;
2864 rc = mdb_txn_renew0(txn);
2867 if (txn != env->me_txn0)
2870 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
2872 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2873 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
2874 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2881 mdb_txn_env(MDB_txn *txn)
2883 if(!txn) return NULL;
2888 mdb_txn_id(MDB_txn *txn)
2891 return txn->mt_txnid;
2894 /** Export or close DBI handles opened in this txn. */
2896 mdb_dbis_update(MDB_txn *txn, int keep)
2899 MDB_dbi n = txn->mt_numdbs;
2900 MDB_env *env = txn->mt_env;
2901 unsigned char *tdbflags = txn->mt_dbflags;
2903 for (i = n; --i >= CORE_DBS;) {
2904 if (tdbflags[i] & DB_NEW) {
2906 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2908 char *ptr = env->me_dbxs[i].md_name.mv_data;
2910 env->me_dbxs[i].md_name.mv_data = NULL;
2911 env->me_dbxs[i].md_name.mv_size = 0;
2912 env->me_dbflags[i] = 0;
2913 env->me_dbiseqs[i]++;
2919 if (keep && env->me_numdbs < n)
2923 /** End a transaction, except successful commit of a nested transaction.
2924 * May be called twice for readonly txns: First reset it, then abort.
2925 * @param[in] txn the transaction handle to end
2926 * @param[in] mode why and how to end the transaction
2929 mdb_txn_end(MDB_txn *txn, unsigned mode)
2931 MDB_env *env = txn->mt_env;
2933 static const char *const names[] = MDB_END_NAMES;
2936 /* Export or close DBI handles opened in this txn */
2937 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
2939 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2940 names[mode & MDB_END_OPMASK],
2941 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2942 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2944 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2945 if (txn->mt_u.reader) {
2946 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2947 if (!(env->me_flags & MDB_NOTLS)) {
2948 txn->mt_u.reader = NULL; /* txn does not own reader */
2949 } else if (mode & MDB_END_SLOT) {
2950 txn->mt_u.reader->mr_pid = 0;
2951 txn->mt_u.reader = NULL;
2952 } /* else txn owns the slot until it does MDB_END_SLOT */
2954 txn->mt_numdbs = 0; /* prevent further DBI activity */
2955 txn->mt_flags |= MDB_TXN_FINISHED;
2957 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
2958 pgno_t *pghead = env->me_pghead;
2960 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
2961 mdb_cursors_close(txn, 0);
2962 if (!(env->me_flags & MDB_WRITEMAP)) {
2963 mdb_dlist_free(txn);
2967 txn->mt_flags = MDB_TXN_FINISHED;
2969 if (!txn->mt_parent) {
2970 mdb_midl_shrink(&txn->mt_free_pgs);
2971 env->me_free_pgs = txn->mt_free_pgs;
2973 env->me_pghead = NULL;
2977 mode = 0; /* txn == env->me_txn0, do not free() it */
2979 /* The writer mutex was locked in mdb_txn_begin. */
2981 UNLOCK_MUTEX(env->me_wmutex);
2983 txn->mt_parent->mt_child = NULL;
2984 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
2985 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2986 mdb_midl_free(txn->mt_free_pgs);
2987 mdb_midl_free(txn->mt_spill_pgs);
2988 free(txn->mt_u.dirty_list);
2991 mdb_midl_free(pghead);
2994 if (mode & MDB_END_FREE)
2999 mdb_txn_reset(MDB_txn *txn)
3004 /* This call is only valid for read-only txns */
3005 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3008 mdb_txn_end(txn, MDB_END_RESET);
3012 mdb_txn_abort(MDB_txn *txn)
3018 mdb_txn_abort(txn->mt_child);
3020 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3023 /** Save the freelist as of this transaction to the freeDB.
3024 * This changes the freelist. Keep trying until it stabilizes.
3027 mdb_freelist_save(MDB_txn *txn)
3029 /* env->me_pghead[] can grow and shrink during this call.
3030 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3031 * Page numbers cannot disappear from txn->mt_free_pgs[].
3034 MDB_env *env = txn->mt_env;
3035 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3036 txnid_t pglast = 0, head_id = 0;
3037 pgno_t freecnt = 0, *free_pgs, *mop;
3038 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3040 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3042 if (env->me_pghead) {
3043 /* Make sure first page of freeDB is touched and on freelist */
3044 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3045 if (rc && rc != MDB_NOTFOUND)
3049 if (!env->me_pghead && txn->mt_loose_pgs) {
3050 /* Put loose page numbers in mt_free_pgs, since
3051 * we may be unable to return them to me_pghead.
3053 MDB_page *mp = txn->mt_loose_pgs;
3054 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3056 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3057 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3058 txn->mt_loose_pgs = NULL;
3059 txn->mt_loose_count = 0;
3062 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3063 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3064 ? SSIZE_MAX : maxfree_1pg;
3067 /* Come back here after each Put() in case freelist changed */
3072 /* If using records from freeDB which we have not yet
3073 * deleted, delete them and any we reserved for me_pghead.
3075 while (pglast < env->me_pglast) {
3076 rc = mdb_cursor_first(&mc, &key, NULL);
3079 pglast = head_id = *(txnid_t *)key.mv_data;
3080 total_room = head_room = 0;
3081 mdb_tassert(txn, pglast <= env->me_pglast);
3082 rc = mdb_cursor_del(&mc, 0);
3087 /* Save the IDL of pages freed by this txn, to a single record */
3088 if (freecnt < txn->mt_free_pgs[0]) {
3090 /* Make sure last page of freeDB is touched and on freelist */
3091 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3092 if (rc && rc != MDB_NOTFOUND)
3095 free_pgs = txn->mt_free_pgs;
3096 /* Write to last page of freeDB */
3097 key.mv_size = sizeof(txn->mt_txnid);
3098 key.mv_data = &txn->mt_txnid;
3100 freecnt = free_pgs[0];
3101 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3102 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3105 /* Retry if mt_free_pgs[] grew during the Put() */
3106 free_pgs = txn->mt_free_pgs;
3107 } while (freecnt < free_pgs[0]);
3108 mdb_midl_sort(free_pgs);
3109 memcpy(data.mv_data, free_pgs, data.mv_size);
3112 unsigned int i = free_pgs[0];
3113 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
3114 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3116 DPRINTF(("IDL %"Z"u", free_pgs[i]));
3122 mop = env->me_pghead;
3123 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3125 /* Reserve records for me_pghead[]. Split it if multi-page,
3126 * to avoid searching freeDB for a page range. Use keys in
3127 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3129 if (total_room >= mop_len) {
3130 if (total_room == mop_len || --more < 0)
3132 } else if (head_room >= maxfree_1pg && head_id > 1) {
3133 /* Keep current record (overflow page), add a new one */
3137 /* (Re)write {key = head_id, IDL length = head_room} */
3138 total_room -= head_room;
3139 head_room = mop_len - total_room;
3140 if (head_room > maxfree_1pg && head_id > 1) {
3141 /* Overflow multi-page for part of me_pghead */
3142 head_room /= head_id; /* amortize page sizes */
3143 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3144 } else if (head_room < 0) {
3145 /* Rare case, not bothering to delete this record */
3148 key.mv_size = sizeof(head_id);
3149 key.mv_data = &head_id;
3150 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3151 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3154 /* IDL is initially empty, zero out at least the length */
3155 pgs = (pgno_t *)data.mv_data;
3156 j = head_room > clean_limit ? head_room : 0;
3160 total_room += head_room;
3163 /* Return loose page numbers to me_pghead, though usually none are
3164 * left at this point. The pages themselves remain in dirty_list.
3166 if (txn->mt_loose_pgs) {
3167 MDB_page *mp = txn->mt_loose_pgs;
3168 unsigned count = txn->mt_loose_count;
3170 /* Room for loose pages + temp IDL with same */
3171 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3173 mop = env->me_pghead;
3174 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3175 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3176 loose[ ++count ] = mp->mp_pgno;
3178 mdb_midl_sort(loose);
3179 mdb_midl_xmerge(mop, loose);
3180 txn->mt_loose_pgs = NULL;
3181 txn->mt_loose_count = 0;
3185 /* Fill in the reserved me_pghead records */
3191 rc = mdb_cursor_first(&mc, &key, &data);
3192 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3193 txnid_t id = *(txnid_t *)key.mv_data;
3194 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3197 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3199 if (len > mop_len) {
3201 data.mv_size = (len + 1) * sizeof(MDB_ID);
3203 data.mv_data = mop -= len;
3206 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3208 if (rc || !(mop_len -= len))
3215 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3216 * @param[in] txn the transaction that's being committed
3217 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3218 * @return 0 on success, non-zero on failure.
3221 mdb_page_flush(MDB_txn *txn, int keep)
3223 MDB_env *env = txn->mt_env;
3224 MDB_ID2L dl = txn->mt_u.dirty_list;
3225 unsigned psize = env->me_psize, j;
3226 int i, pagecount = dl[0].mid, rc;
3227 size_t size = 0, pos = 0;
3229 MDB_page *dp = NULL;
3233 struct iovec iov[MDB_COMMIT_PAGES];
3234 ssize_t wpos = 0, wsize = 0, wres;
3235 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3241 if (env->me_flags & MDB_WRITEMAP) {
3242 /* Clear dirty flags */
3243 while (++i <= pagecount) {
3245 /* Don't flush this page yet */
3246 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3247 dp->mp_flags &= ~P_KEEP;
3251 dp->mp_flags &= ~P_DIRTY;
3256 /* Write the pages */
3258 if (++i <= pagecount) {
3260 /* Don't flush this page yet */
3261 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3262 dp->mp_flags &= ~P_KEEP;
3267 /* clear dirty flag */
3268 dp->mp_flags &= ~P_DIRTY;
3271 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3276 /* Windows actually supports scatter/gather I/O, but only on
3277 * unbuffered file handles. Since we're relying on the OS page
3278 * cache for all our data, that's self-defeating. So we just
3279 * write pages one at a time. We use the ov structure to set
3280 * the write offset, to at least save the overhead of a Seek
3283 DPRINTF(("committing page %"Z"u", pgno));
3284 memset(&ov, 0, sizeof(ov));
3285 ov.Offset = pos & 0xffffffff;
3286 ov.OffsetHigh = pos >> 16 >> 16;
3287 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3289 DPRINTF(("WriteFile: %d", rc));
3293 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3294 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3297 /* Write previous page(s) */
3298 #ifdef MDB_USE_PWRITEV
3299 wres = pwritev(env->me_fd, iov, n, wpos);
3302 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3305 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3309 DPRINTF(("lseek: %s", strerror(rc)));
3312 wres = writev(env->me_fd, iov, n);
3315 if (wres != wsize) {
3320 DPRINTF(("Write error: %s", strerror(rc)));
3322 rc = EIO; /* TODO: Use which error code? */
3323 DPUTS("short write, filesystem full?");
3334 DPRINTF(("committing page %"Z"u", pgno));
3335 next_pos = pos + size;
3336 iov[n].iov_len = size;
3337 iov[n].iov_base = (char *)dp;
3343 /* MIPS has cache coherency issues, this is a no-op everywhere else
3344 * Note: for any size >= on-chip cache size, entire on-chip cache is
3347 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3349 for (i = keep; ++i <= pagecount; ) {
3351 /* This is a page we skipped above */
3354 dl[j].mid = dp->mp_pgno;
3357 mdb_dpage_free(env, dp);
3362 txn->mt_dirty_room += i - j;
3368 mdb_txn_commit(MDB_txn *txn)
3371 unsigned int i, end_mode;
3377 /* mdb_txn_end() mode for a commit which writes nothing */
3378 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3380 if (txn->mt_child) {
3381 rc = mdb_txn_commit(txn->mt_child);
3388 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3392 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3393 DPUTS("txn has failed/finished, can't commit");
3395 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3400 if (txn->mt_parent) {
3401 MDB_txn *parent = txn->mt_parent;
3405 unsigned x, y, len, ps_len;
3407 /* Append our free list to parent's */
3408 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3411 mdb_midl_free(txn->mt_free_pgs);
3412 /* Failures after this must either undo the changes
3413 * to the parent or set MDB_TXN_ERROR in the parent.
3416 parent->mt_next_pgno = txn->mt_next_pgno;
3417 parent->mt_flags = txn->mt_flags;
3419 /* Merge our cursors into parent's and close them */
3420 mdb_cursors_close(txn, 1);
3422 /* Update parent's DB table. */
3423 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3424 parent->mt_numdbs = txn->mt_numdbs;
3425 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3426 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3427 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3428 /* preserve parent's DB_NEW status */
3429 x = parent->mt_dbflags[i] & DB_NEW;
3430 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3433 dst = parent->mt_u.dirty_list;
3434 src = txn->mt_u.dirty_list;
3435 /* Remove anything in our dirty list from parent's spill list */
3436 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3438 pspill[0] = (pgno_t)-1;
3439 /* Mark our dirty pages as deleted in parent spill list */
3440 for (i=0, len=src[0].mid; ++i <= len; ) {
3441 MDB_ID pn = src[i].mid << 1;
3442 while (pn > pspill[x])
3444 if (pn == pspill[x]) {
3449 /* Squash deleted pagenums if we deleted any */
3450 for (x=y; ++x <= ps_len; )
3451 if (!(pspill[x] & 1))
3452 pspill[++y] = pspill[x];
3456 /* Remove anything in our spill list from parent's dirty list */
3457 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3458 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3459 MDB_ID pn = txn->mt_spill_pgs[i];
3461 continue; /* deleted spillpg */
3463 y = mdb_mid2l_search(dst, pn);
3464 if (y <= dst[0].mid && dst[y].mid == pn) {
3466 while (y < dst[0].mid) {
3475 /* Find len = length of merging our dirty list with parent's */
3477 dst[0].mid = 0; /* simplify loops */
3478 if (parent->mt_parent) {
3479 len = x + src[0].mid;
3480 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3481 for (i = x; y && i; y--) {
3482 pgno_t yp = src[y].mid;
3483 while (yp < dst[i].mid)
3485 if (yp == dst[i].mid) {
3490 } else { /* Simplify the above for single-ancestor case */
3491 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3493 /* Merge our dirty list with parent's */
3495 for (i = len; y; dst[i--] = src[y--]) {
3496 pgno_t yp = src[y].mid;
3497 while (yp < dst[x].mid)
3498 dst[i--] = dst[x--];
3499 if (yp == dst[x].mid)
3500 free(dst[x--].mptr);
3502 mdb_tassert(txn, i == x);
3504 free(txn->mt_u.dirty_list);
3505 parent->mt_dirty_room = txn->mt_dirty_room;
3506 if (txn->mt_spill_pgs) {
3507 if (parent->mt_spill_pgs) {
3508 /* TODO: Prevent failure here, so parent does not fail */
3509 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3511 parent->mt_flags |= MDB_TXN_ERROR;
3512 mdb_midl_free(txn->mt_spill_pgs);
3513 mdb_midl_sort(parent->mt_spill_pgs);
3515 parent->mt_spill_pgs = txn->mt_spill_pgs;
3519 /* Append our loose page list to parent's */
3520 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3522 *lp = txn->mt_loose_pgs;
3523 parent->mt_loose_count += txn->mt_loose_count;
3525 parent->mt_child = NULL;
3526 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3531 if (txn != env->me_txn) {
3532 DPUTS("attempt to commit unknown transaction");
3537 mdb_cursors_close(txn, 0);
3539 if (!txn->mt_u.dirty_list[0].mid &&
3540 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3543 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3544 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3546 /* Update DB root pointers */
3547 if (txn->mt_numdbs > CORE_DBS) {
3551 data.mv_size = sizeof(MDB_db);
3553 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3554 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3555 if (txn->mt_dbflags[i] & DB_DIRTY) {
3556 if (TXN_DBI_CHANGED(txn, i)) {
3560 data.mv_data = &txn->mt_dbs[i];
3561 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3569 rc = mdb_freelist_save(txn);
3573 mdb_midl_free(env->me_pghead);
3574 env->me_pghead = NULL;
3575 mdb_midl_shrink(&txn->mt_free_pgs);
3581 if ((rc = mdb_page_flush(txn, 0)) ||
3582 (rc = mdb_env_sync(env, 0)) ||
3583 (rc = mdb_env_write_meta(txn)))
3585 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3588 mdb_txn_end(txn, end_mode);
3596 /** Read the environment parameters of a DB environment before
3597 * mapping it into memory.
3598 * @param[in] env the environment handle
3599 * @param[out] meta address of where to store the meta information
3600 * @return 0 on success, non-zero on failure.
3603 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3609 enum { Size = sizeof(pbuf) };
3611 /* We don't know the page size yet, so use a minimum value.
3612 * Read both meta pages so we can use the latest one.
3615 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3619 memset(&ov, 0, sizeof(ov));
3621 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3622 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3625 rc = pread(env->me_fd, &pbuf, Size, off);
3628 if (rc == 0 && off == 0)
3630 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3631 DPRINTF(("read: %s", mdb_strerror(rc)));
3635 p = (MDB_page *)&pbuf;
3637 if (!F_ISSET(p->mp_flags, P_META)) {
3638 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3643 if (m->mm_magic != MDB_MAGIC) {
3644 DPUTS("meta has invalid magic");
3648 if (m->mm_version != MDB_DATA_VERSION) {
3649 DPRINTF(("database is version %u, expected version %u",
3650 m->mm_version, MDB_DATA_VERSION));
3651 return MDB_VERSION_MISMATCH;
3654 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3660 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3662 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3664 meta->mm_magic = MDB_MAGIC;
3665 meta->mm_version = MDB_DATA_VERSION;
3666 meta->mm_mapsize = env->me_mapsize;
3667 meta->mm_psize = env->me_psize;
3668 meta->mm_last_pg = NUM_METAS-1;
3669 meta->mm_flags = env->me_flags & 0xffff;
3670 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3671 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3672 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3675 /** Write the environment parameters of a freshly created DB environment.
3676 * @param[in] env the environment handle
3677 * @param[in] meta the #MDB_meta to write
3678 * @return 0 on success, non-zero on failure.
3681 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3689 memset(&ov, 0, sizeof(ov));
3690 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3692 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3695 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3696 len = pwrite(fd, ptr, size, pos); \
3697 if (len == -1 && ErrCode() == EINTR) continue; \
3698 rc = (len >= 0); break; } while(1)
3701 DPUTS("writing new meta page");
3703 psize = env->me_psize;
3705 p = calloc(NUM_METAS, psize);
3710 p->mp_flags = P_META;
3711 *(MDB_meta *)METADATA(p) = *meta;
3713 q = (MDB_page *)((char *)p + psize);
3715 q->mp_flags = P_META;
3716 *(MDB_meta *)METADATA(q) = *meta;
3718 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
3721 else if ((unsigned) len == psize * NUM_METAS)
3729 /** Update the environment info to commit a transaction.
3730 * @param[in] txn the transaction that's being committed
3731 * @return 0 on success, non-zero on failure.
3734 mdb_env_write_meta(MDB_txn *txn)
3737 MDB_meta meta, metab, *mp;
3741 int rc, len, toggle;
3750 toggle = txn->mt_txnid & 1;
3751 DPRINTF(("writing meta page %d for root page %"Z"u",
3752 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3755 flags = env->me_flags;
3756 mp = env->me_metas[toggle];
3757 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3758 /* Persist any increases of mapsize config */
3759 if (mapsize < env->me_mapsize)
3760 mapsize = env->me_mapsize;
3762 if (flags & MDB_WRITEMAP) {
3763 mp->mm_mapsize = mapsize;
3764 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3765 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3766 mp->mm_last_pg = txn->mt_next_pgno - 1;
3767 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
3768 !(defined(__i386__) || defined(__x86_64__))
3769 /* LY: issue a memory barrier, if not x86. ITS#7969 */
3770 __sync_synchronize();
3772 mp->mm_txnid = txn->mt_txnid;
3773 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3774 unsigned meta_size = env->me_psize;
3775 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3776 ptr = (char *)mp - PAGEHDRSZ;
3777 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3778 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
3782 if (MDB_MSYNC(ptr, meta_size, rc)) {
3789 metab.mm_txnid = mp->mm_txnid;
3790 metab.mm_last_pg = mp->mm_last_pg;
3792 meta.mm_mapsize = mapsize;
3793 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3794 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3795 meta.mm_last_pg = txn->mt_next_pgno - 1;
3796 meta.mm_txnid = txn->mt_txnid;
3798 off = offsetof(MDB_meta, mm_mapsize);
3799 ptr = (char *)&meta + off;
3800 len = sizeof(MDB_meta) - off;
3801 off += (char *)mp - env->me_map;
3803 /* Write to the SYNC fd */
3804 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
3807 memset(&ov, 0, sizeof(ov));
3809 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3814 rc = pwrite(mfd, ptr, len, off);
3817 rc = rc < 0 ? ErrCode() : EIO;
3822 DPUTS("write failed, disk error?");
3823 /* On a failure, the pagecache still contains the new data.
3824 * Write some old data back, to prevent it from being used.
3825 * Use the non-SYNC fd; we know it will fail anyway.
3827 meta.mm_last_pg = metab.mm_last_pg;
3828 meta.mm_txnid = metab.mm_txnid;
3830 memset(&ov, 0, sizeof(ov));
3832 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3834 r2 = pwrite(env->me_fd, ptr, len, off);
3835 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3838 env->me_flags |= MDB_FATAL_ERROR;
3841 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3842 CACHEFLUSH(env->me_map + off, len, DCACHE);
3844 /* Memory ordering issues are irrelevant; since the entire writer
3845 * is wrapped by wmutex, all of these changes will become visible
3846 * after the wmutex is unlocked. Since the DB is multi-version,
3847 * readers will get consistent data regardless of how fresh or
3848 * how stale their view of these values is.
3851 env->me_txns->mti_txnid = txn->mt_txnid;
3856 /** Check both meta pages to see which one is newer.
3857 * @param[in] env the environment handle
3858 * @return newest #MDB_meta.
3861 mdb_env_pick_meta(const MDB_env *env)
3863 MDB_meta *const *metas = env->me_metas;
3864 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
3868 mdb_env_create(MDB_env **env)
3872 e = calloc(1, sizeof(MDB_env));
3876 e->me_maxreaders = DEFAULT_READERS;
3877 e->me_maxdbs = e->me_numdbs = CORE_DBS;
3878 e->me_fd = INVALID_HANDLE_VALUE;
3879 e->me_lfd = INVALID_HANDLE_VALUE;
3880 e->me_mfd = INVALID_HANDLE_VALUE;
3881 #ifdef MDB_USE_POSIX_SEM
3882 e->me_rmutex = SEM_FAILED;
3883 e->me_wmutex = SEM_FAILED;
3885 e->me_pid = getpid();
3886 GET_PAGESIZE(e->me_os_psize);
3887 VGMEMP_CREATE(e,0,0);
3893 mdb_env_map(MDB_env *env, void *addr)
3896 unsigned int flags = env->me_flags;
3900 LONG sizelo, sizehi;
3903 if (flags & MDB_RDONLY) {
3904 /* Don't set explicit map size, use whatever exists */
3909 msize = env->me_mapsize;
3910 sizelo = msize & 0xffffffff;
3911 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3913 /* Windows won't create mappings for zero length files.
3914 * and won't map more than the file size.
3915 * Just set the maxsize right now.
3917 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3918 || !SetEndOfFile(env->me_fd)
3919 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3923 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3924 PAGE_READWRITE : PAGE_READONLY,
3925 sizehi, sizelo, NULL);
3928 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3929 FILE_MAP_WRITE : FILE_MAP_READ,
3931 rc = env->me_map ? 0 : ErrCode();
3936 int prot = PROT_READ;
3937 if (flags & MDB_WRITEMAP) {
3939 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3942 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3944 if (env->me_map == MAP_FAILED) {
3949 if (flags & MDB_NORDAHEAD) {
3950 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3952 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3954 #ifdef POSIX_MADV_RANDOM
3955 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3956 #endif /* POSIX_MADV_RANDOM */
3957 #endif /* MADV_RANDOM */
3961 /* Can happen because the address argument to mmap() is just a
3962 * hint. mmap() can pick another, e.g. if the range is in use.
3963 * The MAP_FIXED flag would prevent that, but then mmap could
3964 * instead unmap existing pages to make room for the new map.
3966 if (addr && env->me_map != addr)
3967 return EBUSY; /* TODO: Make a new MDB_* error code? */
3969 p = (MDB_page *)env->me_map;
3970 env->me_metas[0] = METADATA(p);
3971 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3977 mdb_env_set_mapsize(MDB_env *env, size_t size)
3979 /* If env is already open, caller is responsible for making
3980 * sure there are no active txns.
3988 meta = mdb_env_pick_meta(env);
3990 size = meta->mm_mapsize;
3992 /* Silently round up to minimum if the size is too small */
3993 size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
3997 munmap(env->me_map, env->me_mapsize);
3998 env->me_mapsize = size;
3999 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4000 rc = mdb_env_map(env, old);
4004 env->me_mapsize = size;
4006 env->me_maxpg = env->me_mapsize / env->me_psize;
4011 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4015 env->me_maxdbs = dbs + CORE_DBS;
4020 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4022 if (env->me_map || readers < 1)
4024 env->me_maxreaders = readers;
4029 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4031 if (!env || !readers)
4033 *readers = env->me_maxreaders;
4038 mdb_fsize(HANDLE fd, size_t *size)
4041 LARGE_INTEGER fsize;
4043 if (!GetFileSizeEx(fd, &fsize))
4046 *size = fsize.QuadPart;
4058 #ifdef BROKEN_FDATASYNC
4059 #include <sys/utsname.h>
4060 #include <sys/vfs.h>
4063 /** Further setup required for opening an LMDB environment
4066 mdb_env_open2(MDB_env *env)
4068 unsigned int flags = env->me_flags;
4069 int i, newenv = 0, rc;
4073 /* See if we should use QueryLimited */
4075 if ((rc & 0xff) > 5)
4076 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4078 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4081 #ifdef BROKEN_FDATASYNC
4082 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4083 * https://lkml.org/lkml/2012/9/3/83
4084 * Kernels after 3.6-rc6 are known good.
4085 * https://lkml.org/lkml/2012/9/10/556
4086 * See if the DB is on ext3/ext4, then check for new enough kernel
4087 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4092 fstatfs(env->me_fd, &st);
4093 while (st.f_type == 0xEF53) {
4097 if (uts.release[0] < '3') {
4098 if (!strncmp(uts.release, "2.6.32.", 7)) {
4099 i = atoi(uts.release+7);
4101 break; /* 2.6.32.60 and newer is OK */
4102 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4103 i = atoi(uts.release+7);
4105 break; /* 2.6.34.15 and newer is OK */
4107 } else if (uts.release[0] == '3') {
4108 i = atoi(uts.release+2);
4110 break; /* 3.6 and newer is OK */
4112 i = atoi(uts.release+4);
4114 break; /* 3.5.4 and newer is OK */
4115 } else if (i == 2) {
4116 i = atoi(uts.release+4);
4118 break; /* 3.2.30 and newer is OK */
4120 } else { /* 4.x and newer is OK */
4123 env->me_flags |= MDB_FSYNCONLY;
4129 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4132 DPUTS("new mdbenv");
4134 env->me_psize = env->me_os_psize;
4135 if (env->me_psize > MAX_PAGESIZE)
4136 env->me_psize = MAX_PAGESIZE;
4137 memset(&meta, 0, sizeof(meta));
4138 mdb_env_init_meta0(env, &meta);
4139 meta.mm_mapsize = DEFAULT_MAPSIZE;
4141 env->me_psize = meta.mm_psize;
4144 /* Was a mapsize configured? */
4145 if (!env->me_mapsize) {
4146 env->me_mapsize = meta.mm_mapsize;
4149 /* Make sure mapsize >= committed data size. Even when using
4150 * mm_mapsize, which could be broken in old files (ITS#7789).
4152 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4153 if (env->me_mapsize < minsize)
4154 env->me_mapsize = minsize;
4156 meta.mm_mapsize = env->me_mapsize;
4158 if (newenv && !(flags & MDB_FIXEDMAP)) {
4159 /* mdb_env_map() may grow the datafile. Write the metapages
4160 * first, so the file will be valid if initialization fails.
4161 * Except with FIXEDMAP, since we do not yet know mm_address.
4162 * We could fill in mm_address later, but then a different
4163 * program might end up doing that - one with a memory layout
4164 * and map address which does not suit the main program.
4166 rc = mdb_env_init_meta(env, &meta);
4172 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4177 if (flags & MDB_FIXEDMAP)
4178 meta.mm_address = env->me_map;
4179 i = mdb_env_init_meta(env, &meta);
4180 if (i != MDB_SUCCESS) {
4185 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4186 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4188 #if !(MDB_MAXKEYSIZE)
4189 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4191 env->me_maxpg = env->me_mapsize / env->me_psize;
4195 MDB_meta *meta = mdb_env_pick_meta(env);
4196 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4198 DPRINTF(("opened database version %u, pagesize %u",
4199 meta->mm_version, env->me_psize));
4200 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4201 DPRINTF(("depth: %u", db->md_depth));
4202 DPRINTF(("entries: %"Z"u", db->md_entries));
4203 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
4204 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
4205 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
4206 DPRINTF(("root: %"Z"u", db->md_root));
4214 /** Release a reader thread's slot in the reader lock table.
4215 * This function is called automatically when a thread exits.
4216 * @param[in] ptr This points to the slot in the reader lock table.
4219 mdb_env_reader_dest(void *ptr)
4221 MDB_reader *reader = ptr;
4227 /** Junk for arranging thread-specific callbacks on Windows. This is
4228 * necessarily platform and compiler-specific. Windows supports up
4229 * to 1088 keys. Let's assume nobody opens more than 64 environments
4230 * in a single process, for now. They can override this if needed.
4232 #ifndef MAX_TLS_KEYS
4233 #define MAX_TLS_KEYS 64
4235 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4236 static int mdb_tls_nkeys;
4238 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4242 case DLL_PROCESS_ATTACH: break;
4243 case DLL_THREAD_ATTACH: break;
4244 case DLL_THREAD_DETACH:
4245 for (i=0; i<mdb_tls_nkeys; i++) {
4246 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4248 mdb_env_reader_dest(r);
4252 case DLL_PROCESS_DETACH: break;
4257 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4259 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4263 /* Force some symbol references.
4264 * _tls_used forces the linker to create the TLS directory if not already done
4265 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4267 #pragma comment(linker, "/INCLUDE:_tls_used")
4268 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4269 #pragma const_seg(".CRT$XLB")
4270 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4271 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4274 #pragma comment(linker, "/INCLUDE:__tls_used")
4275 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4276 #pragma data_seg(".CRT$XLB")
4277 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4279 #endif /* WIN 32/64 */
4280 #endif /* !__GNUC__ */
4283 /** Downgrade the exclusive lock on the region back to shared */
4285 mdb_env_share_locks(MDB_env *env, int *excl)
4288 MDB_meta *meta = mdb_env_pick_meta(env);
4290 env->me_txns->mti_txnid = meta->mm_txnid;
4295 /* First acquire a shared lock. The Unlock will
4296 * then release the existing exclusive lock.
4298 memset(&ov, 0, sizeof(ov));
4299 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4302 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4308 struct flock lock_info;
4309 /* The shared lock replaces the existing lock */
4310 memset((void *)&lock_info, 0, sizeof(lock_info));
4311 lock_info.l_type = F_RDLCK;
4312 lock_info.l_whence = SEEK_SET;
4313 lock_info.l_start = 0;
4314 lock_info.l_len = 1;
4315 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4316 (rc = ErrCode()) == EINTR) ;
4317 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4324 /** Try to get exclusive lock, otherwise shared.
4325 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4328 mdb_env_excl_lock(MDB_env *env, int *excl)
4332 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4336 memset(&ov, 0, sizeof(ov));
4337 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4344 struct flock lock_info;
4345 memset((void *)&lock_info, 0, sizeof(lock_info));
4346 lock_info.l_type = F_WRLCK;
4347 lock_info.l_whence = SEEK_SET;
4348 lock_info.l_start = 0;
4349 lock_info.l_len = 1;
4350 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4351 (rc = ErrCode()) == EINTR) ;
4355 # ifndef MDB_USE_POSIX_MUTEX
4356 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4359 lock_info.l_type = F_RDLCK;
4360 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4361 (rc = ErrCode()) == EINTR) ;
4371 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4373 * @(#) $Revision: 5.1 $
4374 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4375 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4377 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4381 * Please do not copyright this code. This code is in the public domain.
4383 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4384 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4385 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4386 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4387 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4388 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4389 * PERFORMANCE OF THIS SOFTWARE.
4392 * chongo <Landon Curt Noll> /\oo/\
4393 * http://www.isthe.com/chongo/
4395 * Share and Enjoy! :-)
4398 typedef unsigned long long mdb_hash_t;
4399 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4401 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4402 * @param[in] val value to hash
4403 * @param[in] hval initial value for hash
4404 * @return 64 bit hash
4406 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4407 * hval arg on the first call.
4410 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4412 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4413 unsigned char *end = s + val->mv_size;
4415 * FNV-1a hash each octet of the string
4418 /* xor the bottom with the current octet */
4419 hval ^= (mdb_hash_t)*s++;
4421 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4422 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4423 (hval << 7) + (hval << 8) + (hval << 40);
4425 /* return our new hash value */
4429 /** Hash the string and output the encoded hash.
4430 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4431 * very short name limits. We don't care about the encoding being reversible,
4432 * we just want to preserve as many bits of the input as possible in a
4433 * small printable string.
4434 * @param[in] str string to hash
4435 * @param[out] encbuf an array of 11 chars to hold the hash
4437 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4440 mdb_pack85(unsigned long l, char *out)
4444 for (i=0; i<5; i++) {
4445 *out++ = mdb_a85[l % 85];
4451 mdb_hash_enc(MDB_val *val, char *encbuf)
4453 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4455 mdb_pack85(h, encbuf);
4456 mdb_pack85(h>>32, encbuf+5);
4461 /** Open and/or initialize the lock region for the environment.
4462 * @param[in] env The LMDB environment.
4463 * @param[in] lpath The pathname of the file used for the lock region.
4464 * @param[in] mode The Unix permissions for the file, if we create it.
4465 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4466 * @return 0 on success, non-zero on failure.
4469 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4472 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4474 # define MDB_ERRCODE_ROFS EROFS
4475 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4476 # define MDB_CLOEXEC O_CLOEXEC
4479 # define MDB_CLOEXEC 0
4487 rc = utf8_to_utf16(lpath, -1, &wlpath, NULL);
4490 env->me_lfd = CreateFileW(wlpath, GENERIC_READ|GENERIC_WRITE,
4491 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4492 FILE_ATTRIBUTE_NORMAL, NULL);
4495 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4497 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4499 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4504 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4505 /* Lose record locks when exec*() */
4506 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4507 fcntl(env->me_lfd, F_SETFD, fdflags);
4510 if (!(env->me_flags & MDB_NOTLS)) {
4511 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4514 env->me_flags |= MDB_ENV_TXKEY;
4516 /* Windows TLS callbacks need help finding their TLS info. */
4517 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4521 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4525 /* Try to get exclusive lock. If we succeed, then
4526 * nobody is using the lock region and we should initialize it.
4528 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4531 size = GetFileSize(env->me_lfd, NULL);
4533 size = lseek(env->me_lfd, 0, SEEK_END);
4534 if (size == -1) goto fail_errno;
4536 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4537 if (size < rsize && *excl > 0) {
4539 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4540 || !SetEndOfFile(env->me_lfd))
4543 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4547 size = rsize - sizeof(MDB_txninfo);
4548 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4553 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4555 if (!mh) goto fail_errno;
4556 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4558 if (!env->me_txns) goto fail_errno;
4560 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4562 if (m == MAP_FAILED) goto fail_errno;
4568 BY_HANDLE_FILE_INFORMATION stbuf;
4577 if (!mdb_sec_inited) {
4578 InitializeSecurityDescriptor(&mdb_null_sd,
4579 SECURITY_DESCRIPTOR_REVISION);
4580 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4581 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4582 mdb_all_sa.bInheritHandle = FALSE;
4583 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4586 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4587 idbuf.volume = stbuf.dwVolumeSerialNumber;
4588 idbuf.nhigh = stbuf.nFileIndexHigh;
4589 idbuf.nlow = stbuf.nFileIndexLow;
4590 val.mv_data = &idbuf;
4591 val.mv_size = sizeof(idbuf);
4592 mdb_hash_enc(&val, encbuf);
4593 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4594 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4595 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4596 if (!env->me_rmutex) goto fail_errno;
4597 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4598 if (!env->me_wmutex) goto fail_errno;
4599 #elif defined(MDB_USE_POSIX_SEM)
4608 #if defined(__NetBSD__)
4609 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4611 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4612 idbuf.dev = stbuf.st_dev;
4613 idbuf.ino = stbuf.st_ino;
4614 val.mv_data = &idbuf;
4615 val.mv_size = sizeof(idbuf);
4616 mdb_hash_enc(&val, encbuf);
4617 #ifdef MDB_SHORT_SEMNAMES
4618 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4620 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4621 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4622 /* Clean up after a previous run, if needed: Try to
4623 * remove both semaphores before doing anything else.
4625 sem_unlink(env->me_txns->mti_rmname);
4626 sem_unlink(env->me_txns->mti_wmname);
4627 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4628 O_CREAT|O_EXCL, mode, 1);
4629 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4630 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4631 O_CREAT|O_EXCL, mode, 1);
4632 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4633 #else /* MDB_USE_POSIX_MUTEX: */
4634 pthread_mutexattr_t mattr;
4636 /* Solaris needs this before initing a robust mutex. Otherwise
4637 * it may skip the init and return EBUSY "seems someone already
4638 * inited" or EINVAL "it was inited differently".
4640 memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
4641 memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
4643 if ((rc = pthread_mutexattr_init(&mattr)))
4646 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
4647 #ifdef MDB_ROBUST_SUPPORTED
4648 if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
4650 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
4651 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
4652 pthread_mutexattr_destroy(&mattr);
4655 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4657 env->me_txns->mti_magic = MDB_MAGIC;
4658 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4659 env->me_txns->mti_txnid = 0;
4660 env->me_txns->mti_numreaders = 0;
4663 if (env->me_txns->mti_magic != MDB_MAGIC) {
4664 DPUTS("lock region has invalid magic");
4668 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4669 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4670 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4671 rc = MDB_VERSION_MISMATCH;
4675 if (rc && rc != EACCES && rc != EAGAIN) {
4679 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4680 if (!env->me_rmutex) goto fail_errno;
4681 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4682 if (!env->me_wmutex) goto fail_errno;
4683 #elif defined(MDB_USE_POSIX_SEM)
4684 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4685 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4686 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4687 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4698 /** The name of the lock file in the DB environment */
4699 #define LOCKNAME "/lock.mdb"
4700 /** The name of the data file in the DB environment */
4701 #define DATANAME "/data.mdb"
4702 /** The suffix of the lock file when no subdir is used */
4703 #define LOCKSUFF "-lock"
4704 /** Only a subset of the @ref mdb_env flags can be changed
4705 * at runtime. Changing other flags requires closing the
4706 * environment and re-opening it with the new flags.
4708 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4709 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
4710 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4712 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4713 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4717 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4719 int oflags, rc, len, excl = -1;
4720 char *lpath, *dpath;
4725 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4729 if (flags & MDB_NOSUBDIR) {
4730 rc = len + sizeof(LOCKSUFF) + len + 1;
4732 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4737 if (flags & MDB_NOSUBDIR) {
4738 dpath = lpath + len + sizeof(LOCKSUFF);
4739 sprintf(lpath, "%s" LOCKSUFF, path);
4740 strcpy(dpath, path);
4742 dpath = lpath + len + sizeof(LOCKNAME);
4743 sprintf(lpath, "%s" LOCKNAME, path);
4744 sprintf(dpath, "%s" DATANAME, path);
4748 flags |= env->me_flags;
4749 if (flags & MDB_RDONLY) {
4750 /* silently ignore WRITEMAP when we're only getting read access */
4751 flags &= ~MDB_WRITEMAP;
4753 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4754 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4757 env->me_flags = flags |= MDB_ENV_ACTIVE;
4761 env->me_path = strdup(path);
4762 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4763 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4764 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4765 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4769 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
4771 /* For RDONLY, get lockfile after we know datafile exists */
4772 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4773 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4779 if (F_ISSET(flags, MDB_RDONLY)) {
4780 oflags = GENERIC_READ;
4781 len = OPEN_EXISTING;
4783 oflags = GENERIC_READ|GENERIC_WRITE;
4786 mode = FILE_ATTRIBUTE_NORMAL;
4787 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
4790 env->me_fd = CreateFileW(wpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4791 NULL, len, mode, NULL);
4794 if (F_ISSET(flags, MDB_RDONLY))
4797 oflags = O_RDWR | O_CREAT;
4799 env->me_fd = open(dpath, oflags, mode);
4801 if (env->me_fd == INVALID_HANDLE_VALUE) {
4806 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4807 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4812 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4813 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4814 env->me_mfd = env->me_fd;
4816 /* Synchronous fd for meta writes. Needed even with
4817 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4820 len = OPEN_EXISTING;
4821 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
4824 env->me_mfd = CreateFileW(wpath, oflags,
4825 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4826 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4830 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4832 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4837 DPRINTF(("opened dbenv %p", (void *) env));
4839 rc = mdb_env_share_locks(env, &excl);
4843 if (!(flags & MDB_RDONLY)) {
4845 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
4846 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
4847 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
4848 (txn = calloc(1, size)))
4850 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
4851 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
4852 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
4853 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
4855 txn->mt_dbxs = env->me_dbxs;
4856 txn->mt_flags = MDB_TXN_FINISHED;
4866 mdb_env_close0(env, excl);
4872 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4874 mdb_env_close0(MDB_env *env, int excl)
4878 if (!(env->me_flags & MDB_ENV_ACTIVE))
4881 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4883 for (i = env->me_maxdbs; --i >= CORE_DBS; )
4884 free(env->me_dbxs[i].md_name.mv_data);
4889 free(env->me_dbiseqs);
4890 free(env->me_dbflags);
4892 free(env->me_dirty_list);
4894 mdb_midl_free(env->me_free_pgs);
4896 if (env->me_flags & MDB_ENV_TXKEY) {
4897 pthread_key_delete(env->me_txkey);
4899 /* Delete our key from the global list */
4900 for (i=0; i<mdb_tls_nkeys; i++)
4901 if (mdb_tls_keys[i] == env->me_txkey) {
4902 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4910 munmap(env->me_map, env->me_mapsize);
4912 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4913 (void) close(env->me_mfd);
4914 if (env->me_fd != INVALID_HANDLE_VALUE)
4915 (void) close(env->me_fd);
4917 MDB_PID_T pid = env->me_pid;
4918 /* Clearing readers is done in this function because
4919 * me_txkey with its destructor must be disabled first.
4921 * We skip the the reader mutex, so we touch only
4922 * data owned by this process (me_close_readers and
4923 * our readers), and clear each reader atomically.
4925 for (i = env->me_close_readers; --i >= 0; )
4926 if (env->me_txns->mti_readers[i].mr_pid == pid)
4927 env->me_txns->mti_readers[i].mr_pid = 0;
4929 if (env->me_rmutex) {
4930 CloseHandle(env->me_rmutex);
4931 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4933 /* Windows automatically destroys the mutexes when
4934 * the last handle closes.
4936 #elif defined(MDB_USE_POSIX_SEM)
4937 if (env->me_rmutex != SEM_FAILED) {
4938 sem_close(env->me_rmutex);
4939 if (env->me_wmutex != SEM_FAILED)
4940 sem_close(env->me_wmutex);
4941 /* If we have the filelock: If we are the
4942 * only remaining user, clean up semaphores.
4945 mdb_env_excl_lock(env, &excl);
4947 sem_unlink(env->me_txns->mti_rmname);
4948 sem_unlink(env->me_txns->mti_wmname);
4952 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4954 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4957 /* Unlock the lockfile. Windows would have unlocked it
4958 * after closing anyway, but not necessarily at once.
4960 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4963 (void) close(env->me_lfd);
4966 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4970 mdb_env_close(MDB_env *env)
4977 VGMEMP_DESTROY(env);
4978 while ((dp = env->me_dpages) != NULL) {
4979 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4980 env->me_dpages = dp->mp_next;
4984 mdb_env_close0(env, 0);
4988 /** Compare two items pointing at aligned size_t's */
4990 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4992 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4993 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4996 /** Compare two items pointing at aligned unsigned int's.
4998 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
4999 * but #mdb_cmp_clong() is called instead if the data type is size_t.
5002 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5004 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5005 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5008 /** Compare two items pointing at unsigned ints of unknown alignment.
5009 * Nodes and keys are guaranteed to be 2-byte aligned.
5012 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5014 #if BYTE_ORDER == LITTLE_ENDIAN
5015 unsigned short *u, *c;
5018 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5019 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5022 } while(!x && u > (unsigned short *)a->mv_data);
5025 unsigned short *u, *c, *end;
5028 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5029 u = (unsigned short *)a->mv_data;
5030 c = (unsigned short *)b->mv_data;
5033 } while(!x && u < end);
5038 /** Compare two items lexically */
5040 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5047 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5053 diff = memcmp(a->mv_data, b->mv_data, len);
5054 return diff ? diff : len_diff<0 ? -1 : len_diff;
5057 /** Compare two items in reverse byte order */
5059 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5061 const unsigned char *p1, *p2, *p1_lim;
5065 p1_lim = (const unsigned char *)a->mv_data;
5066 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5067 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5069 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5075 while (p1 > p1_lim) {
5076 diff = *--p1 - *--p2;
5080 return len_diff<0 ? -1 : len_diff;
5083 /** Search for key within a page, using binary search.
5084 * Returns the smallest entry larger or equal to the key.
5085 * If exactp is non-null, stores whether the found entry was an exact match
5086 * in *exactp (1 or 0).
5087 * Updates the cursor index with the index of the found entry.
5088 * If no entry larger or equal to the key is found, returns NULL.
5091 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5093 unsigned int i = 0, nkeys;
5096 MDB_page *mp = mc->mc_pg[mc->mc_top];
5097 MDB_node *node = NULL;
5102 nkeys = NUMKEYS(mp);
5104 DPRINTF(("searching %u keys in %s %spage %"Z"u",
5105 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5108 low = IS_LEAF(mp) ? 0 : 1;
5110 cmp = mc->mc_dbx->md_cmp;
5112 /* Branch pages have no data, so if using integer keys,
5113 * alignment is guaranteed. Use faster mdb_cmp_int.
5115 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5116 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
5123 nodekey.mv_size = mc->mc_db->md_pad;
5124 node = NODEPTR(mp, 0); /* fake */
5125 while (low <= high) {
5126 i = (low + high) >> 1;
5127 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5128 rc = cmp(key, &nodekey);
5129 DPRINTF(("found leaf index %u [%s], rc = %i",
5130 i, DKEY(&nodekey), rc));
5139 while (low <= high) {
5140 i = (low + high) >> 1;
5142 node = NODEPTR(mp, i);
5143 nodekey.mv_size = NODEKSZ(node);
5144 nodekey.mv_data = NODEKEY(node);
5146 rc = cmp(key, &nodekey);
5149 DPRINTF(("found leaf index %u [%s], rc = %i",
5150 i, DKEY(&nodekey), rc));
5152 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
5153 i, DKEY(&nodekey), NODEPGNO(node), rc));
5164 if (rc > 0) { /* Found entry is less than the key. */
5165 i++; /* Skip to get the smallest entry larger than key. */
5167 node = NODEPTR(mp, i);
5170 *exactp = (rc == 0 && nkeys > 0);
5171 /* store the key index */
5172 mc->mc_ki[mc->mc_top] = i;
5174 /* There is no entry larger or equal to the key. */
5177 /* nodeptr is fake for LEAF2 */
5183 mdb_cursor_adjust(MDB_cursor *mc, func)
5187 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5188 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5195 /** Pop a page off the top of the cursor's stack. */
5197 mdb_cursor_pop(MDB_cursor *mc)
5200 DPRINTF(("popping page %"Z"u off db %d cursor %p",
5201 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5207 mc->mc_flags &= ~C_INITIALIZED;
5212 /** Push a page onto the top of the cursor's stack. */
5214 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5216 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
5217 DDBI(mc), (void *) mc));
5219 if (mc->mc_snum >= CURSOR_STACK) {
5220 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5221 return MDB_CURSOR_FULL;
5224 mc->mc_top = mc->mc_snum++;
5225 mc->mc_pg[mc->mc_top] = mp;
5226 mc->mc_ki[mc->mc_top] = 0;
5231 /** Find the address of the page corresponding to a given page number.
5232 * @param[in] mc the cursor accessing the page.
5233 * @param[in] pgno the page number for the page to retrieve.
5234 * @param[out] ret address of a pointer where the page's address will be stored.
5235 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5236 * @return 0 on success, non-zero on failure.
5239 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
5241 MDB_txn *txn = mc->mc_txn;
5242 MDB_env *env = txn->mt_env;
5246 if (! (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_WRITEMAP))) {
5250 MDB_ID2L dl = tx2->mt_u.dirty_list;
5252 /* Spilled pages were dirtied in this txn and flushed
5253 * because the dirty list got full. Bring this page
5254 * back in from the map (but don't unspill it here,
5255 * leave that unless page_touch happens again).
5257 if (tx2->mt_spill_pgs) {
5258 MDB_ID pn = pgno << 1;
5259 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5260 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5261 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5266 unsigned x = mdb_mid2l_search(dl, pgno);
5267 if (x <= dl[0].mid && dl[x].mid == pgno) {
5273 } while ((tx2 = tx2->mt_parent) != NULL);
5276 if (pgno < txn->mt_next_pgno) {
5278 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5280 DPRINTF(("page %"Z"u not found", pgno));
5281 txn->mt_flags |= MDB_TXN_ERROR;
5282 return MDB_PAGE_NOTFOUND;
5292 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
5293 * The cursor is at the root page, set up the rest of it.
5296 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
5298 MDB_page *mp = mc->mc_pg[mc->mc_top];
5302 while (IS_BRANCH(mp)) {
5306 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
5307 /* Don't assert on branch pages in the FreeDB. We can get here
5308 * while in the process of rebalancing a FreeDB branch page; we must
5309 * let that proceed. ITS#8336
5311 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
5312 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
5314 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
5316 if (flags & MDB_PS_LAST)
5317 i = NUMKEYS(mp) - 1;
5320 node = mdb_node_search(mc, key, &exact);
5322 i = NUMKEYS(mp) - 1;
5324 i = mc->mc_ki[mc->mc_top];
5326 mdb_cassert(mc, i > 0);
5330 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
5333 mdb_cassert(mc, i < NUMKEYS(mp));
5334 node = NODEPTR(mp, i);
5336 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
5339 mc->mc_ki[mc->mc_top] = i;
5340 if ((rc = mdb_cursor_push(mc, mp)))
5343 if (flags & MDB_PS_MODIFY) {
5344 if ((rc = mdb_page_touch(mc)) != 0)
5346 mp = mc->mc_pg[mc->mc_top];
5351 DPRINTF(("internal error, index points to a %02X page!?",
5353 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5354 return MDB_CORRUPTED;
5357 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
5358 key ? DKEY(key) : "null"));
5359 mc->mc_flags |= C_INITIALIZED;
5360 mc->mc_flags &= ~C_EOF;
5365 /** Search for the lowest key under the current branch page.
5366 * This just bypasses a NUMKEYS check in the current page
5367 * before calling mdb_page_search_root(), because the callers
5368 * are all in situations where the current page is known to
5372 mdb_page_search_lowest(MDB_cursor *mc)
5374 MDB_page *mp = mc->mc_pg[mc->mc_top];
5375 MDB_node *node = NODEPTR(mp, 0);
5378 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
5381 mc->mc_ki[mc->mc_top] = 0;
5382 if ((rc = mdb_cursor_push(mc, mp)))
5384 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5387 /** Search for the page a given key should be in.
5388 * Push it and its parent pages on the cursor stack.
5389 * @param[in,out] mc the cursor for this operation.
5390 * @param[in] key the key to search for, or NULL for first/last page.
5391 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5392 * are touched (updated with new page numbers).
5393 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5394 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5395 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5396 * @return 0 on success, non-zero on failure.
5399 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5404 /* Make sure the txn is still viable, then find the root from
5405 * the txn's db table and set it as the root of the cursor's stack.
5407 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
5408 DPUTS("transaction may not be used now");
5411 /* Make sure we're using an up-to-date root */
5412 if (*mc->mc_dbflag & DB_STALE) {
5414 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5416 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5417 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5424 MDB_node *leaf = mdb_node_search(&mc2,
5425 &mc->mc_dbx->md_name, &exact);
5427 return MDB_NOTFOUND;
5428 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
5429 return MDB_INCOMPATIBLE; /* not a named DB */
5430 rc = mdb_node_read(&mc2, leaf, &data);
5433 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5435 /* The txn may not know this DBI, or another process may
5436 * have dropped and recreated the DB with other flags.
5438 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5439 return MDB_INCOMPATIBLE;
5440 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5442 *mc->mc_dbflag &= ~DB_STALE;
5444 root = mc->mc_db->md_root;
5446 if (root == P_INVALID) { /* Tree is empty. */
5447 DPUTS("tree is empty");
5448 return MDB_NOTFOUND;
5452 mdb_cassert(mc, root > 1);
5453 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5454 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
5460 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5461 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5463 if (flags & MDB_PS_MODIFY) {
5464 if ((rc = mdb_page_touch(mc)))
5468 if (flags & MDB_PS_ROOTONLY)
5471 return mdb_page_search_root(mc, key, flags);
5475 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5477 MDB_txn *txn = mc->mc_txn;
5478 pgno_t pg = mp->mp_pgno;
5479 unsigned x = 0, ovpages = mp->mp_pages;
5480 MDB_env *env = txn->mt_env;
5481 MDB_IDL sl = txn->mt_spill_pgs;
5482 MDB_ID pn = pg << 1;
5485 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5486 /* If the page is dirty or on the spill list we just acquired it,
5487 * so we should give it back to our current free list, if any.
5488 * Otherwise put it onto the list of pages we freed in this txn.
5490 * Won't create me_pghead: me_pglast must be inited along with it.
5491 * Unsupported in nested txns: They would need to hide the page
5492 * range in ancestor txns' dirty and spilled lists.
5494 if (env->me_pghead &&
5496 ((mp->mp_flags & P_DIRTY) ||
5497 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5501 MDB_ID2 *dl, ix, iy;
5502 rc = mdb_midl_need(&env->me_pghead, ovpages);
5505 if (!(mp->mp_flags & P_DIRTY)) {
5506 /* This page is no longer spilled */
5513 /* Remove from dirty list */
5514 dl = txn->mt_u.dirty_list;
5516 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5522 mdb_cassert(mc, x > 1);
5524 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5525 txn->mt_flags |= MDB_TXN_ERROR;
5526 return MDB_CORRUPTED;
5529 txn->mt_dirty_room++;
5530 if (!(env->me_flags & MDB_WRITEMAP))
5531 mdb_dpage_free(env, mp);
5533 /* Insert in me_pghead */
5534 mop = env->me_pghead;
5535 j = mop[0] + ovpages;
5536 for (i = mop[0]; i && mop[i] < pg; i--)
5542 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5546 mc->mc_db->md_overflow_pages -= ovpages;
5550 /** Return the data associated with a given node.
5551 * @param[in] mc The cursor for this operation.
5552 * @param[in] leaf The node being read.
5553 * @param[out] data Updated to point to the node's data.
5554 * @return 0 on success, non-zero on failure.
5557 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
5559 MDB_page *omp; /* overflow page */
5563 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5564 data->mv_size = NODEDSZ(leaf);
5565 data->mv_data = NODEDATA(leaf);
5569 /* Read overflow data.
5571 data->mv_size = NODEDSZ(leaf);
5572 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5573 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
5574 DPRINTF(("read overflow page %"Z"u failed", pgno));
5577 data->mv_data = METADATA(omp);
5583 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5584 MDB_val *key, MDB_val *data)
5591 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5593 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
5596 if (txn->mt_flags & MDB_TXN_BLOCKED)
5599 mdb_cursor_init(&mc, txn, dbi, &mx);
5600 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5603 /** Find a sibling for a page.
5604 * Replaces the page at the top of the cursor's stack with the
5605 * specified sibling, if one exists.
5606 * @param[in] mc The cursor for this operation.
5607 * @param[in] move_right Non-zero if the right sibling is requested,
5608 * otherwise the left sibling.
5609 * @return 0 on success, non-zero on failure.
5612 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5618 if (mc->mc_snum < 2) {
5619 return MDB_NOTFOUND; /* root has no siblings */
5623 DPRINTF(("parent page is page %"Z"u, index %u",
5624 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5626 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5627 : (mc->mc_ki[mc->mc_top] == 0)) {
5628 DPRINTF(("no more keys left, moving to %s sibling",
5629 move_right ? "right" : "left"));
5630 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5631 /* undo cursor_pop before returning */
5638 mc->mc_ki[mc->mc_top]++;
5640 mc->mc_ki[mc->mc_top]--;
5641 DPRINTF(("just moving to %s index key %u",
5642 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5644 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5646 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5647 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
5648 /* mc will be inconsistent if caller does mc_snum++ as above */
5649 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5653 mdb_cursor_push(mc, mp);
5655 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5660 /** Move the cursor to the next data item. */
5662 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5668 if ((mc->mc_flags & C_EOF) ||
5669 ((mc->mc_flags & C_DEL) && op == MDB_NEXT_DUP)) {
5670 return MDB_NOTFOUND;
5672 if (!(mc->mc_flags & C_INITIALIZED))
5673 return mdb_cursor_first(mc, key, data);
5675 mp = mc->mc_pg[mc->mc_top];
5677 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5678 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5679 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5680 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5681 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5682 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5683 if (rc == MDB_SUCCESS)
5684 MDB_GET_KEY(leaf, key);
5689 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5690 if (op == MDB_NEXT_DUP)
5691 return MDB_NOTFOUND;
5695 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5696 mdb_dbg_pgno(mp), (void *) mc));
5697 if (mc->mc_flags & C_DEL) {
5698 mc->mc_flags ^= C_DEL;
5702 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5703 DPUTS("=====> move to next sibling page");
5704 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5705 mc->mc_flags |= C_EOF;
5708 mp = mc->mc_pg[mc->mc_top];
5709 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5711 mc->mc_ki[mc->mc_top]++;
5714 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5715 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5718 key->mv_size = mc->mc_db->md_pad;
5719 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5723 mdb_cassert(mc, IS_LEAF(mp));
5724 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5726 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5727 mdb_xcursor_init1(mc, leaf);
5730 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
5733 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5734 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5735 if (rc != MDB_SUCCESS)
5740 MDB_GET_KEY(leaf, key);
5744 /** Move the cursor to the previous data item. */
5746 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5752 if (!(mc->mc_flags & C_INITIALIZED)) {
5753 rc = mdb_cursor_last(mc, key, data);
5756 mc->mc_ki[mc->mc_top]++;
5759 mp = mc->mc_pg[mc->mc_top];
5761 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5762 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5763 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5764 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5765 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5766 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5767 if (rc == MDB_SUCCESS) {
5768 MDB_GET_KEY(leaf, key);
5769 mc->mc_flags &= ~C_EOF;
5775 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5776 if (op == MDB_PREV_DUP)
5777 return MDB_NOTFOUND;
5781 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5782 mdb_dbg_pgno(mp), (void *) mc));
5784 mc->mc_flags &= ~(C_EOF|C_DEL);
5786 if (mc->mc_ki[mc->mc_top] == 0) {
5787 DPUTS("=====> move to prev sibling page");
5788 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5791 mp = mc->mc_pg[mc->mc_top];
5792 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5793 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5795 mc->mc_ki[mc->mc_top]--;
5797 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5798 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5801 key->mv_size = mc->mc_db->md_pad;
5802 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5806 mdb_cassert(mc, IS_LEAF(mp));
5807 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5809 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5810 mdb_xcursor_init1(mc, leaf);
5813 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
5816 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5817 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5818 if (rc != MDB_SUCCESS)
5823 MDB_GET_KEY(leaf, key);
5827 /** Set the cursor on a specific data item. */
5829 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5830 MDB_cursor_op op, int *exactp)
5834 MDB_node *leaf = NULL;
5837 if (key->mv_size == 0)
5838 return MDB_BAD_VALSIZE;
5841 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5843 /* See if we're already on the right page */
5844 if (mc->mc_flags & C_INITIALIZED) {
5847 mp = mc->mc_pg[mc->mc_top];
5849 mc->mc_ki[mc->mc_top] = 0;
5850 return MDB_NOTFOUND;
5852 if (mp->mp_flags & P_LEAF2) {
5853 nodekey.mv_size = mc->mc_db->md_pad;
5854 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5856 leaf = NODEPTR(mp, 0);
5857 MDB_GET_KEY2(leaf, nodekey);
5859 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5861 /* Probably happens rarely, but first node on the page
5862 * was the one we wanted.
5864 mc->mc_ki[mc->mc_top] = 0;
5871 unsigned int nkeys = NUMKEYS(mp);
5873 if (mp->mp_flags & P_LEAF2) {
5874 nodekey.mv_data = LEAF2KEY(mp,
5875 nkeys-1, nodekey.mv_size);
5877 leaf = NODEPTR(mp, nkeys-1);
5878 MDB_GET_KEY2(leaf, nodekey);
5880 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5882 /* last node was the one we wanted */
5883 mc->mc_ki[mc->mc_top] = nkeys-1;
5889 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5890 /* This is definitely the right page, skip search_page */
5891 if (mp->mp_flags & P_LEAF2) {
5892 nodekey.mv_data = LEAF2KEY(mp,
5893 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5895 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5896 MDB_GET_KEY2(leaf, nodekey);
5898 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5900 /* current node was the one we wanted */
5910 /* If any parents have right-sibs, search.
5911 * Otherwise, there's nothing further.
5913 for (i=0; i<mc->mc_top; i++)
5915 NUMKEYS(mc->mc_pg[i])-1)
5917 if (i == mc->mc_top) {
5918 /* There are no other pages */
5919 mc->mc_ki[mc->mc_top] = nkeys;
5920 return MDB_NOTFOUND;
5924 /* There are no other pages */
5925 mc->mc_ki[mc->mc_top] = 0;
5926 if (op == MDB_SET_RANGE && !exactp) {
5930 return MDB_NOTFOUND;
5936 rc = mdb_page_search(mc, key, 0);
5937 if (rc != MDB_SUCCESS)
5940 mp = mc->mc_pg[mc->mc_top];
5941 mdb_cassert(mc, IS_LEAF(mp));
5944 leaf = mdb_node_search(mc, key, exactp);
5945 if (exactp != NULL && !*exactp) {
5946 /* MDB_SET specified and not an exact match. */
5947 return MDB_NOTFOUND;
5951 DPUTS("===> inexact leaf not found, goto sibling");
5952 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5953 mc->mc_flags |= C_EOF;
5954 return rc; /* no entries matched */
5956 mp = mc->mc_pg[mc->mc_top];
5957 mdb_cassert(mc, IS_LEAF(mp));
5958 leaf = NODEPTR(mp, 0);
5962 mc->mc_flags |= C_INITIALIZED;
5963 mc->mc_flags &= ~C_EOF;
5966 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5967 key->mv_size = mc->mc_db->md_pad;
5968 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5973 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5974 mdb_xcursor_init1(mc, leaf);
5977 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5978 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5979 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5982 if (op == MDB_GET_BOTH) {
5988 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5989 if (rc != MDB_SUCCESS)
5992 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5995 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
5997 dcmp = mc->mc_dbx->md_dcmp;
5998 #if UINT_MAX < SIZE_MAX
5999 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6000 dcmp = mdb_cmp_clong;
6002 rc = dcmp(data, &olddata);
6004 if (op == MDB_GET_BOTH || rc > 0)
6005 return MDB_NOTFOUND;
6012 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6013 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6018 /* The key already matches in all other cases */
6019 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6020 MDB_GET_KEY(leaf, key);
6021 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6026 /** Move the cursor to the first item in the database. */
6028 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6034 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6036 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6037 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6038 if (rc != MDB_SUCCESS)
6041 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6043 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6044 mc->mc_flags |= C_INITIALIZED;
6045 mc->mc_flags &= ~C_EOF;
6047 mc->mc_ki[mc->mc_top] = 0;
6049 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6050 key->mv_size = mc->mc_db->md_pad;
6051 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
6056 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6057 mdb_xcursor_init1(mc, leaf);
6058 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6062 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6066 MDB_GET_KEY(leaf, key);
6070 /** Move the cursor to the last item in the database. */
6072 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6078 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6080 if (!(mc->mc_flags & C_EOF)) {
6082 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6083 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
6084 if (rc != MDB_SUCCESS)
6087 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6090 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
6091 mc->mc_flags |= C_INITIALIZED|C_EOF;
6092 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6094 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6095 key->mv_size = mc->mc_db->md_pad;
6096 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
6101 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6102 mdb_xcursor_init1(mc, leaf);
6103 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6107 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6112 MDB_GET_KEY(leaf, key);
6117 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6122 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
6127 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
6131 case MDB_GET_CURRENT:
6132 if (!(mc->mc_flags & C_INITIALIZED)) {
6135 MDB_page *mp = mc->mc_pg[mc->mc_top];
6136 int nkeys = NUMKEYS(mp);
6137 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
6138 mc->mc_ki[mc->mc_top] = nkeys;
6144 key->mv_size = mc->mc_db->md_pad;
6145 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6147 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6148 MDB_GET_KEY(leaf, key);
6150 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6151 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
6153 rc = mdb_node_read(mc, leaf, data);
6160 case MDB_GET_BOTH_RANGE:
6165 if (mc->mc_xcursor == NULL) {
6166 rc = MDB_INCOMPATIBLE;
6176 rc = mdb_cursor_set(mc, key, data, op,
6177 op == MDB_SET_RANGE ? NULL : &exact);
6180 case MDB_GET_MULTIPLE:
6181 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6185 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6186 rc = MDB_INCOMPATIBLE;
6190 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6191 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6194 case MDB_NEXT_MULTIPLE:
6199 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6200 rc = MDB_INCOMPATIBLE;
6203 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6204 if (rc == MDB_SUCCESS) {
6205 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6208 mx = &mc->mc_xcursor->mx_cursor;
6209 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
6211 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
6212 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
6218 case MDB_PREV_MULTIPLE:
6223 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6224 rc = MDB_INCOMPATIBLE;
6227 if (!(mc->mc_flags & C_INITIALIZED))
6228 rc = mdb_cursor_last(mc, key, data);
6231 if (rc == MDB_SUCCESS) {
6232 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
6233 if (mx->mc_flags & C_INITIALIZED) {
6234 rc = mdb_cursor_sibling(mx, 0);
6235 if (rc == MDB_SUCCESS)
6244 case MDB_NEXT_NODUP:
6245 rc = mdb_cursor_next(mc, key, data, op);
6249 case MDB_PREV_NODUP:
6250 rc = mdb_cursor_prev(mc, key, data, op);
6253 rc = mdb_cursor_first(mc, key, data);
6256 mfunc = mdb_cursor_first;
6258 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6262 if (mc->mc_xcursor == NULL) {
6263 rc = MDB_INCOMPATIBLE;
6267 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6268 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6269 MDB_GET_KEY(leaf, key);
6270 rc = mdb_node_read(mc, leaf, data);
6274 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6278 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
6281 rc = mdb_cursor_last(mc, key, data);
6284 mfunc = mdb_cursor_last;
6287 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
6292 if (mc->mc_flags & C_DEL)
6293 mc->mc_flags ^= C_DEL;
6298 /** Touch all the pages in the cursor stack. Set mc_top.
6299 * Makes sure all the pages are writable, before attempting a write operation.
6300 * @param[in] mc The cursor to operate on.
6303 mdb_cursor_touch(MDB_cursor *mc)
6305 int rc = MDB_SUCCESS;
6307 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & (DB_DIRTY|DB_DUPDATA))) {
6308 /* Touch DB record of named DB */
6311 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6313 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
6314 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
6317 *mc->mc_dbflag |= DB_DIRTY;
6322 rc = mdb_page_touch(mc);
6323 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
6324 mc->mc_top = mc->mc_snum-1;
6329 /** Do not spill pages to disk if txn is getting full, may fail instead */
6330 #define MDB_NOSPILL 0x8000
6333 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6337 MDB_node *leaf = NULL;
6338 MDB_page *fp, *mp, *sub_root = NULL;
6340 MDB_val xdata, *rdata, dkey, olddata;
6342 int do_sub = 0, insert_key, insert_data;
6343 unsigned int mcount = 0, dcount = 0, nospill;
6346 unsigned int nflags;
6349 if (mc == NULL || key == NULL)
6352 env = mc->mc_txn->mt_env;
6354 /* Check this first so counter will always be zero on any
6357 if (flags & MDB_MULTIPLE) {
6358 dcount = data[1].mv_size;
6359 data[1].mv_size = 0;
6360 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
6361 return MDB_INCOMPATIBLE;
6364 nospill = flags & MDB_NOSPILL;
6365 flags &= ~MDB_NOSPILL;
6367 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6368 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6370 if (key->mv_size-1 >= ENV_MAXKEY(env))
6371 return MDB_BAD_VALSIZE;
6373 #if SIZE_MAX > MAXDATASIZE
6374 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
6375 return MDB_BAD_VALSIZE;
6377 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
6378 return MDB_BAD_VALSIZE;
6381 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
6382 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
6386 if (flags == MDB_CURRENT) {
6387 if (!(mc->mc_flags & C_INITIALIZED))
6390 } else if (mc->mc_db->md_root == P_INVALID) {
6391 /* new database, cursor has nothing to point to */
6394 mc->mc_flags &= ~C_INITIALIZED;
6399 if (flags & MDB_APPEND) {
6401 rc = mdb_cursor_last(mc, &k2, &d2);
6403 rc = mc->mc_dbx->md_cmp(key, &k2);
6406 mc->mc_ki[mc->mc_top]++;
6408 /* new key is <= last key */
6413 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6415 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6416 DPRINTF(("duplicate key [%s]", DKEY(key)));
6418 return MDB_KEYEXIST;
6420 if (rc && rc != MDB_NOTFOUND)
6424 if (mc->mc_flags & C_DEL)
6425 mc->mc_flags ^= C_DEL;
6427 /* Cursor is positioned, check for room in the dirty list */
6429 if (flags & MDB_MULTIPLE) {
6431 xdata.mv_size = data->mv_size * dcount;
6435 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6439 if (rc == MDB_NO_ROOT) {
6441 /* new database, write a root leaf page */
6442 DPUTS("allocating new root leaf page");
6443 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6446 mdb_cursor_push(mc, np);
6447 mc->mc_db->md_root = np->mp_pgno;
6448 mc->mc_db->md_depth++;
6449 *mc->mc_dbflag |= DB_DIRTY;
6450 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6452 np->mp_flags |= P_LEAF2;
6453 mc->mc_flags |= C_INITIALIZED;
6455 /* make sure all cursor pages are writable */
6456 rc2 = mdb_cursor_touch(mc);
6461 insert_key = insert_data = rc;
6463 /* The key does not exist */
6464 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6465 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6466 LEAFSIZE(key, data) > env->me_nodemax)
6468 /* Too big for a node, insert in sub-DB. Set up an empty
6469 * "old sub-page" for prep_subDB to expand to a full page.
6471 fp_flags = P_LEAF|P_DIRTY;
6473 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6474 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6475 olddata.mv_size = PAGEHDRSZ;
6479 /* there's only a key anyway, so this is a no-op */
6480 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6482 unsigned int ksize = mc->mc_db->md_pad;
6483 if (key->mv_size != ksize)
6484 return MDB_BAD_VALSIZE;
6485 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6486 memcpy(ptr, key->mv_data, ksize);
6488 /* if overwriting slot 0 of leaf, need to
6489 * update branch key if there is a parent page
6491 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6492 unsigned short dtop = 1;
6494 /* slot 0 is always an empty key, find real slot */
6495 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6499 if (mc->mc_ki[mc->mc_top])
6500 rc2 = mdb_update_key(mc, key);
6511 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6512 olddata.mv_size = NODEDSZ(leaf);
6513 olddata.mv_data = NODEDATA(leaf);
6516 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6517 /* Prepare (sub-)page/sub-DB to accept the new item,
6518 * if needed. fp: old sub-page or a header faking
6519 * it. mp: new (sub-)page. offset: growth in page
6520 * size. xdata: node data with new page or DB.
6522 unsigned i, offset = 0;
6523 mp = fp = xdata.mv_data = env->me_pbuf;
6524 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6526 /* Was a single item before, must convert now */
6527 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6529 /* Just overwrite the current item */
6530 if (flags == MDB_CURRENT)
6532 dcmp = mc->mc_dbx->md_dcmp;
6533 #if UINT_MAX < SIZE_MAX
6534 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6535 dcmp = mdb_cmp_clong;
6537 /* does data match? */
6538 if (!dcmp(data, &olddata)) {
6539 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
6540 return MDB_KEYEXIST;
6545 /* Back up original data item */
6546 dkey.mv_size = olddata.mv_size;
6547 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6549 /* Make sub-page header for the dup items, with dummy body */
6550 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6551 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6552 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6553 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6554 fp->mp_flags |= P_LEAF2;
6555 fp->mp_pad = data->mv_size;
6556 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6558 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6559 (dkey.mv_size & 1) + (data->mv_size & 1);
6561 fp->mp_upper = xdata.mv_size - PAGEBASE;
6562 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6563 } else if (leaf->mn_flags & F_SUBDATA) {
6564 /* Data is on sub-DB, just store it */
6565 flags |= F_DUPDATA|F_SUBDATA;
6568 /* Data is on sub-page */
6569 fp = olddata.mv_data;
6572 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6573 offset = EVEN(NODESIZE + sizeof(indx_t) +
6577 offset = fp->mp_pad;
6578 if (SIZELEFT(fp) < offset) {
6579 offset *= 4; /* space for 4 more */
6582 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6584 fp->mp_flags |= P_DIRTY;
6585 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6586 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6590 xdata.mv_size = olddata.mv_size + offset;
6593 fp_flags = fp->mp_flags;
6594 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6595 /* Too big for a sub-page, convert to sub-DB */
6596 fp_flags &= ~P_SUBP;
6598 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6599 fp_flags |= P_LEAF2;
6600 dummy.md_pad = fp->mp_pad;
6601 dummy.md_flags = MDB_DUPFIXED;
6602 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6603 dummy.md_flags |= MDB_INTEGERKEY;
6609 dummy.md_branch_pages = 0;
6610 dummy.md_leaf_pages = 1;
6611 dummy.md_overflow_pages = 0;
6612 dummy.md_entries = NUMKEYS(fp);
6613 xdata.mv_size = sizeof(MDB_db);
6614 xdata.mv_data = &dummy;
6615 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6617 offset = env->me_psize - olddata.mv_size;
6618 flags |= F_DUPDATA|F_SUBDATA;
6619 dummy.md_root = mp->mp_pgno;
6623 mp->mp_flags = fp_flags | P_DIRTY;
6624 mp->mp_pad = fp->mp_pad;
6625 mp->mp_lower = fp->mp_lower;
6626 mp->mp_upper = fp->mp_upper + offset;
6627 if (fp_flags & P_LEAF2) {
6628 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6630 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6631 olddata.mv_size - fp->mp_upper - PAGEBASE);
6632 for (i=0; i<NUMKEYS(fp); i++)
6633 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6641 mdb_node_del(mc, 0);
6645 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
6646 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
6647 return MDB_INCOMPATIBLE;
6648 /* overflow page overwrites need special handling */
6649 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6652 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6654 memcpy(&pg, olddata.mv_data, sizeof(pg));
6655 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
6657 ovpages = omp->mp_pages;
6659 /* Is the ov page large enough? */
6660 if (ovpages >= dpages) {
6661 if (!(omp->mp_flags & P_DIRTY) &&
6662 (level || (env->me_flags & MDB_WRITEMAP)))
6664 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6667 level = 0; /* dirty in this txn or clean */
6670 if (omp->mp_flags & P_DIRTY) {
6671 /* yes, overwrite it. Note in this case we don't
6672 * bother to try shrinking the page if the new data
6673 * is smaller than the overflow threshold.
6676 /* It is writable only in a parent txn */
6677 size_t sz = (size_t) env->me_psize * ovpages, off;
6678 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6684 /* Note - this page is already counted in parent's dirty_room */
6685 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6686 mdb_cassert(mc, rc2 == 0);
6687 /* Currently we make the page look as with put() in the
6688 * parent txn, in case the user peeks at MDB_RESERVEd
6689 * or unused parts. Some users treat ovpages specially.
6691 if (!(flags & MDB_RESERVE)) {
6692 /* Skip the part where LMDB will put *data.
6693 * Copy end of page, adjusting alignment so
6694 * compiler may copy words instead of bytes.
6696 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6697 memcpy((size_t *)((char *)np + off),
6698 (size_t *)((char *)omp + off), sz - off);
6701 memcpy(np, omp, sz); /* Copy beginning of page */
6704 SETDSZ(leaf, data->mv_size);
6705 if (F_ISSET(flags, MDB_RESERVE))
6706 data->mv_data = METADATA(omp);
6708 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6712 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6714 } else if (data->mv_size == olddata.mv_size) {
6715 /* same size, just replace it. Note that we could
6716 * also reuse this node if the new data is smaller,
6717 * but instead we opt to shrink the node in that case.
6719 if (F_ISSET(flags, MDB_RESERVE))
6720 data->mv_data = olddata.mv_data;
6721 else if (!(mc->mc_flags & C_SUB))
6722 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6724 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6729 mdb_node_del(mc, 0);
6735 nflags = flags & NODE_ADD_FLAGS;
6736 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6737 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6738 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6739 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6741 nflags |= MDB_SPLIT_REPLACE;
6742 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6744 /* There is room already in this leaf page. */
6745 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6747 /* Adjust other cursors pointing to mp */
6748 MDB_cursor *m2, *m3;
6749 MDB_dbi dbi = mc->mc_dbi;
6750 unsigned i = mc->mc_top;
6751 MDB_page *mp = mc->mc_pg[i];
6753 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6754 if (mc->mc_flags & C_SUB)
6755 m3 = &m2->mc_xcursor->mx_cursor;
6758 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
6759 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
6762 if (XCURSOR_INITED(m3))
6763 XCURSOR_REFRESH(m3, mp, m3->mc_ki[i]);
6768 if (rc == MDB_SUCCESS) {
6769 /* Now store the actual data in the child DB. Note that we're
6770 * storing the user data in the keys field, so there are strict
6771 * size limits on dupdata. The actual data fields of the child
6772 * DB are all zero size.
6775 int xflags, new_dupdata;
6780 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6781 if (flags & MDB_CURRENT) {
6782 xflags = MDB_CURRENT|MDB_NOSPILL;
6784 mdb_xcursor_init1(mc, leaf);
6785 xflags = (flags & MDB_NODUPDATA) ?
6786 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6789 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
6790 new_dupdata = (int)dkey.mv_size;
6791 /* converted, write the original data first */
6793 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6796 /* we've done our job */
6799 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
6800 /* Adjust other cursors pointing to mp */
6802 MDB_xcursor *mx = mc->mc_xcursor;
6803 unsigned i = mc->mc_top;
6804 MDB_page *mp = mc->mc_pg[i];
6805 int nkeys = NUMKEYS(mp);
6807 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6808 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6809 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6810 if (m2->mc_pg[i] == mp) {
6811 if (m2->mc_ki[i] == mc->mc_ki[i]) {
6812 mdb_xcursor_init2(m2, mx, new_dupdata);
6813 } else if (!insert_key && m2->mc_ki[i] < nkeys) {
6814 XCURSOR_REFRESH(m2, mp, m2->mc_ki[i]);
6819 ecount = mc->mc_xcursor->mx_db.md_entries;
6820 if (flags & MDB_APPENDDUP)
6821 xflags |= MDB_APPEND;
6822 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6823 if (flags & F_SUBDATA) {
6824 void *db = NODEDATA(leaf);
6825 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6827 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6829 /* Increment count unless we just replaced an existing item. */
6831 mc->mc_db->md_entries++;
6833 /* Invalidate txn if we created an empty sub-DB */
6836 /* If we succeeded and the key didn't exist before,
6837 * make sure the cursor is marked valid.
6839 mc->mc_flags |= C_INITIALIZED;
6841 if (flags & MDB_MULTIPLE) {
6844 /* let caller know how many succeeded, if any */
6845 data[1].mv_size = mcount;
6846 if (mcount < dcount) {
6847 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6848 insert_key = insert_data = 0;
6855 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6858 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6863 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6869 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6870 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6872 if (!(mc->mc_flags & C_INITIALIZED))
6875 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6876 return MDB_NOTFOUND;
6878 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6881 rc = mdb_cursor_touch(mc);
6885 mp = mc->mc_pg[mc->mc_top];
6888 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6890 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6891 if (flags & MDB_NODUPDATA) {
6892 /* mdb_cursor_del0() will subtract the final entry */
6893 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6894 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
6896 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6897 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6899 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6902 /* If sub-DB still has entries, we're done */
6903 if (mc->mc_xcursor->mx_db.md_entries) {
6904 if (leaf->mn_flags & F_SUBDATA) {
6905 /* update subDB info */
6906 void *db = NODEDATA(leaf);
6907 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6910 /* shrink fake page */
6911 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6912 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6913 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6914 /* fix other sub-DB cursors pointed at fake pages on this page */
6915 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6916 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6917 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6918 if (m2->mc_pg[mc->mc_top] == mp) {
6919 MDB_node *n2 = leaf;
6920 if (m2->mc_ki[mc->mc_top] != mc->mc_ki[mc->mc_top]) {
6921 n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
6922 if (n2->mn_flags & F_SUBDATA) continue;
6924 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
6928 mc->mc_db->md_entries--;
6931 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
6933 /* otherwise fall thru and delete the sub-DB */
6936 if (leaf->mn_flags & F_SUBDATA) {
6937 /* add all the child DB's pages to the free list */
6938 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6943 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
6944 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
6945 rc = MDB_INCOMPATIBLE;
6949 /* add overflow pages to free list */
6950 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6954 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6955 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
6956 (rc = mdb_ovpage_free(mc, omp)))
6961 return mdb_cursor_del0(mc);
6964 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6968 /** Allocate and initialize new pages for a database.
6969 * @param[in] mc a cursor on the database being added to.
6970 * @param[in] flags flags defining what type of page is being allocated.
6971 * @param[in] num the number of pages to allocate. This is usually 1,
6972 * unless allocating overflow pages for a large record.
6973 * @param[out] mp Address of a page, or NULL on failure.
6974 * @return 0 on success, non-zero on failure.
6977 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6982 if ((rc = mdb_page_alloc(mc, num, &np)))
6984 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6985 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6986 np->mp_flags = flags | P_DIRTY;
6987 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
6988 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
6991 mc->mc_db->md_branch_pages++;
6992 else if (IS_LEAF(np))
6993 mc->mc_db->md_leaf_pages++;
6994 else if (IS_OVERFLOW(np)) {
6995 mc->mc_db->md_overflow_pages += num;
7003 /** Calculate the size of a leaf node.
7004 * The size depends on the environment's page size; if a data item
7005 * is too large it will be put onto an overflow page and the node
7006 * size will only include the key and not the data. Sizes are always
7007 * rounded up to an even number of bytes, to guarantee 2-byte alignment
7008 * of the #MDB_node headers.
7009 * @param[in] env The environment handle.
7010 * @param[in] key The key for the node.
7011 * @param[in] data The data for the node.
7012 * @return The number of bytes needed to store the node.
7015 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
7019 sz = LEAFSIZE(key, data);
7020 if (sz > env->me_nodemax) {
7021 /* put on overflow page */
7022 sz -= data->mv_size - sizeof(pgno_t);
7025 return EVEN(sz + sizeof(indx_t));
7028 /** Calculate the size of a branch node.
7029 * The size should depend on the environment's page size but since
7030 * we currently don't support spilling large keys onto overflow
7031 * pages, it's simply the size of the #MDB_node header plus the
7032 * size of the key. Sizes are always rounded up to an even number
7033 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7034 * @param[in] env The environment handle.
7035 * @param[in] key The key for the node.
7036 * @return The number of bytes needed to store the node.
7039 mdb_branch_size(MDB_env *env, MDB_val *key)
7044 if (sz > env->me_nodemax) {
7045 /* put on overflow page */
7046 /* not implemented */
7047 /* sz -= key->size - sizeof(pgno_t); */
7050 return sz + sizeof(indx_t);
7053 /** Add a node to the page pointed to by the cursor.
7054 * @param[in] mc The cursor for this operation.
7055 * @param[in] indx The index on the page where the new node should be added.
7056 * @param[in] key The key for the new node.
7057 * @param[in] data The data for the new node, if any.
7058 * @param[in] pgno The page number, if adding a branch node.
7059 * @param[in] flags Flags for the node.
7060 * @return 0 on success, non-zero on failure. Possible errors are:
7062 * <li>ENOMEM - failed to allocate overflow pages for the node.
7063 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
7064 * should never happen since all callers already calculate the
7065 * page's free space before calling this function.
7069 mdb_node_add(MDB_cursor *mc, indx_t indx,
7070 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
7073 size_t node_size = NODESIZE;
7077 MDB_page *mp = mc->mc_pg[mc->mc_top];
7078 MDB_page *ofp = NULL; /* overflow page */
7082 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
7084 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
7085 IS_LEAF(mp) ? "leaf" : "branch",
7086 IS_SUBP(mp) ? "sub-" : "",
7087 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
7088 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
7091 /* Move higher keys up one slot. */
7092 int ksize = mc->mc_db->md_pad, dif;
7093 char *ptr = LEAF2KEY(mp, indx, ksize);
7094 dif = NUMKEYS(mp) - indx;
7096 memmove(ptr+ksize, ptr, dif*ksize);
7097 /* insert new key */
7098 memcpy(ptr, key->mv_data, ksize);
7100 /* Just using these for counting */
7101 mp->mp_lower += sizeof(indx_t);
7102 mp->mp_upper -= ksize - sizeof(indx_t);
7106 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
7108 node_size += key->mv_size;
7110 mdb_cassert(mc, key && data);
7111 if (F_ISSET(flags, F_BIGDATA)) {
7112 /* Data already on overflow page. */
7113 node_size += sizeof(pgno_t);
7114 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
7115 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
7117 /* Put data on overflow page. */
7118 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
7119 data->mv_size, node_size+data->mv_size));
7120 node_size = EVEN(node_size + sizeof(pgno_t));
7121 if ((ssize_t)node_size > room)
7123 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
7125 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
7129 node_size += data->mv_size;
7132 node_size = EVEN(node_size);
7133 if ((ssize_t)node_size > room)
7137 /* Move higher pointers up one slot. */
7138 for (i = NUMKEYS(mp); i > indx; i--)
7139 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
7141 /* Adjust free space offsets. */
7142 ofs = mp->mp_upper - node_size;
7143 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
7144 mp->mp_ptrs[indx] = ofs;
7146 mp->mp_lower += sizeof(indx_t);
7148 /* Write the node data. */
7149 node = NODEPTR(mp, indx);
7150 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
7151 node->mn_flags = flags;
7153 SETDSZ(node,data->mv_size);
7158 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7161 ndata = NODEDATA(node);
7163 if (F_ISSET(flags, F_BIGDATA))
7164 memcpy(ndata, data->mv_data, sizeof(pgno_t));
7165 else if (F_ISSET(flags, MDB_RESERVE))
7166 data->mv_data = ndata;
7168 memcpy(ndata, data->mv_data, data->mv_size);
7170 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
7171 ndata = METADATA(ofp);
7172 if (F_ISSET(flags, MDB_RESERVE))
7173 data->mv_data = ndata;
7175 memcpy(ndata, data->mv_data, data->mv_size);
7182 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
7183 mdb_dbg_pgno(mp), NUMKEYS(mp)));
7184 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
7185 DPRINTF(("node size = %"Z"u", node_size));
7186 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7187 return MDB_PAGE_FULL;
7190 /** Delete the specified node from a page.
7191 * @param[in] mc Cursor pointing to the node to delete.
7192 * @param[in] ksize The size of a node. Only used if the page is
7193 * part of a #MDB_DUPFIXED database.
7196 mdb_node_del(MDB_cursor *mc, int ksize)
7198 MDB_page *mp = mc->mc_pg[mc->mc_top];
7199 indx_t indx = mc->mc_ki[mc->mc_top];
7201 indx_t i, j, numkeys, ptr;
7205 DPRINTF(("delete node %u on %s page %"Z"u", indx,
7206 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
7207 numkeys = NUMKEYS(mp);
7208 mdb_cassert(mc, indx < numkeys);
7211 int x = numkeys - 1 - indx;
7212 base = LEAF2KEY(mp, indx, ksize);
7214 memmove(base, base + ksize, x * ksize);
7215 mp->mp_lower -= sizeof(indx_t);
7216 mp->mp_upper += ksize - sizeof(indx_t);
7220 node = NODEPTR(mp, indx);
7221 sz = NODESIZE + node->mn_ksize;
7223 if (F_ISSET(node->mn_flags, F_BIGDATA))
7224 sz += sizeof(pgno_t);
7226 sz += NODEDSZ(node);
7230 ptr = mp->mp_ptrs[indx];
7231 for (i = j = 0; i < numkeys; i++) {
7233 mp->mp_ptrs[j] = mp->mp_ptrs[i];
7234 if (mp->mp_ptrs[i] < ptr)
7235 mp->mp_ptrs[j] += sz;
7240 base = (char *)mp + mp->mp_upper + PAGEBASE;
7241 memmove(base + sz, base, ptr - mp->mp_upper);
7243 mp->mp_lower -= sizeof(indx_t);
7247 /** Compact the main page after deleting a node on a subpage.
7248 * @param[in] mp The main page to operate on.
7249 * @param[in] indx The index of the subpage on the main page.
7252 mdb_node_shrink(MDB_page *mp, indx_t indx)
7257 indx_t delta, nsize, len, ptr;
7260 node = NODEPTR(mp, indx);
7261 sp = (MDB_page *)NODEDATA(node);
7262 delta = SIZELEFT(sp);
7263 nsize = NODEDSZ(node) - delta;
7265 /* Prepare to shift upward, set len = length(subpage part to shift) */
7269 return; /* do not make the node uneven-sized */
7271 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
7272 for (i = NUMKEYS(sp); --i >= 0; )
7273 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
7276 sp->mp_upper = sp->mp_lower;
7277 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
7278 SETDSZ(node, nsize);
7280 /* Shift <lower nodes...initial part of subpage> upward */
7281 base = (char *)mp + mp->mp_upper + PAGEBASE;
7282 memmove(base + delta, base, (char *)sp + len - base);
7284 ptr = mp->mp_ptrs[indx];
7285 for (i = NUMKEYS(mp); --i >= 0; ) {
7286 if (mp->mp_ptrs[i] <= ptr)
7287 mp->mp_ptrs[i] += delta;
7289 mp->mp_upper += delta;
7292 /** Initial setup of a sorted-dups cursor.
7293 * Sorted duplicates are implemented as a sub-database for the given key.
7294 * The duplicate data items are actually keys of the sub-database.
7295 * Operations on the duplicate data items are performed using a sub-cursor
7296 * initialized when the sub-database is first accessed. This function does
7297 * the preliminary setup of the sub-cursor, filling in the fields that
7298 * depend only on the parent DB.
7299 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7302 mdb_xcursor_init0(MDB_cursor *mc)
7304 MDB_xcursor *mx = mc->mc_xcursor;
7306 mx->mx_cursor.mc_xcursor = NULL;
7307 mx->mx_cursor.mc_txn = mc->mc_txn;
7308 mx->mx_cursor.mc_db = &mx->mx_db;
7309 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
7310 mx->mx_cursor.mc_dbi = mc->mc_dbi;
7311 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
7312 mx->mx_cursor.mc_snum = 0;
7313 mx->mx_cursor.mc_top = 0;
7314 mx->mx_cursor.mc_flags = C_SUB;
7315 mx->mx_dbx.md_name.mv_size = 0;
7316 mx->mx_dbx.md_name.mv_data = NULL;
7317 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
7318 mx->mx_dbx.md_dcmp = NULL;
7319 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
7322 /** Final setup of a sorted-dups cursor.
7323 * Sets up the fields that depend on the data from the main cursor.
7324 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7325 * @param[in] node The data containing the #MDB_db record for the
7326 * sorted-dup database.
7329 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
7331 MDB_xcursor *mx = mc->mc_xcursor;
7333 if (node->mn_flags & F_SUBDATA) {
7334 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
7335 mx->mx_cursor.mc_pg[0] = 0;
7336 mx->mx_cursor.mc_snum = 0;
7337 mx->mx_cursor.mc_top = 0;
7338 mx->mx_cursor.mc_flags = C_SUB;
7340 MDB_page *fp = NODEDATA(node);
7341 mx->mx_db.md_pad = 0;
7342 mx->mx_db.md_flags = 0;
7343 mx->mx_db.md_depth = 1;
7344 mx->mx_db.md_branch_pages = 0;
7345 mx->mx_db.md_leaf_pages = 1;
7346 mx->mx_db.md_overflow_pages = 0;
7347 mx->mx_db.md_entries = NUMKEYS(fp);
7348 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
7349 mx->mx_cursor.mc_snum = 1;
7350 mx->mx_cursor.mc_top = 0;
7351 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
7352 mx->mx_cursor.mc_pg[0] = fp;
7353 mx->mx_cursor.mc_ki[0] = 0;
7354 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7355 mx->mx_db.md_flags = MDB_DUPFIXED;
7356 mx->mx_db.md_pad = fp->mp_pad;
7357 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7358 mx->mx_db.md_flags |= MDB_INTEGERKEY;
7361 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7362 mx->mx_db.md_root));
7363 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
7364 #if UINT_MAX < SIZE_MAX
7365 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
7366 mx->mx_dbx.md_cmp = mdb_cmp_clong;
7371 /** Fixup a sorted-dups cursor due to underlying update.
7372 * Sets up some fields that depend on the data from the main cursor.
7373 * Almost the same as init1, but skips initialization steps if the
7374 * xcursor had already been used.
7375 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
7376 * @param[in] src_mx The xcursor of an up-to-date cursor.
7377 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
7380 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
7382 MDB_xcursor *mx = mc->mc_xcursor;
7385 mx->mx_cursor.mc_snum = 1;
7386 mx->mx_cursor.mc_top = 0;
7387 mx->mx_cursor.mc_flags |= C_INITIALIZED;
7388 mx->mx_cursor.mc_ki[0] = 0;
7389 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
7390 #if UINT_MAX < SIZE_MAX
7391 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
7393 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
7396 mx->mx_db = src_mx->mx_db;
7397 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
7398 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7399 mx->mx_db.md_root));
7402 /** Initialize a cursor for a given transaction and database. */
7404 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
7407 mc->mc_backup = NULL;
7410 mc->mc_db = &txn->mt_dbs[dbi];
7411 mc->mc_dbx = &txn->mt_dbxs[dbi];
7412 mc->mc_dbflag = &txn->mt_dbflags[dbi];
7418 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
7419 mdb_tassert(txn, mx != NULL);
7420 mc->mc_xcursor = mx;
7421 mdb_xcursor_init0(mc);
7423 mc->mc_xcursor = NULL;
7425 if (*mc->mc_dbflag & DB_STALE) {
7426 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
7431 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
7434 size_t size = sizeof(MDB_cursor);
7436 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
7439 if (txn->mt_flags & MDB_TXN_BLOCKED)
7442 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7445 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
7446 size += sizeof(MDB_xcursor);
7448 if ((mc = malloc(size)) != NULL) {
7449 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
7450 if (txn->mt_cursors) {
7451 mc->mc_next = txn->mt_cursors[dbi];
7452 txn->mt_cursors[dbi] = mc;
7453 mc->mc_flags |= C_UNTRACK;
7465 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
7467 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
7470 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
7473 if (txn->mt_flags & MDB_TXN_BLOCKED)
7476 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
7480 /* Return the count of duplicate data items for the current key */
7482 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7486 if (mc == NULL || countp == NULL)
7489 if (mc->mc_xcursor == NULL)
7490 return MDB_INCOMPATIBLE;
7492 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
7495 if (!(mc->mc_flags & C_INITIALIZED))
7498 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
7499 return MDB_NOTFOUND;
7501 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7502 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7505 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7508 *countp = mc->mc_xcursor->mx_db.md_entries;
7514 mdb_cursor_close(MDB_cursor *mc)
7516 if (mc && !mc->mc_backup) {
7517 /* remove from txn, if tracked */
7518 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7519 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7520 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7522 *prev = mc->mc_next;
7529 mdb_cursor_txn(MDB_cursor *mc)
7531 if (!mc) return NULL;
7536 mdb_cursor_dbi(MDB_cursor *mc)
7541 /** Replace the key for a branch node with a new key.
7542 * @param[in] mc Cursor pointing to the node to operate on.
7543 * @param[in] key The new key to use.
7544 * @return 0 on success, non-zero on failure.
7547 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7553 int delta, ksize, oksize;
7554 indx_t ptr, i, numkeys, indx;
7557 indx = mc->mc_ki[mc->mc_top];
7558 mp = mc->mc_pg[mc->mc_top];
7559 node = NODEPTR(mp, indx);
7560 ptr = mp->mp_ptrs[indx];
7564 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7565 k2.mv_data = NODEKEY(node);
7566 k2.mv_size = node->mn_ksize;
7567 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7569 mdb_dkey(&k2, kbuf2),
7575 /* Sizes must be 2-byte aligned. */
7576 ksize = EVEN(key->mv_size);
7577 oksize = EVEN(node->mn_ksize);
7578 delta = ksize - oksize;
7580 /* Shift node contents if EVEN(key length) changed. */
7582 if (delta > 0 && SIZELEFT(mp) < delta) {
7584 /* not enough space left, do a delete and split */
7585 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7586 pgno = NODEPGNO(node);
7587 mdb_node_del(mc, 0);
7588 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7591 numkeys = NUMKEYS(mp);
7592 for (i = 0; i < numkeys; i++) {
7593 if (mp->mp_ptrs[i] <= ptr)
7594 mp->mp_ptrs[i] -= delta;
7597 base = (char *)mp + mp->mp_upper + PAGEBASE;
7598 len = ptr - mp->mp_upper + NODESIZE;
7599 memmove(base - delta, base, len);
7600 mp->mp_upper -= delta;
7602 node = NODEPTR(mp, indx);
7605 /* But even if no shift was needed, update ksize */
7606 if (node->mn_ksize != key->mv_size)
7607 node->mn_ksize = key->mv_size;
7610 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7616 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7618 /** Perform \b act while tracking temporary cursor \b mn */
7619 #define WITH_CURSOR_TRACKING(mn, act) do { \
7620 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
7621 if ((mn).mc_flags & C_SUB) { \
7622 dummy.mc_flags = C_INITIALIZED; \
7623 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
7628 tracked->mc_next = *tp; \
7631 *tp = tracked->mc_next; \
7634 /** Move a node from csrc to cdst.
7637 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
7644 unsigned short flags;
7648 /* Mark src and dst as dirty. */
7649 if ((rc = mdb_page_touch(csrc)) ||
7650 (rc = mdb_page_touch(cdst)))
7653 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7654 key.mv_size = csrc->mc_db->md_pad;
7655 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7657 data.mv_data = NULL;
7661 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7662 mdb_cassert(csrc, !((size_t)srcnode & 1));
7663 srcpg = NODEPGNO(srcnode);
7664 flags = srcnode->mn_flags;
7665 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7666 unsigned int snum = csrc->mc_snum;
7668 /* must find the lowest key below src */
7669 rc = mdb_page_search_lowest(csrc);
7672 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7673 key.mv_size = csrc->mc_db->md_pad;
7674 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7676 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7677 key.mv_size = NODEKSZ(s2);
7678 key.mv_data = NODEKEY(s2);
7680 csrc->mc_snum = snum--;
7681 csrc->mc_top = snum;
7683 key.mv_size = NODEKSZ(srcnode);
7684 key.mv_data = NODEKEY(srcnode);
7686 data.mv_size = NODEDSZ(srcnode);
7687 data.mv_data = NODEDATA(srcnode);
7689 mn.mc_xcursor = NULL;
7690 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7691 unsigned int snum = cdst->mc_snum;
7694 /* must find the lowest key below dst */
7695 mdb_cursor_copy(cdst, &mn);
7696 rc = mdb_page_search_lowest(&mn);
7699 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7700 bkey.mv_size = mn.mc_db->md_pad;
7701 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7703 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7704 bkey.mv_size = NODEKSZ(s2);
7705 bkey.mv_data = NODEKEY(s2);
7707 mn.mc_snum = snum--;
7710 rc = mdb_update_key(&mn, &bkey);
7715 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7716 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7717 csrc->mc_ki[csrc->mc_top],
7719 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7720 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7722 /* Add the node to the destination page.
7724 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7725 if (rc != MDB_SUCCESS)
7728 /* Delete the node from the source page.
7730 mdb_node_del(csrc, key.mv_size);
7733 /* Adjust other cursors pointing to mp */
7734 MDB_cursor *m2, *m3;
7735 MDB_dbi dbi = csrc->mc_dbi;
7736 MDB_page *mpd, *mps;
7738 mps = csrc->mc_pg[csrc->mc_top];
7739 /* If we're adding on the left, bump others up */
7741 mpd = cdst->mc_pg[csrc->mc_top];
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->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
7750 m3->mc_pg[csrc->mc_top] == mpd &&
7751 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
7752 m3->mc_ki[csrc->mc_top]++;
7755 m3->mc_pg[csrc->mc_top] == mps &&
7756 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
7757 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7758 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7759 m3->mc_ki[csrc->mc_top-1]++;
7761 if (XCURSOR_INITED(m3) && IS_LEAF(mps))
7762 XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
7765 /* Adding on the right, bump others down */
7767 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7768 if (csrc->mc_flags & C_SUB)
7769 m3 = &m2->mc_xcursor->mx_cursor;
7772 if (m3 == csrc) continue;
7773 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
7775 if (m3->mc_pg[csrc->mc_top] == mps) {
7776 if (!m3->mc_ki[csrc->mc_top]) {
7777 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7778 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7779 m3->mc_ki[csrc->mc_top-1]--;
7781 m3->mc_ki[csrc->mc_top]--;
7783 if (XCURSOR_INITED(m3) && IS_LEAF(mps))
7784 XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
7790 /* Update the parent separators.
7792 if (csrc->mc_ki[csrc->mc_top] == 0) {
7793 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7794 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7795 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7797 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7798 key.mv_size = NODEKSZ(srcnode);
7799 key.mv_data = NODEKEY(srcnode);
7801 DPRINTF(("update separator for source page %"Z"u to [%s]",
7802 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7803 mdb_cursor_copy(csrc, &mn);
7806 /* We want mdb_rebalance to find mn when doing fixups */
7807 WITH_CURSOR_TRACKING(mn,
7808 rc = mdb_update_key(&mn, &key));
7812 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7814 indx_t ix = csrc->mc_ki[csrc->mc_top];
7815 nullkey.mv_size = 0;
7816 csrc->mc_ki[csrc->mc_top] = 0;
7817 rc = mdb_update_key(csrc, &nullkey);
7818 csrc->mc_ki[csrc->mc_top] = ix;
7819 mdb_cassert(csrc, rc == MDB_SUCCESS);
7823 if (cdst->mc_ki[cdst->mc_top] == 0) {
7824 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7825 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7826 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7828 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7829 key.mv_size = NODEKSZ(srcnode);
7830 key.mv_data = NODEKEY(srcnode);
7832 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7833 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7834 mdb_cursor_copy(cdst, &mn);
7837 /* We want mdb_rebalance to find mn when doing fixups */
7838 WITH_CURSOR_TRACKING(mn,
7839 rc = mdb_update_key(&mn, &key));
7843 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7845 indx_t ix = cdst->mc_ki[cdst->mc_top];
7846 nullkey.mv_size = 0;
7847 cdst->mc_ki[cdst->mc_top] = 0;
7848 rc = mdb_update_key(cdst, &nullkey);
7849 cdst->mc_ki[cdst->mc_top] = ix;
7850 mdb_cassert(cdst, rc == MDB_SUCCESS);
7857 /** Merge one page into another.
7858 * The nodes from the page pointed to by \b csrc will
7859 * be copied to the page pointed to by \b cdst and then
7860 * the \b csrc page will be freed.
7861 * @param[in] csrc Cursor pointing to the source page.
7862 * @param[in] cdst Cursor pointing to the destination page.
7863 * @return 0 on success, non-zero on failure.
7866 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7868 MDB_page *psrc, *pdst;
7875 psrc = csrc->mc_pg[csrc->mc_top];
7876 pdst = cdst->mc_pg[cdst->mc_top];
7878 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7880 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7881 mdb_cassert(csrc, cdst->mc_snum > 1);
7883 /* Mark dst as dirty. */
7884 if ((rc = mdb_page_touch(cdst)))
7887 /* get dst page again now that we've touched it. */
7888 pdst = cdst->mc_pg[cdst->mc_top];
7890 /* Move all nodes from src to dst.
7892 j = nkeys = NUMKEYS(pdst);
7893 if (IS_LEAF2(psrc)) {
7894 key.mv_size = csrc->mc_db->md_pad;
7895 key.mv_data = METADATA(psrc);
7896 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7897 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7898 if (rc != MDB_SUCCESS)
7900 key.mv_data = (char *)key.mv_data + key.mv_size;
7903 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7904 srcnode = NODEPTR(psrc, i);
7905 if (i == 0 && IS_BRANCH(psrc)) {
7908 mdb_cursor_copy(csrc, &mn);
7909 mn.mc_xcursor = NULL;
7910 /* must find the lowest key below src */
7911 rc = mdb_page_search_lowest(&mn);
7914 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7915 key.mv_size = mn.mc_db->md_pad;
7916 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7918 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7919 key.mv_size = NODEKSZ(s2);
7920 key.mv_data = NODEKEY(s2);
7923 key.mv_size = srcnode->mn_ksize;
7924 key.mv_data = NODEKEY(srcnode);
7927 data.mv_size = NODEDSZ(srcnode);
7928 data.mv_data = NODEDATA(srcnode);
7929 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7930 if (rc != MDB_SUCCESS)
7935 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7936 pdst->mp_pgno, NUMKEYS(pdst),
7937 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7939 /* Unlink the src page from parent and add to free list.
7942 mdb_node_del(csrc, 0);
7943 if (csrc->mc_ki[csrc->mc_top] == 0) {
7945 rc = mdb_update_key(csrc, &key);
7953 psrc = csrc->mc_pg[csrc->mc_top];
7954 /* If not operating on FreeDB, allow this page to be reused
7955 * in this txn. Otherwise just add to free list.
7957 rc = mdb_page_loose(csrc, psrc);
7961 csrc->mc_db->md_leaf_pages--;
7963 csrc->mc_db->md_branch_pages--;
7965 /* Adjust other cursors pointing to mp */
7966 MDB_cursor *m2, *m3;
7967 MDB_dbi dbi = csrc->mc_dbi;
7968 unsigned int top = csrc->mc_top;
7970 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7971 if (csrc->mc_flags & C_SUB)
7972 m3 = &m2->mc_xcursor->mx_cursor;
7975 if (m3 == csrc) continue;
7976 if (m3->mc_snum < csrc->mc_snum) continue;
7977 if (m3->mc_pg[top] == psrc) {
7978 m3->mc_pg[top] = pdst;
7979 m3->mc_ki[top] += nkeys;
7980 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
7981 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
7982 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
7985 if (XCURSOR_INITED(m3) && IS_LEAF(psrc))
7986 XCURSOR_REFRESH(m3, m3->mc_pg[top], m3->mc_ki[top]);
7990 unsigned int snum = cdst->mc_snum;
7991 uint16_t depth = cdst->mc_db->md_depth;
7992 mdb_cursor_pop(cdst);
7993 rc = mdb_rebalance(cdst);
7994 /* Did the tree height change? */
7995 if (depth != cdst->mc_db->md_depth)
7996 snum += cdst->mc_db->md_depth - depth;
7997 cdst->mc_snum = snum;
7998 cdst->mc_top = snum-1;
8003 /** Copy the contents of a cursor.
8004 * @param[in] csrc The cursor to copy from.
8005 * @param[out] cdst The cursor to copy to.
8008 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
8012 cdst->mc_txn = csrc->mc_txn;
8013 cdst->mc_dbi = csrc->mc_dbi;
8014 cdst->mc_db = csrc->mc_db;
8015 cdst->mc_dbx = csrc->mc_dbx;
8016 cdst->mc_snum = csrc->mc_snum;
8017 cdst->mc_top = csrc->mc_top;
8018 cdst->mc_flags = csrc->mc_flags;
8020 for (i=0; i<csrc->mc_snum; i++) {
8021 cdst->mc_pg[i] = csrc->mc_pg[i];
8022 cdst->mc_ki[i] = csrc->mc_ki[i];
8026 /** Rebalance the tree after a delete operation.
8027 * @param[in] mc Cursor pointing to the page where rebalancing
8029 * @return 0 on success, non-zero on failure.
8032 mdb_rebalance(MDB_cursor *mc)
8036 unsigned int ptop, minkeys, thresh;
8040 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
8045 thresh = FILL_THRESHOLD;
8047 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
8048 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
8049 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
8050 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
8052 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
8053 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
8054 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
8055 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
8059 if (mc->mc_snum < 2) {
8060 MDB_page *mp = mc->mc_pg[0];
8062 DPUTS("Can't rebalance a subpage, ignoring");
8065 if (NUMKEYS(mp) == 0) {
8066 DPUTS("tree is completely empty");
8067 mc->mc_db->md_root = P_INVALID;
8068 mc->mc_db->md_depth = 0;
8069 mc->mc_db->md_leaf_pages = 0;
8070 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8073 /* Adjust cursors pointing to mp */
8076 mc->mc_flags &= ~C_INITIALIZED;
8078 MDB_cursor *m2, *m3;
8079 MDB_dbi dbi = mc->mc_dbi;
8081 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8082 if (mc->mc_flags & C_SUB)
8083 m3 = &m2->mc_xcursor->mx_cursor;
8086 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
8088 if (m3->mc_pg[0] == mp) {
8091 m3->mc_flags &= ~C_INITIALIZED;
8095 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
8097 DPUTS("collapsing root page!");
8098 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8101 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
8102 rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
8105 mc->mc_db->md_depth--;
8106 mc->mc_db->md_branch_pages--;
8107 mc->mc_ki[0] = mc->mc_ki[1];
8108 for (i = 1; i<mc->mc_db->md_depth; i++) {
8109 mc->mc_pg[i] = mc->mc_pg[i+1];
8110 mc->mc_ki[i] = mc->mc_ki[i+1];
8113 /* Adjust other cursors pointing to mp */
8114 MDB_cursor *m2, *m3;
8115 MDB_dbi dbi = mc->mc_dbi;
8117 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8118 if (mc->mc_flags & C_SUB)
8119 m3 = &m2->mc_xcursor->mx_cursor;
8122 if (m3 == mc) continue;
8123 if (!(m3->mc_flags & C_INITIALIZED))
8125 if (m3->mc_pg[0] == mp) {
8126 for (i=0; i<mc->mc_db->md_depth; i++) {
8127 m3->mc_pg[i] = m3->mc_pg[i+1];
8128 m3->mc_ki[i] = m3->mc_ki[i+1];
8136 DPUTS("root page doesn't need rebalancing");
8140 /* The parent (branch page) must have at least 2 pointers,
8141 * otherwise the tree is invalid.
8143 ptop = mc->mc_top-1;
8144 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
8146 /* Leaf page fill factor is below the threshold.
8147 * Try to move keys from left or right neighbor, or
8148 * merge with a neighbor page.
8153 mdb_cursor_copy(mc, &mn);
8154 mn.mc_xcursor = NULL;
8156 oldki = mc->mc_ki[mc->mc_top];
8157 if (mc->mc_ki[ptop] == 0) {
8158 /* We're the leftmost leaf in our parent.
8160 DPUTS("reading right neighbor");
8162 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8163 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8166 mn.mc_ki[mn.mc_top] = 0;
8167 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
8170 /* There is at least one neighbor to the left.
8172 DPUTS("reading left neighbor");
8174 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8175 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8178 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
8179 mc->mc_ki[mc->mc_top] = 0;
8183 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
8184 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
8185 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
8187 /* If the neighbor page is above threshold and has enough keys,
8188 * move one key from it. Otherwise we should try to merge them.
8189 * (A branch page must never have less than 2 keys.)
8191 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
8192 rc = mdb_node_move(&mn, mc, fromleft);
8194 /* if we inserted on left, bump position up */
8199 rc = mdb_page_merge(&mn, mc);
8201 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
8202 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
8203 /* We want mdb_rebalance to find mn when doing fixups */
8204 WITH_CURSOR_TRACKING(mn,
8205 rc = mdb_page_merge(mc, &mn));
8206 mdb_cursor_copy(&mn, mc);
8208 mc->mc_flags &= ~C_EOF;
8210 mc->mc_ki[mc->mc_top] = oldki;
8214 /** Complete a delete operation started by #mdb_cursor_del(). */
8216 mdb_cursor_del0(MDB_cursor *mc)
8222 MDB_cursor *m2, *m3;
8223 MDB_dbi dbi = mc->mc_dbi;
8225 ki = mc->mc_ki[mc->mc_top];
8226 mp = mc->mc_pg[mc->mc_top];
8227 mdb_node_del(mc, mc->mc_db->md_pad);
8228 mc->mc_db->md_entries--;
8230 /* Adjust other cursors pointing to mp */
8231 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8232 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8233 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8235 if (m3 == mc || m3->mc_snum < mc->mc_snum)
8237 if (m3->mc_pg[mc->mc_top] == mp) {
8238 if (m3->mc_ki[mc->mc_top] == ki) {
8239 m3->mc_flags |= C_DEL;
8240 if (mc->mc_db->md_flags & MDB_DUPSORT) {
8241 /* Sub-cursor referred into dataset which is gone */
8242 m3->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
8245 } else if (m3->mc_ki[mc->mc_top] > ki) {
8246 m3->mc_ki[mc->mc_top]--;
8248 if (XCURSOR_INITED(m3))
8249 XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
8253 rc = mdb_rebalance(mc);
8255 if (rc == MDB_SUCCESS) {
8256 /* DB is totally empty now, just bail out.
8257 * Other cursors adjustments were already done
8258 * by mdb_rebalance and aren't needed here.
8263 mp = mc->mc_pg[mc->mc_top];
8264 nkeys = NUMKEYS(mp);
8266 /* Adjust other cursors pointing to mp */
8267 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
8268 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8269 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8271 if (m3->mc_snum < mc->mc_snum)
8273 if (m3->mc_pg[mc->mc_top] == mp) {
8274 /* if m3 points past last node in page, find next sibling */
8275 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
8276 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8277 rc = mdb_cursor_sibling(m3, 1);
8278 if (rc == MDB_NOTFOUND) {
8279 m3->mc_flags |= C_EOF;
8284 if (mc->mc_db->md_flags & MDB_DUPSORT) {
8285 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
8286 /* If this node is a fake page, it needs to be reinited
8287 * because its data has moved. But just reset mc_pg[0]
8288 * if the xcursor is already live.
8290 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) {
8291 if (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)
8292 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8294 mdb_xcursor_init1(m3, node);
8300 mc->mc_flags |= C_DEL;
8304 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8309 mdb_del(MDB_txn *txn, MDB_dbi dbi,
8310 MDB_val *key, MDB_val *data)
8312 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8315 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8316 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8318 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
8319 /* must ignore any data */
8323 return mdb_del0(txn, dbi, key, data, 0);
8327 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
8328 MDB_val *key, MDB_val *data, unsigned flags)
8333 MDB_val rdata, *xdata;
8337 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
8339 mdb_cursor_init(&mc, txn, dbi, &mx);
8348 flags |= MDB_NODUPDATA;
8350 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
8352 /* let mdb_page_split know about this cursor if needed:
8353 * delete will trigger a rebalance; if it needs to move
8354 * a node from one page to another, it will have to
8355 * update the parent's separator key(s). If the new sepkey
8356 * is larger than the current one, the parent page may
8357 * run out of space, triggering a split. We need this
8358 * cursor to be consistent until the end of the rebalance.
8360 mc.mc_flags |= C_UNTRACK;
8361 mc.mc_next = txn->mt_cursors[dbi];
8362 txn->mt_cursors[dbi] = &mc;
8363 rc = mdb_cursor_del(&mc, flags);
8364 txn->mt_cursors[dbi] = mc.mc_next;
8369 /** Split a page and insert a new node.
8370 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
8371 * The cursor will be updated to point to the actual page and index where
8372 * the node got inserted after the split.
8373 * @param[in] newkey The key for the newly inserted node.
8374 * @param[in] newdata The data for the newly inserted node.
8375 * @param[in] newpgno The page number, if the new node is a branch node.
8376 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
8377 * @return 0 on success, non-zero on failure.
8380 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
8381 unsigned int nflags)
8384 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
8387 int i, j, split_indx, nkeys, pmax;
8388 MDB_env *env = mc->mc_txn->mt_env;
8390 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
8391 MDB_page *copy = NULL;
8392 MDB_page *mp, *rp, *pp;
8397 mp = mc->mc_pg[mc->mc_top];
8398 newindx = mc->mc_ki[mc->mc_top];
8399 nkeys = NUMKEYS(mp);
8401 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
8402 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
8403 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
8405 /* Create a right sibling. */
8406 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
8408 rp->mp_pad = mp->mp_pad;
8409 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
8411 /* Usually when splitting the root page, the cursor
8412 * height is 1. But when called from mdb_update_key,
8413 * the cursor height may be greater because it walks
8414 * up the stack while finding the branch slot to update.
8416 if (mc->mc_top < 1) {
8417 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
8419 /* shift current top to make room for new parent */
8420 for (i=mc->mc_snum; i>0; i--) {
8421 mc->mc_pg[i] = mc->mc_pg[i-1];
8422 mc->mc_ki[i] = mc->mc_ki[i-1];
8426 mc->mc_db->md_root = pp->mp_pgno;
8427 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
8428 new_root = mc->mc_db->md_depth++;
8430 /* Add left (implicit) pointer. */
8431 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
8432 /* undo the pre-push */
8433 mc->mc_pg[0] = mc->mc_pg[1];
8434 mc->mc_ki[0] = mc->mc_ki[1];
8435 mc->mc_db->md_root = mp->mp_pgno;
8436 mc->mc_db->md_depth--;
8443 ptop = mc->mc_top-1;
8444 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
8447 mdb_cursor_copy(mc, &mn);
8448 mn.mc_xcursor = NULL;
8449 mn.mc_pg[mn.mc_top] = rp;
8450 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
8452 if (nflags & MDB_APPEND) {
8453 mn.mc_ki[mn.mc_top] = 0;
8455 split_indx = newindx;
8459 split_indx = (nkeys+1) / 2;
8464 unsigned int lsize, rsize, ksize;
8465 /* Move half of the keys to the right sibling */
8466 x = mc->mc_ki[mc->mc_top] - split_indx;
8467 ksize = mc->mc_db->md_pad;
8468 split = LEAF2KEY(mp, split_indx, ksize);
8469 rsize = (nkeys - split_indx) * ksize;
8470 lsize = (nkeys - split_indx) * sizeof(indx_t);
8471 mp->mp_lower -= lsize;
8472 rp->mp_lower += lsize;
8473 mp->mp_upper += rsize - lsize;
8474 rp->mp_upper -= rsize - lsize;
8475 sepkey.mv_size = ksize;
8476 if (newindx == split_indx) {
8477 sepkey.mv_data = newkey->mv_data;
8479 sepkey.mv_data = split;
8482 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
8483 memcpy(rp->mp_ptrs, split, rsize);
8484 sepkey.mv_data = rp->mp_ptrs;
8485 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
8486 memcpy(ins, newkey->mv_data, ksize);
8487 mp->mp_lower += sizeof(indx_t);
8488 mp->mp_upper -= ksize - sizeof(indx_t);
8491 memcpy(rp->mp_ptrs, split, x * ksize);
8492 ins = LEAF2KEY(rp, x, ksize);
8493 memcpy(ins, newkey->mv_data, ksize);
8494 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
8495 rp->mp_lower += sizeof(indx_t);
8496 rp->mp_upper -= ksize - sizeof(indx_t);
8497 mc->mc_ki[mc->mc_top] = x;
8500 int psize, nsize, k;
8501 /* Maximum free space in an empty page */
8502 pmax = env->me_psize - PAGEHDRSZ;
8504 nsize = mdb_leaf_size(env, newkey, newdata);
8506 nsize = mdb_branch_size(env, newkey);
8507 nsize = EVEN(nsize);
8509 /* grab a page to hold a temporary copy */
8510 copy = mdb_page_malloc(mc->mc_txn, 1);
8515 copy->mp_pgno = mp->mp_pgno;
8516 copy->mp_flags = mp->mp_flags;
8517 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
8518 copy->mp_upper = env->me_psize - PAGEBASE;
8520 /* prepare to insert */
8521 for (i=0, j=0; i<nkeys; i++) {
8523 copy->mp_ptrs[j++] = 0;
8525 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
8528 /* When items are relatively large the split point needs
8529 * to be checked, because being off-by-one will make the
8530 * difference between success or failure in mdb_node_add.
8532 * It's also relevant if a page happens to be laid out
8533 * such that one half of its nodes are all "small" and
8534 * the other half of its nodes are "large." If the new
8535 * item is also "large" and falls on the half with
8536 * "large" nodes, it also may not fit.
8538 * As a final tweak, if the new item goes on the last
8539 * spot on the page (and thus, onto the new page), bias
8540 * the split so the new page is emptier than the old page.
8541 * This yields better packing during sequential inserts.
8543 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
8544 /* Find split point */
8546 if (newindx <= split_indx || newindx >= nkeys) {
8548 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
8553 for (; i!=k; i+=j) {
8558 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8559 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
8561 if (F_ISSET(node->mn_flags, F_BIGDATA))
8562 psize += sizeof(pgno_t);
8564 psize += NODEDSZ(node);
8566 psize = EVEN(psize);
8568 if (psize > pmax || i == k-j) {
8569 split_indx = i + (j<0);
8574 if (split_indx == newindx) {
8575 sepkey.mv_size = newkey->mv_size;
8576 sepkey.mv_data = newkey->mv_data;
8578 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
8579 sepkey.mv_size = node->mn_ksize;
8580 sepkey.mv_data = NODEKEY(node);
8585 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
8587 /* Copy separator key to the parent.
8589 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
8590 int snum = mc->mc_snum;
8594 /* We want other splits to find mn when doing fixups */
8595 WITH_CURSOR_TRACKING(mn,
8596 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
8601 if (mc->mc_snum > snum) {
8604 /* Right page might now have changed parent.
8605 * Check if left page also changed parent.
8607 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8608 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8609 for (i=0; i<ptop; i++) {
8610 mc->mc_pg[i] = mn.mc_pg[i];
8611 mc->mc_ki[i] = mn.mc_ki[i];
8613 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8614 if (mn.mc_ki[ptop]) {
8615 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8617 /* find right page's left sibling */
8618 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8619 mdb_cursor_sibling(mc, 0);
8624 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8627 if (rc != MDB_SUCCESS) {
8630 if (nflags & MDB_APPEND) {
8631 mc->mc_pg[mc->mc_top] = rp;
8632 mc->mc_ki[mc->mc_top] = 0;
8633 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8636 for (i=0; i<mc->mc_top; i++)
8637 mc->mc_ki[i] = mn.mc_ki[i];
8638 } else if (!IS_LEAF2(mp)) {
8640 mc->mc_pg[mc->mc_top] = rp;
8645 rkey.mv_data = newkey->mv_data;
8646 rkey.mv_size = newkey->mv_size;
8652 /* Update index for the new key. */
8653 mc->mc_ki[mc->mc_top] = j;
8655 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8656 rkey.mv_data = NODEKEY(node);
8657 rkey.mv_size = node->mn_ksize;
8659 xdata.mv_data = NODEDATA(node);
8660 xdata.mv_size = NODEDSZ(node);
8663 pgno = NODEPGNO(node);
8664 flags = node->mn_flags;
8667 if (!IS_LEAF(mp) && j == 0) {
8668 /* First branch index doesn't need key data. */
8672 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8678 mc->mc_pg[mc->mc_top] = copy;
8683 } while (i != split_indx);
8685 nkeys = NUMKEYS(copy);
8686 for (i=0; i<nkeys; i++)
8687 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8688 mp->mp_lower = copy->mp_lower;
8689 mp->mp_upper = copy->mp_upper;
8690 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8691 env->me_psize - copy->mp_upper - PAGEBASE);
8693 /* reset back to original page */
8694 if (newindx < split_indx) {
8695 mc->mc_pg[mc->mc_top] = mp;
8697 mc->mc_pg[mc->mc_top] = rp;
8699 /* Make sure mc_ki is still valid.
8701 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8702 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8703 for (i=0; i<=ptop; i++) {
8704 mc->mc_pg[i] = mn.mc_pg[i];
8705 mc->mc_ki[i] = mn.mc_ki[i];
8709 if (nflags & MDB_RESERVE) {
8710 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8711 if (!(node->mn_flags & F_BIGDATA))
8712 newdata->mv_data = NODEDATA(node);
8715 if (newindx >= split_indx) {
8716 mc->mc_pg[mc->mc_top] = rp;
8718 /* Make sure mc_ki is still valid.
8720 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8721 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8722 for (i=0; i<=ptop; i++) {
8723 mc->mc_pg[i] = mn.mc_pg[i];
8724 mc->mc_ki[i] = mn.mc_ki[i];
8731 /* Adjust other cursors pointing to mp */
8732 MDB_cursor *m2, *m3;
8733 MDB_dbi dbi = mc->mc_dbi;
8734 nkeys = NUMKEYS(mp);
8736 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8737 if (mc->mc_flags & C_SUB)
8738 m3 = &m2->mc_xcursor->mx_cursor;
8743 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8747 /* sub cursors may be on different DB */
8748 if (m3->mc_pg[0] != mp)
8751 for (k=new_root; k>=0; k--) {
8752 m3->mc_ki[k+1] = m3->mc_ki[k];
8753 m3->mc_pg[k+1] = m3->mc_pg[k];
8755 if (m3->mc_ki[0] >= nkeys) {
8760 m3->mc_pg[0] = mc->mc_pg[0];
8764 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8765 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8766 m3->mc_ki[mc->mc_top]++;
8767 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8768 m3->mc_pg[mc->mc_top] = rp;
8769 m3->mc_ki[mc->mc_top] -= nkeys;
8770 for (i=0; i<mc->mc_top; i++) {
8771 m3->mc_ki[i] = mn.mc_ki[i];
8772 m3->mc_pg[i] = mn.mc_pg[i];
8775 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8776 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8779 if (XCURSOR_INITED(m3) && IS_LEAF(mp))
8780 XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
8783 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8786 if (copy) /* tmp page */
8787 mdb_page_free(env, copy);
8789 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8794 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8795 MDB_val *key, MDB_val *data, unsigned int flags)
8801 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8804 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
8807 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8808 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8810 mdb_cursor_init(&mc, txn, dbi, &mx);
8811 mc.mc_next = txn->mt_cursors[dbi];
8812 txn->mt_cursors[dbi] = &mc;
8813 rc = mdb_cursor_put(&mc, key, data, flags);
8814 txn->mt_cursors[dbi] = mc.mc_next;
8819 #define MDB_WBUF (1024*1024)
8822 /** State needed for a compacting copy. */
8823 typedef struct mdb_copy {
8824 pthread_mutex_t mc_mutex;
8825 pthread_cond_t mc_cond;
8832 pgno_t mc_next_pgno;
8835 volatile int mc_new;
8840 /** Dedicated writer thread for compacting copy. */
8841 static THREAD_RET ESECT CALL_CONV
8842 mdb_env_copythr(void *arg)
8846 int toggle = 0, wsize, rc;
8849 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8852 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8855 pthread_mutex_lock(&my->mc_mutex);
8857 pthread_cond_signal(&my->mc_cond);
8860 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8861 if (my->mc_new < 0) {
8866 wsize = my->mc_wlen[toggle];
8867 ptr = my->mc_wbuf[toggle];
8870 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8874 } else if (len > 0) {
8888 /* If there's an overflow page tail, write it too */
8889 if (my->mc_olen[toggle]) {
8890 wsize = my->mc_olen[toggle];
8891 ptr = my->mc_over[toggle];
8892 my->mc_olen[toggle] = 0;
8895 my->mc_wlen[toggle] = 0;
8897 pthread_cond_signal(&my->mc_cond);
8899 pthread_cond_signal(&my->mc_cond);
8900 pthread_mutex_unlock(&my->mc_mutex);
8901 return (THREAD_RET)0;
8905 /** Tell the writer thread there's a buffer ready to write */
8907 mdb_env_cthr_toggle(mdb_copy *my, int st)
8909 int toggle = my->mc_toggle ^ 1;
8910 pthread_mutex_lock(&my->mc_mutex);
8911 if (my->mc_status) {
8912 pthread_mutex_unlock(&my->mc_mutex);
8913 return my->mc_status;
8915 while (my->mc_new == 1)
8916 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8918 my->mc_toggle = toggle;
8919 pthread_cond_signal(&my->mc_cond);
8920 pthread_mutex_unlock(&my->mc_mutex);
8924 /** Depth-first tree traversal for compacting copy. */
8926 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8928 MDB_cursor mc = {0};
8930 MDB_page *mo, *mp, *leaf;
8935 /* Empty DB, nothing to do */
8936 if (*pg == P_INVALID)
8940 mc.mc_txn = my->mc_txn;
8942 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
8945 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8949 /* Make cursor pages writable */
8950 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8954 for (i=0; i<mc.mc_top; i++) {
8955 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8956 mc.mc_pg[i] = (MDB_page *)ptr;
8957 ptr += my->mc_env->me_psize;
8960 /* This is writable space for a leaf page. Usually not needed. */
8961 leaf = (MDB_page *)ptr;
8963 toggle = my->mc_toggle;
8964 while (mc.mc_snum > 0) {
8966 mp = mc.mc_pg[mc.mc_top];
8970 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8971 for (i=0; i<n; i++) {
8972 ni = NODEPTR(mp, i);
8973 if (ni->mn_flags & F_BIGDATA) {
8977 /* Need writable leaf */
8979 mc.mc_pg[mc.mc_top] = leaf;
8980 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8982 ni = NODEPTR(mp, i);
8985 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8986 rc = mdb_page_get(&mc, pg, &omp, NULL);
8989 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8990 rc = mdb_env_cthr_toggle(my, 1);
8993 toggle = my->mc_toggle;
8995 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8996 memcpy(mo, omp, my->mc_env->me_psize);
8997 mo->mp_pgno = my->mc_next_pgno;
8998 my->mc_next_pgno += omp->mp_pages;
8999 my->mc_wlen[toggle] += my->mc_env->me_psize;
9000 if (omp->mp_pages > 1) {
9001 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
9002 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
9003 rc = mdb_env_cthr_toggle(my, 1);
9006 toggle = my->mc_toggle;
9008 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
9009 } else if (ni->mn_flags & F_SUBDATA) {
9012 /* Need writable leaf */
9014 mc.mc_pg[mc.mc_top] = leaf;
9015 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9017 ni = NODEPTR(mp, i);
9020 memcpy(&db, NODEDATA(ni), sizeof(db));
9021 my->mc_toggle = toggle;
9022 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
9025 toggle = my->mc_toggle;
9026 memcpy(NODEDATA(ni), &db, sizeof(db));
9031 mc.mc_ki[mc.mc_top]++;
9032 if (mc.mc_ki[mc.mc_top] < n) {
9035 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
9037 rc = mdb_page_get(&mc, pg, &mp, NULL);
9042 mc.mc_ki[mc.mc_top] = 0;
9043 if (IS_BRANCH(mp)) {
9044 /* Whenever we advance to a sibling branch page,
9045 * we must proceed all the way down to its first leaf.
9047 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
9050 mc.mc_pg[mc.mc_top] = mp;
9054 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9055 rc = mdb_env_cthr_toggle(my, 1);
9058 toggle = my->mc_toggle;
9060 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9061 mdb_page_copy(mo, mp, my->mc_env->me_psize);
9062 mo->mp_pgno = my->mc_next_pgno++;
9063 my->mc_wlen[toggle] += my->mc_env->me_psize;
9065 /* Update parent if there is one */
9066 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
9067 SETPGNO(ni, mo->mp_pgno);
9068 mdb_cursor_pop(&mc);
9070 /* Otherwise we're done */
9080 /** Copy environment with compaction. */
9082 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
9087 MDB_txn *txn = NULL;
9092 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
9093 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
9094 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
9095 if (my.mc_wbuf[0] == NULL)
9098 pthread_mutex_init(&my.mc_mutex, NULL);
9099 pthread_cond_init(&my.mc_cond, NULL);
9100 #ifdef HAVE_MEMALIGN
9101 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
9102 if (my.mc_wbuf[0] == NULL)
9105 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_os_psize, MDB_WBUF*2);
9110 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
9111 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
9116 my.mc_next_pgno = NUM_METAS;
9122 THREAD_CREATE(thr, mdb_env_copythr, &my);
9124 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9128 mp = (MDB_page *)my.mc_wbuf[0];
9129 memset(mp, 0, NUM_METAS * env->me_psize);
9131 mp->mp_flags = P_META;
9132 mm = (MDB_meta *)METADATA(mp);
9133 mdb_env_init_meta0(env, mm);
9134 mm->mm_address = env->me_metas[0]->mm_address;
9136 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
9138 mp->mp_flags = P_META;
9139 *(MDB_meta *)METADATA(mp) = *mm;
9140 mm = (MDB_meta *)METADATA(mp);
9142 /* Count the number of free pages, subtract from lastpg to find
9143 * number of active pages
9146 MDB_ID freecount = 0;
9149 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
9150 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
9151 freecount += *(MDB_ID *)data.mv_data;
9152 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
9153 txn->mt_dbs[FREE_DBI].md_leaf_pages +
9154 txn->mt_dbs[FREE_DBI].md_overflow_pages;
9156 /* Set metapage 1 */
9157 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
9158 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
9159 if (mm->mm_last_pg > NUM_METAS-1) {
9160 mm->mm_dbs[MAIN_DBI].md_root = mm->mm_last_pg;
9163 mm->mm_dbs[MAIN_DBI].md_root = P_INVALID;
9166 my.mc_wlen[0] = env->me_psize * NUM_METAS;
9168 pthread_mutex_lock(&my.mc_mutex);
9170 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
9171 pthread_mutex_unlock(&my.mc_mutex);
9172 rc = mdb_env_cwalk(&my, &txn->mt_dbs[MAIN_DBI].md_root, 0);
9173 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
9174 rc = mdb_env_cthr_toggle(&my, 1);
9175 mdb_env_cthr_toggle(&my, -1);
9176 pthread_mutex_lock(&my.mc_mutex);
9178 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
9179 pthread_mutex_unlock(&my.mc_mutex);
9184 CloseHandle(my.mc_cond);
9185 CloseHandle(my.mc_mutex);
9186 _aligned_free(my.mc_wbuf[0]);
9188 pthread_cond_destroy(&my.mc_cond);
9189 pthread_mutex_destroy(&my.mc_mutex);
9190 free(my.mc_wbuf[0]);
9195 /** Copy environment as-is. */
9197 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
9199 MDB_txn *txn = NULL;
9200 mdb_mutexref_t wmutex = NULL;
9206 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9210 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9213 /* Do the lock/unlock of the reader mutex before starting the
9214 * write txn. Otherwise other read txns could block writers.
9216 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9221 /* We must start the actual read txn after blocking writers */
9222 mdb_txn_end(txn, MDB_END_RESET_TMP);
9224 /* Temporarily block writers until we snapshot the meta pages */
9225 wmutex = env->me_wmutex;
9226 if (LOCK_MUTEX(rc, env, wmutex))
9229 rc = mdb_txn_renew0(txn);
9231 UNLOCK_MUTEX(wmutex);
9236 wsize = env->me_psize * NUM_METAS;
9240 DO_WRITE(rc, fd, ptr, w2, len);
9244 } else if (len > 0) {
9250 /* Non-blocking or async handles are not supported */
9256 UNLOCK_MUTEX(wmutex);
9261 w3 = txn->mt_next_pgno * env->me_psize;
9264 if ((rc = mdb_fsize(env->me_fd, &fsize)))
9271 if (wsize > MAX_WRITE)
9275 DO_WRITE(rc, fd, ptr, w2, len);
9279 } else if (len > 0) {
9296 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
9298 if (flags & MDB_CP_COMPACT)
9299 return mdb_env_copyfd1(env, fd);
9301 return mdb_env_copyfd0(env, fd);
9305 mdb_env_copyfd(MDB_env *env, HANDLE fd)
9307 return mdb_env_copyfd2(env, fd, 0);
9311 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
9315 HANDLE newfd = INVALID_HANDLE_VALUE;
9320 if (env->me_flags & MDB_NOSUBDIR) {
9321 lpath = (char *)path;
9324 len += sizeof(DATANAME);
9325 lpath = malloc(len);
9328 sprintf(lpath, "%s" DATANAME, path);
9331 /* The destination path must exist, but the destination file must not.
9332 * We don't want the OS to cache the writes, since the source data is
9333 * already in the OS cache.
9336 rc = utf8_to_utf16(lpath, -1, &wpath, NULL);
9339 newfd = CreateFileW(wpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
9340 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
9343 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
9345 if (newfd == INVALID_HANDLE_VALUE) {
9350 if (env->me_psize >= env->me_os_psize) {
9352 /* Set O_DIRECT if the file system supports it */
9353 if ((rc = fcntl(newfd, F_GETFL)) != -1)
9354 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
9356 #ifdef F_NOCACHE /* __APPLE__ */
9357 rc = fcntl(newfd, F_NOCACHE, 1);
9365 rc = mdb_env_copyfd2(env, newfd, flags);
9368 if (!(env->me_flags & MDB_NOSUBDIR))
9370 if (newfd != INVALID_HANDLE_VALUE)
9371 if (close(newfd) < 0 && rc == MDB_SUCCESS)
9378 mdb_env_copy(MDB_env *env, const char *path)
9380 return mdb_env_copy2(env, path, 0);
9384 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
9386 if (flag & ~CHANGEABLE)
9389 env->me_flags |= flag;
9391 env->me_flags &= ~flag;
9396 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
9401 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
9406 mdb_env_set_userctx(MDB_env *env, void *ctx)
9410 env->me_userctx = ctx;
9415 mdb_env_get_userctx(MDB_env *env)
9417 return env ? env->me_userctx : NULL;
9421 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
9426 env->me_assert_func = func;
9432 mdb_env_get_path(MDB_env *env, const char **arg)
9437 *arg = env->me_path;
9442 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
9451 /** Common code for #mdb_stat() and #mdb_env_stat().
9452 * @param[in] env the environment to operate in.
9453 * @param[in] db the #MDB_db record containing the stats to return.
9454 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
9455 * @return 0, this function always succeeds.
9458 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
9460 arg->ms_psize = env->me_psize;
9461 arg->ms_depth = db->md_depth;
9462 arg->ms_branch_pages = db->md_branch_pages;
9463 arg->ms_leaf_pages = db->md_leaf_pages;
9464 arg->ms_overflow_pages = db->md_overflow_pages;
9465 arg->ms_entries = db->md_entries;
9471 mdb_env_stat(MDB_env *env, MDB_stat *arg)
9475 if (env == NULL || arg == NULL)
9478 meta = mdb_env_pick_meta(env);
9480 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
9484 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
9488 if (env == NULL || arg == NULL)
9491 meta = mdb_env_pick_meta(env);
9492 arg->me_mapaddr = meta->mm_address;
9493 arg->me_last_pgno = meta->mm_last_pg;
9494 arg->me_last_txnid = meta->mm_txnid;
9496 arg->me_mapsize = env->me_mapsize;
9497 arg->me_maxreaders = env->me_maxreaders;
9498 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
9502 /** Set the default comparison functions for a database.
9503 * Called immediately after a database is opened to set the defaults.
9504 * The user can then override them with #mdb_set_compare() or
9505 * #mdb_set_dupsort().
9506 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
9507 * @param[in] dbi A database handle returned by #mdb_dbi_open()
9510 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
9512 uint16_t f = txn->mt_dbs[dbi].md_flags;
9514 txn->mt_dbxs[dbi].md_cmp =
9515 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
9516 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
9518 txn->mt_dbxs[dbi].md_dcmp =
9519 !(f & MDB_DUPSORT) ? 0 :
9520 ((f & MDB_INTEGERDUP)
9521 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
9522 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
9525 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
9531 int rc, dbflag, exact;
9532 unsigned int unused = 0, seq;
9536 if (flags & ~VALID_FLAGS)
9538 if (txn->mt_flags & MDB_TXN_BLOCKED)
9544 if (flags & PERSISTENT_FLAGS) {
9545 uint16_t f2 = flags & PERSISTENT_FLAGS;
9546 /* make sure flag changes get committed */
9547 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
9548 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
9549 txn->mt_flags |= MDB_TXN_DIRTY;
9552 mdb_default_cmp(txn, MAIN_DBI);
9556 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
9557 mdb_default_cmp(txn, MAIN_DBI);
9560 /* Is the DB already open? */
9562 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
9563 if (!txn->mt_dbxs[i].md_name.mv_size) {
9564 /* Remember this free slot */
9565 if (!unused) unused = i;
9568 if (len == txn->mt_dbxs[i].md_name.mv_size &&
9569 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
9575 /* If no free slot and max hit, fail */
9576 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
9577 return MDB_DBS_FULL;
9579 /* Cannot mix named databases with some mainDB flags */
9580 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
9581 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
9583 /* Find the DB info */
9584 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
9587 key.mv_data = (void *)name;
9588 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
9589 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
9590 if (rc == MDB_SUCCESS) {
9591 /* make sure this is actually a DB */
9592 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
9593 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
9594 return MDB_INCOMPATIBLE;
9595 } else if (! (rc == MDB_NOTFOUND && (flags & MDB_CREATE))) {
9599 /* Done here so we cannot fail after creating a new DB */
9600 if ((namedup = strdup(name)) == NULL)
9604 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
9605 data.mv_size = sizeof(MDB_db);
9606 data.mv_data = &dummy;
9607 memset(&dummy, 0, sizeof(dummy));
9608 dummy.md_root = P_INVALID;
9609 dummy.md_flags = flags & PERSISTENT_FLAGS;
9610 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
9617 /* Got info, register DBI in this txn */
9618 unsigned int slot = unused ? unused : txn->mt_numdbs;
9619 txn->mt_dbxs[slot].md_name.mv_data = namedup;
9620 txn->mt_dbxs[slot].md_name.mv_size = len;
9621 txn->mt_dbxs[slot].md_rel = NULL;
9622 txn->mt_dbflags[slot] = dbflag;
9623 /* txn-> and env-> are the same in read txns, use
9624 * tmp variable to avoid undefined assignment
9626 seq = ++txn->mt_env->me_dbiseqs[slot];
9627 txn->mt_dbiseqs[slot] = seq;
9629 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
9631 mdb_default_cmp(txn, slot);
9641 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9643 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
9646 if (txn->mt_flags & MDB_TXN_BLOCKED)
9649 if (txn->mt_dbflags[dbi] & DB_STALE) {
9652 /* Stale, must read the DB's root. cursor_init does it for us. */
9653 mdb_cursor_init(&mc, txn, dbi, &mx);
9655 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9658 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9661 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
9663 ptr = env->me_dbxs[dbi].md_name.mv_data;
9664 /* If there was no name, this was already closed */
9666 env->me_dbxs[dbi].md_name.mv_data = NULL;
9667 env->me_dbxs[dbi].md_name.mv_size = 0;
9668 env->me_dbflags[dbi] = 0;
9669 env->me_dbiseqs[dbi]++;
9674 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9676 /* We could return the flags for the FREE_DBI too but what's the point? */
9677 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9679 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9683 /** Add all the DB's pages to the free list.
9684 * @param[in] mc Cursor on the DB to free.
9685 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9686 * @return 0 on success, non-zero on failure.
9689 mdb_drop0(MDB_cursor *mc, int subs)
9693 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9694 if (rc == MDB_SUCCESS) {
9695 MDB_txn *txn = mc->mc_txn;
9700 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
9701 * This also avoids any P_LEAF2 pages, which have no nodes.
9702 * Also if the DB doesn't have sub-DBs and has no overflow
9703 * pages, omit scanning leaves.
9705 if ((mc->mc_flags & C_SUB) ||
9706 (!subs && !mc->mc_db->md_overflow_pages))
9709 mdb_cursor_copy(mc, &mx);
9710 while (mc->mc_snum > 0) {
9711 MDB_page *mp = mc->mc_pg[mc->mc_top];
9712 unsigned n = NUMKEYS(mp);
9714 for (i=0; i<n; i++) {
9715 ni = NODEPTR(mp, i);
9716 if (ni->mn_flags & F_BIGDATA) {
9719 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9720 rc = mdb_page_get(mc, pg, &omp, NULL);
9723 mdb_cassert(mc, IS_OVERFLOW(omp));
9724 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9728 mc->mc_db->md_overflow_pages -= omp->mp_pages;
9729 if (!mc->mc_db->md_overflow_pages && !subs)
9731 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9732 mdb_xcursor_init1(mc, ni);
9733 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9738 if (!subs && !mc->mc_db->md_overflow_pages)
9741 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9743 for (i=0; i<n; i++) {
9745 ni = NODEPTR(mp, i);
9748 mdb_midl_xappend(txn->mt_free_pgs, pg);
9753 mc->mc_ki[mc->mc_top] = i;
9754 rc = mdb_cursor_sibling(mc, 1);
9756 if (rc != MDB_NOTFOUND)
9758 /* no more siblings, go back to beginning
9759 * of previous level.
9764 for (i=1; i<mc->mc_snum; i++) {
9766 mc->mc_pg[i] = mx.mc_pg[i];
9771 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9774 txn->mt_flags |= MDB_TXN_ERROR;
9775 } else if (rc == MDB_NOTFOUND) {
9778 mc->mc_flags &= ~C_INITIALIZED;
9782 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9784 MDB_cursor *mc, *m2;
9787 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9790 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9793 if (TXN_DBI_CHANGED(txn, dbi))
9796 rc = mdb_cursor_open(txn, dbi, &mc);
9800 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9801 /* Invalidate the dropped DB's cursors */
9802 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9803 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9807 /* Can't delete the main DB */
9808 if (del && dbi >= CORE_DBS) {
9809 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
9811 txn->mt_dbflags[dbi] = DB_STALE;
9812 mdb_dbi_close(txn->mt_env, dbi);
9814 txn->mt_flags |= MDB_TXN_ERROR;
9817 /* reset the DB record, mark it dirty */
9818 txn->mt_dbflags[dbi] |= DB_DIRTY;
9819 txn->mt_dbs[dbi].md_depth = 0;
9820 txn->mt_dbs[dbi].md_branch_pages = 0;
9821 txn->mt_dbs[dbi].md_leaf_pages = 0;
9822 txn->mt_dbs[dbi].md_overflow_pages = 0;
9823 txn->mt_dbs[dbi].md_entries = 0;
9824 txn->mt_dbs[dbi].md_root = P_INVALID;
9826 txn->mt_flags |= MDB_TXN_DIRTY;
9829 mdb_cursor_close(mc);
9833 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9835 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9838 txn->mt_dbxs[dbi].md_cmp = cmp;
9842 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9844 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9847 txn->mt_dbxs[dbi].md_dcmp = cmp;
9851 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9853 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9856 txn->mt_dbxs[dbi].md_rel = rel;
9860 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9862 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9865 txn->mt_dbxs[dbi].md_relctx = ctx;
9870 mdb_env_get_maxkeysize(MDB_env *env)
9872 return ENV_MAXKEY(env);
9876 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9878 unsigned int i, rdrs;
9881 int rc = 0, first = 1;
9885 if (!env->me_txns) {
9886 return func("(no reader locks)\n", ctx);
9888 rdrs = env->me_txns->mti_numreaders;
9889 mr = env->me_txns->mti_readers;
9890 for (i=0; i<rdrs; i++) {
9892 txnid_t txnid = mr[i].mr_txnid;
9893 sprintf(buf, txnid == (txnid_t)-1 ?
9894 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9895 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9898 rc = func(" pid thread txnid\n", ctx);
9902 rc = func(buf, ctx);
9908 rc = func("(no active readers)\n", ctx);
9913 /** Insert pid into list if not already present.
9914 * return -1 if already present.
9917 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9919 /* binary search of pid in list */
9921 unsigned cursor = 1;
9923 unsigned n = ids[0];
9926 unsigned pivot = n >> 1;
9927 cursor = base + pivot + 1;
9928 val = pid - ids[cursor];
9933 } else if ( val > 0 ) {
9938 /* found, so it's a duplicate */
9947 for (n = ids[0]; n > cursor; n--)
9954 mdb_reader_check(MDB_env *env, int *dead)
9960 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
9963 /** As #mdb_reader_check(). rlocked = <caller locked the reader mutex>. */
9965 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
9967 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
9968 unsigned int i, j, rdrs;
9970 MDB_PID_T *pids, pid;
9971 int rc = MDB_SUCCESS, count = 0;
9973 rdrs = env->me_txns->mti_numreaders;
9974 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
9978 mr = env->me_txns->mti_readers;
9979 for (i=0; i<rdrs; i++) {
9981 if (pid && pid != env->me_pid) {
9982 if (mdb_pid_insert(pids, pid) == 0) {
9983 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9984 /* Stale reader found */
9987 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
9988 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
9990 rdrs = 0; /* the above checked all readers */
9992 /* Recheck, a new process may have reused pid */
9993 if (mdb_reader_pid(env, Pidcheck, pid))
9998 if (mr[j].mr_pid == pid) {
9999 DPRINTF(("clear stale reader pid %u txn %"Z"d",
10000 (unsigned) pid, mr[j].mr_txnid));
10005 UNLOCK_MUTEX(rmutex);
10016 #ifdef MDB_ROBUST_SUPPORTED
10017 /** Handle #LOCK_MUTEX0() failure.
10018 * Try to repair the lock file if the mutex owner died.
10019 * @param[in] env the environment handle
10020 * @param[in] mutex LOCK_MUTEX0() mutex
10021 * @param[in] rc LOCK_MUTEX0() error (nonzero)
10022 * @return 0 on success with the mutex locked, or an error code on failure.
10025 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10030 if (rc == MDB_OWNERDEAD) {
10031 /* We own the mutex. Clean up after dead previous owner. */
10033 rlocked = (mutex == env->me_rmutex);
10035 /* Keep mti_txnid updated, otherwise next writer can
10036 * overwrite data which latest meta page refers to.
10038 meta = mdb_env_pick_meta(env);
10039 env->me_txns->mti_txnid = meta->mm_txnid;
10040 /* env is hosed if the dead thread was ours */
10042 env->me_flags |= MDB_FATAL_ERROR;
10043 env->me_txn = NULL;
10047 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
10048 (rc ? "this process' env is hosed" : "recovering")));
10049 rc2 = mdb_reader_check0(env, rlocked, NULL);
10051 rc2 = mdb_mutex_consistent(mutex);
10052 if (rc || (rc = rc2)) {
10053 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
10054 UNLOCK_MUTEX(mutex);
10060 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
10065 #endif /* MDB_ROBUST_SUPPORTED */
10068 #if defined(_WIN32)
10069 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize)
10073 need = MultiByteToWideChar(CP_UTF8, 0, src, srcsize, NULL, 0);
10074 if (need == 0xFFFD)
10078 result = malloc(sizeof(wchar_t) * need);
10081 MultiByteToWideChar(CP_UTF8, 0, src, srcsize, result, need);
10087 #endif /* defined(_WIN32) */