2 * @brief Lightning memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2015 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
41 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
42 * as int64 which is wrong. MSVC doesn't define it at all, so just
46 #define MDB_THR_T DWORD
47 #include <sys/types.h>
50 # include <sys/param.h>
52 # define LITTLE_ENDIAN 1234
53 # define BIG_ENDIAN 4321
54 # define BYTE_ORDER LITTLE_ENDIAN
56 # define SSIZE_MAX INT_MAX
60 #include <sys/types.h>
62 #define MDB_PID_T pid_t
63 #define MDB_THR_T pthread_t
64 #include <sys/param.h>
67 #ifdef HAVE_SYS_FILE_H
73 #if defined(__mips) && defined(__linux)
74 /* MIPS has cache coherency issues, requires explicit cache control */
75 #include <asm/cachectl.h>
76 extern int cacheflush(char *addr, int nbytes, int cache);
77 #define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
79 #define CACHEFLUSH(addr, bytes, cache)
82 #if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
83 /** fdatasync is broken on ext3/ext4fs on older kernels, see
84 * description in #mdb_env_open2 comments. You can safely
85 * define MDB_FDATASYNC_WORKS if this code will only be run
86 * on kernels 3.6 and newer.
88 #define BROKEN_FDATASYNC
102 typedef SSIZE_T ssize_t;
107 #if defined(__sun) || defined(ANDROID)
108 /* Most platforms have posix_memalign, older may only have memalign */
109 #define HAVE_MEMALIGN 1
113 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
114 #include <netinet/in.h>
115 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
118 #if defined(__APPLE__) || defined (BSD)
119 # define MDB_USE_POSIX_SEM 1
120 # define MDB_FDATASYNC fsync
121 #elif defined(ANDROID)
122 # define MDB_FDATASYNC fsync
127 #ifdef MDB_USE_POSIX_SEM
128 # define MDB_USE_HASH 1
129 #include <semaphore.h>
131 #define MDB_USE_POSIX_MUTEX 1
135 #if defined(_WIN32) + defined(MDB_USE_POSIX_SEM) \
136 + defined(MDB_USE_POSIX_MUTEX) != 1
137 # error "Ambiguous shared-lock implementation"
141 #include <valgrind/memcheck.h>
142 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
143 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
144 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
145 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
146 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
148 #define VGMEMP_CREATE(h,r,z)
149 #define VGMEMP_ALLOC(h,a,s)
150 #define VGMEMP_FREE(h,a)
151 #define VGMEMP_DESTROY(h)
152 #define VGMEMP_DEFINED(a,s)
156 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
157 /* Solaris just defines one or the other */
158 # define LITTLE_ENDIAN 1234
159 # define BIG_ENDIAN 4321
160 # ifdef _LITTLE_ENDIAN
161 # define BYTE_ORDER LITTLE_ENDIAN
163 # define BYTE_ORDER BIG_ENDIAN
166 # define BYTE_ORDER __BYTE_ORDER
170 #ifndef LITTLE_ENDIAN
171 #define LITTLE_ENDIAN __LITTLE_ENDIAN
174 #define BIG_ENDIAN __BIG_ENDIAN
177 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
178 #define MISALIGNED_OK 1
184 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
185 # error "Unknown or unsupported endianness (BYTE_ORDER)"
186 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
187 # error "Two's complement, reasonably sized integer types, please"
191 /** Put infrequently used env functions in separate section */
193 # define ESECT __attribute__ ((section("__TEXT,text_env")))
195 # define ESECT __attribute__ ((section("text_env")))
202 #define CALL_CONV WINAPI
207 /** @defgroup internal LMDB Internals
210 /** @defgroup compat Compatibility Macros
211 * A bunch of macros to minimize the amount of platform-specific ifdefs
212 * needed throughout the rest of the code. When the features this library
213 * needs are similar enough to POSIX to be hidden in a one-or-two line
214 * replacement, this macro approach is used.
218 /** Features under development */
223 /** Wrapper around __func__, which is a C99 feature */
224 #if __STDC_VERSION__ >= 199901L
225 # define mdb_func_ __func__
226 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
227 # define mdb_func_ __FUNCTION__
229 /* If a debug message says <mdb_unknown>(), update the #if statements above */
230 # define mdb_func_ "<mdb_unknown>"
233 /* Internal error codes, not exposed outside liblmdb */
234 #define MDB_NO_ROOT (MDB_LAST_ERRCODE + 10)
236 #define MDB_OWNERDEAD ((int) WAIT_ABANDONED)
237 #elif defined(MDB_USE_POSIX_MUTEX) && defined(EOWNERDEAD)
238 #define MDB_OWNERDEAD EOWNERDEAD /**< #LOCK_MUTEX0() result if dead owner */
242 #define MDB_ROBUST_SUPPORTED 1
246 #define MDB_USE_HASH 1
247 #define MDB_PIDLOCK 0
248 #define THREAD_RET DWORD
249 #define pthread_t HANDLE
250 #define pthread_mutex_t HANDLE
251 #define pthread_cond_t HANDLE
252 typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
253 #define pthread_key_t DWORD
254 #define pthread_self() GetCurrentThreadId()
255 #define pthread_key_create(x,y) \
256 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
257 #define pthread_key_delete(x) TlsFree(x)
258 #define pthread_getspecific(x) TlsGetValue(x)
259 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
260 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
261 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
262 #define pthread_cond_signal(x) SetEvent(*x)
263 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
264 #define THREAD_CREATE(thr,start,arg) thr=CreateThread(NULL,0,start,arg,0,NULL)
265 #define THREAD_FINISH(thr) WaitForSingleObject(thr, INFINITE)
266 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
267 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
268 #define mdb_mutex_consistent(mutex) 0
269 #define getpid() GetCurrentProcessId()
270 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
271 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
272 #define ErrCode() GetLastError()
273 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
274 #define close(fd) (CloseHandle(fd) ? 0 : -1)
275 #define munmap(ptr,len) UnmapViewOfFile(ptr)
276 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
277 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
279 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
283 #define THREAD_RET void *
284 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
285 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
286 #define Z "z" /**< printf format modifier for size_t */
288 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
289 #define MDB_PIDLOCK 1
291 #ifdef MDB_USE_POSIX_SEM
293 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
294 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
295 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
298 mdb_sem_wait(sem_t *sem)
301 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
305 #else /* MDB_USE_POSIX_MUTEX: */
306 /** Shared mutex/semaphore as it is stored (mdb_mutex_t), and as
307 * local variables keep it (mdb_mutexref_t).
309 * When #mdb_mutexref_t is a pointer declaration and #mdb_mutex_t is
310 * not, then it is array[size 1] so it can be assigned to a pointer.
313 typedef pthread_mutex_t mdb_mutex_t[1], *mdb_mutexref_t;
315 /** Lock the reader or writer mutex.
316 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
318 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
319 /** Unlock the reader or writer mutex.
321 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
322 /** Mark mutex-protected data as repaired, after death of previous owner.
324 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
325 #endif /* MDB_USE_POSIX_SEM */
327 /** Get the error code for the last failed system function.
329 #define ErrCode() errno
331 /** An abstraction for a file handle.
332 * On POSIX systems file handles are small integers. On Windows
333 * they're opaque pointers.
337 /** A value for an invalid file handle.
338 * Mainly used to initialize file variables and signify that they are
341 #define INVALID_HANDLE_VALUE (-1)
343 /** Get the size of a memory page for the system.
344 * This is the basic size that the platform's memory manager uses, and is
345 * fundamental to the use of memory-mapped files.
347 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
350 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
353 #define MNAME_LEN (sizeof(pthread_mutex_t))
358 #ifdef MDB_ROBUST_SUPPORTED
359 /** Lock mutex, handle any error, set rc = result.
360 * Return 0 on success, nonzero (not rc) on error.
362 #define LOCK_MUTEX(rc, env, mutex) \
363 (((rc) = LOCK_MUTEX0(mutex)) && \
364 ((rc) = mdb_mutex_failed(env, mutex, rc)))
365 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
367 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
368 #define mdb_mutex_failed(env, mutex, rc) (rc)
372 /** A flag for opening a file and requesting synchronous data writes.
373 * This is only used when writing a meta page. It's not strictly needed;
374 * we could just do a normal write and then immediately perform a flush.
375 * But if this flag is available it saves us an extra system call.
377 * @note If O_DSYNC is undefined but exists in /usr/include,
378 * preferably set some compiler flag to get the definition.
379 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
382 # define MDB_DSYNC O_DSYNC
386 /** Function for flushing the data of a file. Define this to fsync
387 * if fdatasync() is not supported.
389 #ifndef MDB_FDATASYNC
390 # define MDB_FDATASYNC fdatasync
394 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
405 /** A page number in the database.
406 * Note that 64 bit page numbers are overkill, since pages themselves
407 * already represent 12-13 bits of addressable memory, and the OS will
408 * always limit applications to a maximum of 63 bits of address space.
410 * @note In the #MDB_node structure, we only store 48 bits of this value,
411 * which thus limits us to only 60 bits of addressable data.
413 typedef MDB_ID pgno_t;
415 /** A transaction ID.
416 * See struct MDB_txn.mt_txnid for details.
418 typedef MDB_ID txnid_t;
420 /** @defgroup debug Debug Macros
424 /** Enable debug output. Needs variable argument macros (a C99 feature).
425 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
426 * read from and written to the database (used for free space management).
432 static int mdb_debug;
433 static txnid_t mdb_debug_start;
435 /** Print a debug message with printf formatting.
436 * Requires double parenthesis around 2 or more args.
438 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
439 # define DPRINTF0(fmt, ...) \
440 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
442 # define DPRINTF(args) ((void) 0)
444 /** Print a debug string.
445 * The string is printed literally, with no format processing.
447 #define DPUTS(arg) DPRINTF(("%s", arg))
448 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
450 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
453 /** @brief The maximum size of a database page.
455 * It is 32k or 64k, since value-PAGEBASE must fit in
456 * #MDB_page.%mp_upper.
458 * LMDB will use database pages < OS pages if needed.
459 * That causes more I/O in write transactions: The OS must
460 * know (read) the whole page before writing a partial page.
462 * Note that we don't currently support Huge pages. On Linux,
463 * regular data files cannot use Huge pages, and in general
464 * Huge pages aren't actually pageable. We rely on the OS
465 * demand-pager to read our data and page it out when memory
466 * pressure from other processes is high. So until OSs have
467 * actual paging support for Huge pages, they're not viable.
469 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
471 /** The minimum number of keys required in a database page.
472 * Setting this to a larger value will place a smaller bound on the
473 * maximum size of a data item. Data items larger than this size will
474 * be pushed into overflow pages instead of being stored directly in
475 * the B-tree node. This value used to default to 4. With a page size
476 * of 4096 bytes that meant that any item larger than 1024 bytes would
477 * go into an overflow page. That also meant that on average 2-3KB of
478 * each overflow page was wasted space. The value cannot be lower than
479 * 2 because then there would no longer be a tree structure. With this
480 * value, items larger than 2KB will go into overflow pages, and on
481 * average only 1KB will be wasted.
483 #define MDB_MINKEYS 2
485 /** A stamp that identifies a file as an LMDB file.
486 * There's nothing special about this value other than that it is easily
487 * recognizable, and it will reflect any byte order mismatches.
489 #define MDB_MAGIC 0xBEEFC0DE
491 /** The version number for a database's datafile format. */
492 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
493 /** The version number for a database's lockfile format. */
494 #define MDB_LOCK_VERSION 1
496 /** @brief The max size of a key we can write, or 0 for computed max.
498 * This macro should normally be left alone or set to 0.
499 * Note that a database with big keys or dupsort data cannot be
500 * reliably modified by a liblmdb which uses a smaller max.
501 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
503 * Other values are allowed, for backwards compat. However:
504 * A value bigger than the computed max can break if you do not
505 * know what you are doing, and liblmdb <= 0.9.10 can break when
506 * modifying a DB with keys/dupsort data bigger than its max.
508 * Data items in an #MDB_DUPSORT database are also limited to
509 * this size, since they're actually keys of a sub-DB. Keys and
510 * #MDB_DUPSORT data items must fit on a node in a regular page.
512 #ifndef MDB_MAXKEYSIZE
513 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
516 /** The maximum size of a key we can write to the environment. */
518 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
520 #define ENV_MAXKEY(env) ((env)->me_maxkey)
523 /** @brief The maximum size of a data item.
525 * We only store a 32 bit value for node sizes.
527 #define MAXDATASIZE 0xffffffffUL
530 /** Key size which fits in a #DKBUF.
533 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
536 * This is used for printing a hex dump of a key's contents.
538 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
539 /** Display a key in hex.
541 * Invoke a function to display a key in hex.
543 #define DKEY(x) mdb_dkey(x, kbuf)
549 /** An invalid page number.
550 * Mainly used to denote an empty tree.
552 #define P_INVALID (~(pgno_t)0)
554 /** Test if the flags \b f are set in a flag word \b w. */
555 #define F_ISSET(w, f) (((w) & (f)) == (f))
557 /** Round \b n up to an even number. */
558 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
560 /** Used for offsets within a single page.
561 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
564 typedef uint16_t indx_t;
566 /** Default size of memory map.
567 * This is certainly too small for any actual applications. Apps should always set
568 * the size explicitly using #mdb_env_set_mapsize().
570 #define DEFAULT_MAPSIZE 1048576
572 /** @defgroup readers Reader Lock Table
573 * Readers don't acquire any locks for their data access. Instead, they
574 * simply record their transaction ID in the reader table. The reader
575 * mutex is needed just to find an empty slot in the reader table. The
576 * slot's address is saved in thread-specific data so that subsequent read
577 * transactions started by the same thread need no further locking to proceed.
579 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
581 * No reader table is used if the database is on a read-only filesystem, or
582 * if #MDB_NOLOCK is set.
584 * Since the database uses multi-version concurrency control, readers don't
585 * actually need any locking. This table is used to keep track of which
586 * readers are using data from which old transactions, so that we'll know
587 * when a particular old transaction is no longer in use. Old transactions
588 * that have discarded any data pages can then have those pages reclaimed
589 * for use by a later write transaction.
591 * The lock table is constructed such that reader slots are aligned with the
592 * processor's cache line size. Any slot is only ever used by one thread.
593 * This alignment guarantees that there will be no contention or cache
594 * thrashing as threads update their own slot info, and also eliminates
595 * any need for locking when accessing a slot.
597 * A writer thread will scan every slot in the table to determine the oldest
598 * outstanding reader transaction. Any freed pages older than this will be
599 * reclaimed by the writer. The writer doesn't use any locks when scanning
600 * this table. This means that there's no guarantee that the writer will
601 * see the most up-to-date reader info, but that's not required for correct
602 * operation - all we need is to know the upper bound on the oldest reader,
603 * we don't care at all about the newest reader. So the only consequence of
604 * reading stale information here is that old pages might hang around a
605 * while longer before being reclaimed. That's actually good anyway, because
606 * the longer we delay reclaiming old pages, the more likely it is that a
607 * string of contiguous pages can be found after coalescing old pages from
608 * many old transactions together.
611 /** Number of slots in the reader table.
612 * This value was chosen somewhat arbitrarily. 126 readers plus a
613 * couple mutexes fit exactly into 8KB on my development machine.
614 * Applications should set the table size using #mdb_env_set_maxreaders().
616 #define DEFAULT_READERS 126
618 /** The size of a CPU cache line in bytes. We want our lock structures
619 * aligned to this size to avoid false cache line sharing in the
621 * This value works for most CPUs. For Itanium this should be 128.
627 /** The information we store in a single slot of the reader table.
628 * In addition to a transaction ID, we also record the process and
629 * thread ID that owns a slot, so that we can detect stale information,
630 * e.g. threads or processes that went away without cleaning up.
631 * @note We currently don't check for stale records. We simply re-init
632 * the table when we know that we're the only process opening the
635 typedef struct MDB_rxbody {
636 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
637 * Multiple readers that start at the same time will probably have the
638 * same ID here. Again, it's not important to exclude them from
639 * anything; all we need to know is which version of the DB they
640 * started from so we can avoid overwriting any data used in that
641 * particular version.
643 volatile txnid_t mrb_txnid;
644 /** The process ID of the process owning this reader txn. */
645 volatile MDB_PID_T mrb_pid;
646 /** The thread ID of the thread owning this txn. */
647 volatile MDB_THR_T mrb_tid;
650 /** The actual reader record, with cacheline padding. */
651 typedef struct MDB_reader {
654 /** shorthand for mrb_txnid */
655 #define mr_txnid mru.mrx.mrb_txnid
656 #define mr_pid mru.mrx.mrb_pid
657 #define mr_tid mru.mrx.mrb_tid
658 /** cache line alignment */
659 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
663 /** The header for the reader table.
664 * The table resides in a memory-mapped file. (This is a different file
665 * than is used for the main database.)
667 * For POSIX the actual mutexes reside in the shared memory of this
668 * mapped file. On Windows, mutexes are named objects allocated by the
669 * kernel; we store the mutex names in this mapped file so that other
670 * processes can grab them. This same approach is also used on
671 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
672 * process-shared POSIX mutexes. For these cases where a named object
673 * is used, the object name is derived from a 64 bit FNV hash of the
674 * environment pathname. As such, naming collisions are extremely
675 * unlikely. If a collision occurs, the results are unpredictable.
677 typedef struct MDB_txbody {
678 /** Stamp identifying this as an LMDB file. It must be set
681 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
683 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
684 char mtb_rmname[MNAME_LEN];
686 /** Mutex protecting access to this table.
687 * This is the reader table lock used with LOCK_MUTEX().
689 mdb_mutex_t mtb_rmutex;
691 /** The ID of the last transaction committed to the database.
692 * This is recorded here only for convenience; the value can always
693 * be determined by reading the main database meta pages.
695 volatile txnid_t mtb_txnid;
696 /** The number of slots that have been used in the reader table.
697 * This always records the maximum count, it is not decremented
698 * when readers release their slots.
700 volatile unsigned mtb_numreaders;
703 /** The actual reader table definition. */
704 typedef struct MDB_txninfo {
707 #define mti_magic mt1.mtb.mtb_magic
708 #define mti_format mt1.mtb.mtb_format
709 #define mti_rmutex mt1.mtb.mtb_rmutex
710 #define mti_rmname mt1.mtb.mtb_rmname
711 #define mti_txnid mt1.mtb.mtb_txnid
712 #define mti_numreaders mt1.mtb.mtb_numreaders
713 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
716 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
717 char mt2_wmname[MNAME_LEN];
718 #define mti_wmname mt2.mt2_wmname
720 mdb_mutex_t mt2_wmutex;
721 #define mti_wmutex mt2.mt2_wmutex
723 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
725 MDB_reader mti_readers[1];
728 /** Lockfile format signature: version, features and field layout */
729 #define MDB_LOCK_FORMAT \
731 ((MDB_LOCK_VERSION) \
732 /* Flags which describe functionality */ \
733 + (((MDB_PIDLOCK) != 0) << 16)))
736 /** Common header for all page types.
737 * Overflow records occupy a number of contiguous pages with no
738 * headers on any page after the first.
740 typedef struct MDB_page {
741 #define mp_pgno mp_p.p_pgno
742 #define mp_next mp_p.p_next
744 pgno_t p_pgno; /**< page number */
745 struct MDB_page *p_next; /**< for in-memory list of freed pages */
748 /** @defgroup mdb_page Page Flags
750 * Flags for the page headers.
753 #define P_BRANCH 0x01 /**< branch page */
754 #define P_LEAF 0x02 /**< leaf page */
755 #define P_OVERFLOW 0x04 /**< overflow page */
756 #define P_META 0x08 /**< meta page */
757 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
758 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
759 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
760 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
761 #define P_KEEP 0x8000 /**< leave this page alone during spill */
763 uint16_t mp_flags; /**< @ref mdb_page */
764 #define mp_lower mp_pb.pb.pb_lower
765 #define mp_upper mp_pb.pb.pb_upper
766 #define mp_pages mp_pb.pb_pages
769 indx_t pb_lower; /**< lower bound of free space */
770 indx_t pb_upper; /**< upper bound of free space */
772 uint32_t pb_pages; /**< number of overflow pages */
774 indx_t mp_ptrs[1]; /**< dynamic size */
777 /** Size of the page header, excluding dynamic data at the end */
778 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
780 /** Address of first usable data byte in a page, after the header */
781 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
783 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
784 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
786 /** Number of nodes on a page */
787 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
789 /** The amount of space remaining in the page */
790 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
792 /** The percentage of space used in the page, in tenths of a percent. */
793 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
794 ((env)->me_psize - PAGEHDRSZ))
795 /** The minimum page fill factor, in tenths of a percent.
796 * Pages emptier than this are candidates for merging.
798 #define FILL_THRESHOLD 250
800 /** Test if a page is a leaf page */
801 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
802 /** Test if a page is a LEAF2 page */
803 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
804 /** Test if a page is a branch page */
805 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
806 /** Test if a page is an overflow page */
807 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
808 /** Test if a page is a sub page */
809 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
811 /** The number of overflow pages needed to store the given size. */
812 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
814 /** Link in #MDB_txn.%mt_loose_pgs list */
815 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
817 /** Header for a single key/data pair within a page.
818 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
819 * We guarantee 2-byte alignment for 'MDB_node's.
821 typedef struct MDB_node {
822 /** lo and hi are used for data size on leaf nodes and for
823 * child pgno on branch nodes. On 64 bit platforms, flags
824 * is also used for pgno. (Branch nodes have no flags).
825 * They are in host byte order in case that lets some
826 * accesses be optimized into a 32-bit word access.
828 #if BYTE_ORDER == LITTLE_ENDIAN
829 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
831 unsigned short mn_hi, mn_lo;
833 /** @defgroup mdb_node Node Flags
835 * Flags for node headers.
838 #define F_BIGDATA 0x01 /**< data put on overflow page */
839 #define F_SUBDATA 0x02 /**< data is a sub-database */
840 #define F_DUPDATA 0x04 /**< data has duplicates */
842 /** valid flags for #mdb_node_add() */
843 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
846 unsigned short mn_flags; /**< @ref mdb_node */
847 unsigned short mn_ksize; /**< key size */
848 char mn_data[1]; /**< key and data are appended here */
851 /** Size of the node header, excluding dynamic data at the end */
852 #define NODESIZE offsetof(MDB_node, mn_data)
854 /** Bit position of top word in page number, for shifting mn_flags */
855 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
857 /** Size of a node in a branch page with a given key.
858 * This is just the node header plus the key, there is no data.
860 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
862 /** Size of a node in a leaf page with a given key and data.
863 * This is node header plus key plus data size.
865 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
867 /** Address of node \b i in page \b p */
868 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
870 /** Address of the key for the node */
871 #define NODEKEY(node) (void *)((node)->mn_data)
873 /** Address of the data for a node */
874 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
876 /** Get the page number pointed to by a branch node */
877 #define NODEPGNO(node) \
878 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
879 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
880 /** Set the page number in a branch node */
881 #define SETPGNO(node,pgno) do { \
882 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
883 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
885 /** Get the size of the data in a leaf node */
886 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
887 /** Set the size of the data for a leaf node */
888 #define SETDSZ(node,size) do { \
889 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
890 /** The size of a key in a node */
891 #define NODEKSZ(node) ((node)->mn_ksize)
893 /** Copy a page number from src to dst */
895 #define COPY_PGNO(dst,src) dst = src
897 #if SIZE_MAX > 4294967295UL
898 #define COPY_PGNO(dst,src) do { \
899 unsigned short *s, *d; \
900 s = (unsigned short *)&(src); \
901 d = (unsigned short *)&(dst); \
908 #define COPY_PGNO(dst,src) do { \
909 unsigned short *s, *d; \
910 s = (unsigned short *)&(src); \
911 d = (unsigned short *)&(dst); \
917 /** The address of a key in a LEAF2 page.
918 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
919 * There are no node headers, keys are stored contiguously.
921 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
923 /** Set the \b node's key into \b keyptr, if requested. */
924 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
925 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
927 /** Set the \b node's key into \b key. */
928 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
930 /** Information about a single database in the environment. */
931 typedef struct MDB_db {
932 uint32_t md_pad; /**< also ksize for LEAF2 pages */
933 uint16_t md_flags; /**< @ref mdb_dbi_open */
934 uint16_t md_depth; /**< depth of this tree */
935 pgno_t md_branch_pages; /**< number of internal pages */
936 pgno_t md_leaf_pages; /**< number of leaf pages */
937 pgno_t md_overflow_pages; /**< number of overflow pages */
938 size_t md_entries; /**< number of data items */
939 pgno_t md_root; /**< the root page of this tree */
942 /** mdb_dbi_open flags */
943 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
944 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
945 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
946 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
948 /** Handle for the DB used to track free pages. */
950 /** Handle for the default DB. */
952 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
955 /** Number of meta pages - also hardcoded elsewhere */
958 /** Meta page content.
959 * A meta page is the start point for accessing a database snapshot.
960 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
962 typedef struct MDB_meta {
963 /** Stamp identifying this as an LMDB file. It must be set
966 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
968 void *mm_address; /**< address for fixed mapping */
969 size_t mm_mapsize; /**< size of mmap region */
970 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
971 /** The size of pages used in this DB */
972 #define mm_psize mm_dbs[FREE_DBI].md_pad
973 /** Any persistent environment flags. @ref mdb_env */
974 #define mm_flags mm_dbs[FREE_DBI].md_flags
975 pgno_t mm_last_pg; /**< last used page in file */
976 volatile txnid_t mm_txnid; /**< txnid that committed this page */
979 /** Buffer for a stack-allocated meta page.
980 * The members define size and alignment, and silence type
981 * aliasing warnings. They are not used directly; that could
982 * mean incorrectly using several union members in parallel.
984 typedef union MDB_metabuf {
987 char mm_pad[PAGEHDRSZ];
992 /** Auxiliary DB info.
993 * The information here is mostly static/read-only. There is
994 * only a single copy of this record in the environment.
996 typedef struct MDB_dbx {
997 MDB_val md_name; /**< name of the database */
998 MDB_cmp_func *md_cmp; /**< function for comparing keys */
999 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1000 MDB_rel_func *md_rel; /**< user relocate function */
1001 void *md_relctx; /**< user-provided context for md_rel */
1004 /** A database transaction.
1005 * Every operation requires a transaction handle.
1008 MDB_txn *mt_parent; /**< parent of a nested txn */
1009 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1011 pgno_t mt_next_pgno; /**< next unallocated page */
1012 /** The ID of this transaction. IDs are integers incrementing from 1.
1013 * Only committed write transactions increment the ID. If a transaction
1014 * aborts, the ID may be re-used by the next writer.
1017 MDB_env *mt_env; /**< the DB environment */
1018 /** The list of pages that became unused during this transaction.
1020 MDB_IDL mt_free_pgs;
1021 /** The list of loose pages that became unused and may be reused
1022 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1024 MDB_page *mt_loose_pgs;
1025 /* #Number of loose pages (#mt_loose_pgs) */
1027 /** The sorted list of dirty pages we temporarily wrote to disk
1028 * because the dirty list was full. page numbers in here are
1029 * shifted left by 1, deleted slots have the LSB set.
1031 MDB_IDL mt_spill_pgs;
1033 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1034 MDB_ID2L dirty_list;
1035 /** For read txns: This thread/txn's reader table slot, or NULL. */
1038 /** Array of records for each DB known in the environment. */
1040 /** Array of MDB_db records for each known DB */
1042 /** Array of sequence numbers for each DB handle */
1043 unsigned int *mt_dbiseqs;
1044 /** @defgroup mt_dbflag Transaction DB Flags
1048 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
1049 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1050 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1051 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1052 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1054 /** In write txns, array of cursors for each DB */
1055 MDB_cursor **mt_cursors;
1056 /** Array of flags for each DB */
1057 unsigned char *mt_dbflags;
1058 /** Number of DB records in use, or 0 when the txn is finished.
1059 * This number only ever increments until the txn finishes; we
1060 * don't decrement it when individual DB handles are closed.
1064 /** @defgroup mdb_txn Transaction Flags
1068 /** #mdb_txn_begin() flags */
1069 #define MDB_TXN_BEGIN_FLAGS MDB_RDONLY
1070 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1071 /* internal txn flags */
1072 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1073 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1074 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1075 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1076 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1077 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1078 /** most operations on the txn are currently illegal */
1079 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1081 unsigned int mt_flags; /**< @ref mdb_txn */
1082 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1083 * Includes ancestor txns' dirty pages not hidden by other txns'
1084 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1085 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1087 unsigned int mt_dirty_room;
1090 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1091 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1092 * raise this on a 64 bit machine.
1094 #define CURSOR_STACK 32
1098 /** Cursors are used for all DB operations.
1099 * A cursor holds a path of (page pointer, key index) from the DB
1100 * root to a position in the DB, plus other state. #MDB_DUPSORT
1101 * cursors include an xcursor to the current data item. Write txns
1102 * track their cursors and keep them up to date when data moves.
1103 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1104 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1107 /** Next cursor on this DB in this txn */
1108 MDB_cursor *mc_next;
1109 /** Backup of the original cursor if this cursor is a shadow */
1110 MDB_cursor *mc_backup;
1111 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1112 struct MDB_xcursor *mc_xcursor;
1113 /** The transaction that owns this cursor */
1115 /** The database handle this cursor operates on */
1117 /** The database record for this cursor */
1119 /** The database auxiliary record for this cursor */
1121 /** The @ref mt_dbflag for this database */
1122 unsigned char *mc_dbflag;
1123 unsigned short mc_snum; /**< number of pushed pages */
1124 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1125 /** @defgroup mdb_cursor Cursor Flags
1127 * Cursor state flags.
1130 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1131 #define C_EOF 0x02 /**< No more data */
1132 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1133 #define C_DEL 0x08 /**< last op was a cursor_del */
1134 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
1135 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1137 unsigned int mc_flags; /**< @ref mdb_cursor */
1138 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1139 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1142 /** Context for sorted-dup records.
1143 * We could have gone to a fully recursive design, with arbitrarily
1144 * deep nesting of sub-databases. But for now we only handle these
1145 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1147 typedef struct MDB_xcursor {
1148 /** A sub-cursor for traversing the Dup DB */
1149 MDB_cursor mx_cursor;
1150 /** The database record for this Dup DB */
1152 /** The auxiliary DB record for this Dup DB */
1154 /** The @ref mt_dbflag for this Dup DB */
1155 unsigned char mx_dbflag;
1158 /** State of FreeDB old pages, stored in the MDB_env */
1159 typedef struct MDB_pgstate {
1160 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1161 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1164 /** The database environment. */
1166 HANDLE me_fd; /**< The main data file */
1167 HANDLE me_lfd; /**< The lock file */
1168 HANDLE me_mfd; /**< just for writing the meta pages */
1169 /** Failed to update the meta page. Probably an I/O error. */
1170 #define MDB_FATAL_ERROR 0x80000000U
1171 /** Some fields are initialized. */
1172 #define MDB_ENV_ACTIVE 0x20000000U
1173 /** me_txkey is set */
1174 #define MDB_ENV_TXKEY 0x10000000U
1175 /** fdatasync is unreliable */
1176 #define MDB_FSYNCONLY 0x08000000U
1177 uint32_t me_flags; /**< @ref mdb_env */
1178 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1179 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1180 unsigned int me_maxreaders; /**< size of the reader table */
1181 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1182 volatile int me_close_readers;
1183 MDB_dbi me_numdbs; /**< number of DBs opened */
1184 MDB_dbi me_maxdbs; /**< size of the DB table */
1185 MDB_PID_T me_pid; /**< process ID of this env */
1186 char *me_path; /**< path to the DB files */
1187 char *me_map; /**< the memory map of the data file */
1188 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1189 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1190 void *me_pbuf; /**< scratch area for DUPSORT put() */
1191 MDB_txn *me_txn; /**< current write transaction */
1192 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1193 size_t me_mapsize; /**< size of the data memory map */
1194 off_t me_size; /**< current file size */
1195 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1196 MDB_dbx *me_dbxs; /**< array of static DB info */
1197 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1198 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1199 pthread_key_t me_txkey; /**< thread-key for readers */
1200 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1201 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1202 # define me_pglast me_pgstate.mf_pglast
1203 # define me_pghead me_pgstate.mf_pghead
1204 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1205 /** IDL of pages that became unused in a write txn */
1206 MDB_IDL me_free_pgs;
1207 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1208 MDB_ID2L me_dirty_list;
1209 /** Max number of freelist items that can fit in a single overflow page */
1211 /** Max size of a node on a page */
1212 unsigned int me_nodemax;
1213 #if !(MDB_MAXKEYSIZE)
1214 unsigned int me_maxkey; /**< max size of a key */
1216 int me_live_reader; /**< have liveness lock in reader table */
1218 int me_pidquery; /**< Used in OpenProcess */
1220 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1221 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1222 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1224 mdb_mutex_t me_rmutex;
1225 mdb_mutex_t me_wmutex;
1227 void *me_userctx; /**< User-settable context */
1228 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1231 /** Nested transaction */
1232 typedef struct MDB_ntxn {
1233 MDB_txn mnt_txn; /**< the transaction */
1234 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1237 /** max number of pages to commit in one writev() call */
1238 #define MDB_COMMIT_PAGES 64
1239 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1240 #undef MDB_COMMIT_PAGES
1241 #define MDB_COMMIT_PAGES IOV_MAX
1244 /** max bytes to write in one call */
1245 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1247 /** Check \b txn and \b dbi arguments to a function */
1248 #define TXN_DBI_EXIST(txn, dbi, validity) \
1249 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1251 /** Check for misused \b dbi handles */
1252 #define TXN_DBI_CHANGED(txn, dbi) \
1253 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1255 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1256 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1257 static int mdb_page_touch(MDB_cursor *mc);
1259 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1260 "reset-tmp", "fail-begin", "fail-beginchild"}
1262 /* mdb_txn_end operation number, for logging */
1263 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1264 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1266 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1267 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1268 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1269 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1270 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1272 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1273 static int mdb_page_search_root(MDB_cursor *mc,
1274 MDB_val *key, int modify);
1275 #define MDB_PS_MODIFY 1
1276 #define MDB_PS_ROOTONLY 2
1277 #define MDB_PS_FIRST 4
1278 #define MDB_PS_LAST 8
1279 static int mdb_page_search(MDB_cursor *mc,
1280 MDB_val *key, int flags);
1281 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1283 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1284 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1285 pgno_t newpgno, unsigned int nflags);
1287 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1288 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1289 static int mdb_env_write_meta(MDB_txn *txn);
1290 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1291 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1293 static void mdb_env_close0(MDB_env *env, int excl);
1295 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1296 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1297 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1298 static void mdb_node_del(MDB_cursor *mc, int ksize);
1299 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1300 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1301 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1302 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1303 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1305 static int mdb_rebalance(MDB_cursor *mc);
1306 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1308 static void mdb_cursor_pop(MDB_cursor *mc);
1309 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1311 static int mdb_cursor_del0(MDB_cursor *mc);
1312 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1313 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1314 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1315 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1316 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1318 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1319 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1321 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1322 static void mdb_xcursor_init0(MDB_cursor *mc);
1323 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1324 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1326 static int mdb_drop0(MDB_cursor *mc, int subs);
1327 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1328 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1331 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1334 /** Compare two items pointing at size_t's of unknown alignment. */
1335 #ifdef MISALIGNED_OK
1336 # define mdb_cmp_clong mdb_cmp_long
1338 # define mdb_cmp_clong mdb_cmp_cint
1342 static SECURITY_DESCRIPTOR mdb_null_sd;
1343 static SECURITY_ATTRIBUTES mdb_all_sa;
1344 static int mdb_sec_inited;
1347 /** Return the library version info. */
1349 mdb_version(int *major, int *minor, int *patch)
1351 if (major) *major = MDB_VERSION_MAJOR;
1352 if (minor) *minor = MDB_VERSION_MINOR;
1353 if (patch) *patch = MDB_VERSION_PATCH;
1354 return MDB_VERSION_STRING;
1357 /** Table of descriptions for LMDB @ref errors */
1358 static char *const mdb_errstr[] = {
1359 "MDB_KEYEXIST: Key/data pair already exists",
1360 "MDB_NOTFOUND: No matching key/data pair found",
1361 "MDB_PAGE_NOTFOUND: Requested page not found",
1362 "MDB_CORRUPTED: Located page was wrong type",
1363 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1364 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1365 "MDB_INVALID: File is not an LMDB file",
1366 "MDB_MAP_FULL: Environment mapsize limit reached",
1367 "MDB_DBS_FULL: Environment maxdbs limit reached",
1368 "MDB_READERS_FULL: Environment maxreaders limit reached",
1369 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1370 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1371 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1372 "MDB_PAGE_FULL: Internal error - page has no more space",
1373 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1374 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1375 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1376 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1377 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1378 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1382 mdb_strerror(int err)
1385 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1386 * This works as long as no function between the call to mdb_strerror
1387 * and the actual use of the message uses more than 4K of stack.
1390 char buf[1024], *ptr = buf;
1394 return ("Successful return: 0");
1396 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1397 i = err - MDB_KEYEXIST;
1398 return mdb_errstr[i];
1402 /* These are the C-runtime error codes we use. The comment indicates
1403 * their numeric value, and the Win32 error they would correspond to
1404 * if the error actually came from a Win32 API. A major mess, we should
1405 * have used LMDB-specific error codes for everything.
1408 case ENOENT: /* 2, FILE_NOT_FOUND */
1409 case EIO: /* 5, ACCESS_DENIED */
1410 case ENOMEM: /* 12, INVALID_ACCESS */
1411 case EACCES: /* 13, INVALID_DATA */
1412 case EBUSY: /* 16, CURRENT_DIRECTORY */
1413 case EINVAL: /* 22, BAD_COMMAND */
1414 case ENOSPC: /* 28, OUT_OF_PAPER */
1415 return strerror(err);
1420 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1421 FORMAT_MESSAGE_IGNORE_INSERTS,
1422 NULL, err, 0, ptr, sizeof(buf), (va_list *)pad);
1425 return strerror(err);
1429 /** assert(3) variant in cursor context */
1430 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1431 /** assert(3) variant in transaction context */
1432 #define mdb_tassert(mc, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1433 /** assert(3) variant in environment context */
1434 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1437 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1438 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1441 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1442 const char *func, const char *file, int line)
1445 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1446 file, line, expr_txt, func);
1447 if (env->me_assert_func)
1448 env->me_assert_func(env, buf);
1449 fprintf(stderr, "%s\n", buf);
1453 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1457 /** Return the page number of \b mp which may be sub-page, for debug output */
1459 mdb_dbg_pgno(MDB_page *mp)
1462 COPY_PGNO(ret, mp->mp_pgno);
1466 /** Display a key in hexadecimal and return the address of the result.
1467 * @param[in] key the key to display
1468 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1469 * @return The key in hexadecimal form.
1472 mdb_dkey(MDB_val *key, char *buf)
1475 unsigned char *c = key->mv_data;
1481 if (key->mv_size > DKBUF_MAXKEYSIZE)
1482 return "MDB_MAXKEYSIZE";
1483 /* may want to make this a dynamic check: if the key is mostly
1484 * printable characters, print it as-is instead of converting to hex.
1488 for (i=0; i<key->mv_size; i++)
1489 ptr += sprintf(ptr, "%02x", *c++);
1491 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1497 mdb_leafnode_type(MDB_node *n)
1499 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1500 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1501 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1504 /** Display all the keys in the page. */
1506 mdb_page_list(MDB_page *mp)
1508 pgno_t pgno = mdb_dbg_pgno(mp);
1509 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1511 unsigned int i, nkeys, nsize, total = 0;
1515 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1516 case P_BRANCH: type = "Branch page"; break;
1517 case P_LEAF: type = "Leaf page"; break;
1518 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1519 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1520 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1522 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1523 pgno, mp->mp_pages, state);
1526 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1527 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1530 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1534 nkeys = NUMKEYS(mp);
1535 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1537 for (i=0; i<nkeys; i++) {
1538 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1539 key.mv_size = nsize = mp->mp_pad;
1540 key.mv_data = LEAF2KEY(mp, i, nsize);
1542 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1545 node = NODEPTR(mp, i);
1546 key.mv_size = node->mn_ksize;
1547 key.mv_data = node->mn_data;
1548 nsize = NODESIZE + key.mv_size;
1549 if (IS_BRANCH(mp)) {
1550 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1554 if (F_ISSET(node->mn_flags, F_BIGDATA))
1555 nsize += sizeof(pgno_t);
1557 nsize += NODEDSZ(node);
1559 nsize += sizeof(indx_t);
1560 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1561 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1563 total = EVEN(total);
1565 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1566 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1570 mdb_cursor_chk(MDB_cursor *mc)
1576 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1577 for (i=0; i<mc->mc_top; i++) {
1579 node = NODEPTR(mp, mc->mc_ki[i]);
1580 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1583 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1589 /** Count all the pages in each DB and in the freelist
1590 * and make sure it matches the actual number of pages
1592 * All named DBs must be open for a correct count.
1594 static void mdb_audit(MDB_txn *txn)
1598 MDB_ID freecount, count;
1603 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1604 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1605 freecount += *(MDB_ID *)data.mv_data;
1606 mdb_tassert(txn, rc == MDB_NOTFOUND);
1609 for (i = 0; i<txn->mt_numdbs; i++) {
1611 if (!(txn->mt_dbflags[i] & DB_VALID))
1613 mdb_cursor_init(&mc, txn, i, &mx);
1614 if (txn->mt_dbs[i].md_root == P_INVALID)
1616 count += txn->mt_dbs[i].md_branch_pages +
1617 txn->mt_dbs[i].md_leaf_pages +
1618 txn->mt_dbs[i].md_overflow_pages;
1619 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1620 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1621 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1624 mp = mc.mc_pg[mc.mc_top];
1625 for (j=0; j<NUMKEYS(mp); j++) {
1626 MDB_node *leaf = NODEPTR(mp, j);
1627 if (leaf->mn_flags & F_SUBDATA) {
1629 memcpy(&db, NODEDATA(leaf), sizeof(db));
1630 count += db.md_branch_pages + db.md_leaf_pages +
1631 db.md_overflow_pages;
1635 mdb_tassert(txn, rc == MDB_NOTFOUND);
1638 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1639 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1640 txn->mt_txnid, freecount, count+NUM_METAS,
1641 freecount+count+NUM_METAS, txn->mt_next_pgno);
1647 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1649 return txn->mt_dbxs[dbi].md_cmp(a, b);
1653 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1655 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1656 #if UINT_MAX < SIZE_MAX
1657 if (dcmp == mdb_cmp_int && a->mv_size == sizeof(size_t))
1658 dcmp = mdb_cmp_clong;
1663 /** Allocate memory for a page.
1664 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1667 mdb_page_malloc(MDB_txn *txn, unsigned num)
1669 MDB_env *env = txn->mt_env;
1670 MDB_page *ret = env->me_dpages;
1671 size_t psize = env->me_psize, sz = psize, off;
1672 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1673 * For a single page alloc, we init everything after the page header.
1674 * For multi-page, we init the final page; if the caller needed that
1675 * many pages they will be filling in at least up to the last page.
1679 VGMEMP_ALLOC(env, ret, sz);
1680 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1681 env->me_dpages = ret->mp_next;
1684 psize -= off = PAGEHDRSZ;
1689 if ((ret = malloc(sz)) != NULL) {
1690 VGMEMP_ALLOC(env, ret, sz);
1691 if (!(env->me_flags & MDB_NOMEMINIT)) {
1692 memset((char *)ret + off, 0, psize);
1696 txn->mt_flags |= MDB_TXN_ERROR;
1700 /** Free a single page.
1701 * Saves single pages to a list, for future reuse.
1702 * (This is not used for multi-page overflow pages.)
1705 mdb_page_free(MDB_env *env, MDB_page *mp)
1707 mp->mp_next = env->me_dpages;
1708 VGMEMP_FREE(env, mp);
1709 env->me_dpages = mp;
1712 /** Free a dirty page */
1714 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1716 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1717 mdb_page_free(env, dp);
1719 /* large pages just get freed directly */
1720 VGMEMP_FREE(env, dp);
1725 /** Return all dirty pages to dpage list */
1727 mdb_dlist_free(MDB_txn *txn)
1729 MDB_env *env = txn->mt_env;
1730 MDB_ID2L dl = txn->mt_u.dirty_list;
1731 unsigned i, n = dl[0].mid;
1733 for (i = 1; i <= n; i++) {
1734 mdb_dpage_free(env, dl[i].mptr);
1739 /** Loosen or free a single page.
1740 * Saves single pages to a list for future reuse
1741 * in this same txn. It has been pulled from the freeDB
1742 * and already resides on the dirty list, but has been
1743 * deleted. Use these pages first before pulling again
1746 * If the page wasn't dirtied in this txn, just add it
1747 * to this txn's free list.
1750 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1753 pgno_t pgno = mp->mp_pgno;
1754 MDB_txn *txn = mc->mc_txn;
1756 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1757 if (txn->mt_parent) {
1758 MDB_ID2 *dl = txn->mt_u.dirty_list;
1759 /* If txn has a parent, make sure the page is in our
1763 unsigned x = mdb_mid2l_search(dl, pgno);
1764 if (x <= dl[0].mid && dl[x].mid == pgno) {
1765 if (mp != dl[x].mptr) { /* bad cursor? */
1766 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1767 txn->mt_flags |= MDB_TXN_ERROR;
1768 return MDB_CORRUPTED;
1775 /* no parent txn, so it's just ours */
1780 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1782 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1783 txn->mt_loose_pgs = mp;
1784 txn->mt_loose_count++;
1785 mp->mp_flags |= P_LOOSE;
1787 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1795 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1796 * @param[in] mc A cursor handle for the current operation.
1797 * @param[in] pflags Flags of the pages to update:
1798 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1799 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1800 * @return 0 on success, non-zero on failure.
1803 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1805 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1806 MDB_txn *txn = mc->mc_txn;
1812 int rc = MDB_SUCCESS, level;
1814 /* Mark pages seen by cursors */
1815 if (mc->mc_flags & C_UNTRACK)
1816 mc = NULL; /* will find mc in mt_cursors */
1817 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1818 for (; mc; mc=mc->mc_next) {
1819 if (!(mc->mc_flags & C_INITIALIZED))
1821 for (m3 = mc;; m3 = &mx->mx_cursor) {
1823 for (j=0; j<m3->mc_snum; j++) {
1825 if ((mp->mp_flags & Mask) == pflags)
1826 mp->mp_flags ^= P_KEEP;
1828 mx = m3->mc_xcursor;
1829 /* Proceed to mx if it is at a sub-database */
1830 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1832 if (! (mp && (mp->mp_flags & P_LEAF)))
1834 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1835 if (!(leaf->mn_flags & F_SUBDATA))
1844 /* Mark dirty root pages */
1845 for (i=0; i<txn->mt_numdbs; i++) {
1846 if (txn->mt_dbflags[i] & DB_DIRTY) {
1847 pgno_t pgno = txn->mt_dbs[i].md_root;
1848 if (pgno == P_INVALID)
1850 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1852 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1853 dp->mp_flags ^= P_KEEP;
1861 static int mdb_page_flush(MDB_txn *txn, int keep);
1863 /** Spill pages from the dirty list back to disk.
1864 * This is intended to prevent running into #MDB_TXN_FULL situations,
1865 * but note that they may still occur in a few cases:
1866 * 1) our estimate of the txn size could be too small. Currently this
1867 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1868 * 2) child txns may run out of space if their parents dirtied a
1869 * lot of pages and never spilled them. TODO: we probably should do
1870 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1871 * the parent's dirty_room is below a given threshold.
1873 * Otherwise, if not using nested txns, it is expected that apps will
1874 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1875 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1876 * If the txn never references them again, they can be left alone.
1877 * If the txn only reads them, they can be used without any fuss.
1878 * If the txn writes them again, they can be dirtied immediately without
1879 * going thru all of the work of #mdb_page_touch(). Such references are
1880 * handled by #mdb_page_unspill().
1882 * Also note, we never spill DB root pages, nor pages of active cursors,
1883 * because we'll need these back again soon anyway. And in nested txns,
1884 * we can't spill a page in a child txn if it was already spilled in a
1885 * parent txn. That would alter the parent txns' data even though
1886 * the child hasn't committed yet, and we'd have no way to undo it if
1887 * the child aborted.
1889 * @param[in] m0 cursor A cursor handle identifying the transaction and
1890 * database for which we are checking space.
1891 * @param[in] key For a put operation, the key being stored.
1892 * @param[in] data For a put operation, the data being stored.
1893 * @return 0 on success, non-zero on failure.
1896 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1898 MDB_txn *txn = m0->mc_txn;
1900 MDB_ID2L dl = txn->mt_u.dirty_list;
1901 unsigned int i, j, need;
1904 if (m0->mc_flags & C_SUB)
1907 /* Estimate how much space this op will take */
1908 i = m0->mc_db->md_depth;
1909 /* Named DBs also dirty the main DB */
1910 if (m0->mc_dbi >= CORE_DBS)
1911 i += txn->mt_dbs[MAIN_DBI].md_depth;
1912 /* For puts, roughly factor in the key+data size */
1914 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1915 i += i; /* double it for good measure */
1918 if (txn->mt_dirty_room > i)
1921 if (!txn->mt_spill_pgs) {
1922 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1923 if (!txn->mt_spill_pgs)
1926 /* purge deleted slots */
1927 MDB_IDL sl = txn->mt_spill_pgs;
1928 unsigned int num = sl[0];
1930 for (i=1; i<=num; i++) {
1937 /* Preserve pages which may soon be dirtied again */
1938 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1941 /* Less aggressive spill - we originally spilled the entire dirty list,
1942 * with a few exceptions for cursor pages and DB root pages. But this
1943 * turns out to be a lot of wasted effort because in a large txn many
1944 * of those pages will need to be used again. So now we spill only 1/8th
1945 * of the dirty pages. Testing revealed this to be a good tradeoff,
1946 * better than 1/2, 1/4, or 1/10.
1948 if (need < MDB_IDL_UM_MAX / 8)
1949 need = MDB_IDL_UM_MAX / 8;
1951 /* Save the page IDs of all the pages we're flushing */
1952 /* flush from the tail forward, this saves a lot of shifting later on. */
1953 for (i=dl[0].mid; i && need; i--) {
1954 MDB_ID pn = dl[i].mid << 1;
1956 if (dp->mp_flags & (P_LOOSE|P_KEEP))
1958 /* Can't spill twice, make sure it's not already in a parent's
1961 if (txn->mt_parent) {
1963 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1964 if (tx2->mt_spill_pgs) {
1965 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1966 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1967 dp->mp_flags |= P_KEEP;
1975 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1979 mdb_midl_sort(txn->mt_spill_pgs);
1981 /* Flush the spilled part of dirty list */
1982 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1985 /* Reset any dirty pages we kept that page_flush didn't see */
1986 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1989 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1993 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1995 mdb_find_oldest(MDB_txn *txn)
1998 txnid_t mr, oldest = txn->mt_txnid - 1;
1999 if (txn->mt_env->me_txns) {
2000 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2001 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2012 /** Add a page to the txn's dirty list */
2014 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2017 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2019 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2020 insert = mdb_mid2l_append;
2022 insert = mdb_mid2l_insert;
2024 mid.mid = mp->mp_pgno;
2026 rc = insert(txn->mt_u.dirty_list, &mid);
2027 mdb_tassert(txn, rc == 0);
2028 txn->mt_dirty_room--;
2031 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2032 * me_pghead and mt_next_pgno.
2034 * If there are free pages available from older transactions, they
2035 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2036 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2037 * and move me_pglast to say which records were consumed. Only this
2038 * function can create me_pghead and move me_pglast/mt_next_pgno.
2039 * @param[in] mc cursor A cursor handle identifying the transaction and
2040 * database for which we are allocating.
2041 * @param[in] num the number of pages to allocate.
2042 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2043 * will always be satisfied by a single contiguous chunk of memory.
2044 * @return 0 on success, non-zero on failure.
2047 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2049 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2050 /* Get at most <Max_retries> more freeDB records once me_pghead
2051 * has enough pages. If not enough, use new pages from the map.
2052 * If <Paranoid> and mc is updating the freeDB, only get new
2053 * records if me_pghead is empty. Then the freelist cannot play
2054 * catch-up with itself by growing while trying to save it.
2056 enum { Paranoid = 1, Max_retries = 500 };
2058 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2060 int rc, retry = num * 60;
2061 MDB_txn *txn = mc->mc_txn;
2062 MDB_env *env = txn->mt_env;
2063 pgno_t pgno, *mop = env->me_pghead;
2064 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2066 txnid_t oldest = 0, last;
2071 /* If there are any loose pages, just use them */
2072 if (num == 1 && txn->mt_loose_pgs) {
2073 np = txn->mt_loose_pgs;
2074 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2075 txn->mt_loose_count--;
2076 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
2084 /* If our dirty list is already full, we can't do anything */
2085 if (txn->mt_dirty_room == 0) {
2090 for (op = MDB_FIRST;; op = MDB_NEXT) {
2095 /* Seek a big enough contiguous page range. Prefer
2096 * pages at the tail, just truncating the list.
2102 if (mop[i-n2] == pgno+n2)
2109 if (op == MDB_FIRST) { /* 1st iteration */
2110 /* Prepare to fetch more and coalesce */
2111 last = env->me_pglast;
2112 oldest = env->me_pgoldest;
2113 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2116 key.mv_data = &last; /* will look up last+1 */
2117 key.mv_size = sizeof(last);
2119 if (Paranoid && mc->mc_dbi == FREE_DBI)
2122 if (Paranoid && retry < 0 && mop_len)
2126 /* Do not fetch more if the record will be too recent */
2127 if (oldest <= last) {
2129 oldest = mdb_find_oldest(txn);
2130 env->me_pgoldest = oldest;
2136 rc = mdb_cursor_get(&m2, &key, NULL, op);
2138 if (rc == MDB_NOTFOUND)
2142 last = *(txnid_t*)key.mv_data;
2143 if (oldest <= last) {
2145 oldest = mdb_find_oldest(txn);
2146 env->me_pgoldest = oldest;
2152 np = m2.mc_pg[m2.mc_top];
2153 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2154 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
2157 idl = (MDB_ID *) data.mv_data;
2160 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2165 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2167 mop = env->me_pghead;
2169 env->me_pglast = last;
2171 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2172 last, txn->mt_dbs[FREE_DBI].md_root, i));
2174 DPRINTF(("IDL %"Z"u", idl[j]));
2176 /* Merge in descending sorted order */
2177 mdb_midl_xmerge(mop, idl);
2181 /* Use new pages from the map when nothing suitable in the freeDB */
2183 pgno = txn->mt_next_pgno;
2184 if (pgno + num >= env->me_maxpg) {
2185 DPUTS("DB size maxed out");
2191 if (env->me_flags & MDB_WRITEMAP) {
2192 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2194 if (!(np = mdb_page_malloc(txn, num))) {
2200 mop[0] = mop_len -= num;
2201 /* Move any stragglers down */
2202 for (j = i-num; j < mop_len; )
2203 mop[++j] = mop[++i];
2205 txn->mt_next_pgno = pgno + num;
2208 mdb_page_dirty(txn, np);
2214 txn->mt_flags |= MDB_TXN_ERROR;
2218 /** Copy the used portions of a non-overflow page.
2219 * @param[in] dst page to copy into
2220 * @param[in] src page to copy from
2221 * @param[in] psize size of a page
2224 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2226 enum { Align = sizeof(pgno_t) };
2227 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2229 /* If page isn't full, just copy the used portion. Adjust
2230 * alignment so memcpy may copy words instead of bytes.
2232 if ((unused &= -Align) && !IS_LEAF2(src)) {
2233 upper = (upper + PAGEBASE) & -Align;
2234 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2235 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2238 memcpy(dst, src, psize - unused);
2242 /** Pull a page off the txn's spill list, if present.
2243 * If a page being referenced was spilled to disk in this txn, bring
2244 * it back and make it dirty/writable again.
2245 * @param[in] txn the transaction handle.
2246 * @param[in] mp the page being referenced. It must not be dirty.
2247 * @param[out] ret the writable page, if any. ret is unchanged if
2248 * mp wasn't spilled.
2251 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2253 MDB_env *env = txn->mt_env;
2256 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2258 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2259 if (!tx2->mt_spill_pgs)
2261 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2262 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2265 if (txn->mt_dirty_room == 0)
2266 return MDB_TXN_FULL;
2267 if (IS_OVERFLOW(mp))
2271 if (env->me_flags & MDB_WRITEMAP) {
2274 np = mdb_page_malloc(txn, num);
2278 memcpy(np, mp, num * env->me_psize);
2280 mdb_page_copy(np, mp, env->me_psize);
2283 /* If in current txn, this page is no longer spilled.
2284 * If it happens to be the last page, truncate the spill list.
2285 * Otherwise mark it as deleted by setting the LSB.
2287 if (x == txn->mt_spill_pgs[0])
2288 txn->mt_spill_pgs[0]--;
2290 txn->mt_spill_pgs[x] |= 1;
2291 } /* otherwise, if belonging to a parent txn, the
2292 * page remains spilled until child commits
2295 mdb_page_dirty(txn, np);
2296 np->mp_flags |= P_DIRTY;
2304 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2305 * @param[in] mc cursor pointing to the page to be touched
2306 * @return 0 on success, non-zero on failure.
2309 mdb_page_touch(MDB_cursor *mc)
2311 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2312 MDB_txn *txn = mc->mc_txn;
2313 MDB_cursor *m2, *m3;
2317 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2318 if (txn->mt_flags & MDB_TXN_SPILLS) {
2320 rc = mdb_page_unspill(txn, mp, &np);
2326 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2327 (rc = mdb_page_alloc(mc, 1, &np)))
2330 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2331 mp->mp_pgno, pgno));
2332 mdb_cassert(mc, mp->mp_pgno != pgno);
2333 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2334 /* Update the parent page, if any, to point to the new page */
2336 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2337 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2338 SETPGNO(node, pgno);
2340 mc->mc_db->md_root = pgno;
2342 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2343 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2345 /* If txn has a parent, make sure the page is in our
2349 unsigned x = mdb_mid2l_search(dl, pgno);
2350 if (x <= dl[0].mid && dl[x].mid == pgno) {
2351 if (mp != dl[x].mptr) { /* bad cursor? */
2352 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2353 txn->mt_flags |= MDB_TXN_ERROR;
2354 return MDB_CORRUPTED;
2359 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2361 np = mdb_page_malloc(txn, 1);
2366 rc = mdb_mid2l_insert(dl, &mid);
2367 mdb_cassert(mc, rc == 0);
2372 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2374 np->mp_flags |= P_DIRTY;
2377 /* Adjust cursors pointing to mp */
2378 mc->mc_pg[mc->mc_top] = np;
2379 m2 = txn->mt_cursors[mc->mc_dbi];
2380 if (mc->mc_flags & C_SUB) {
2381 for (; m2; m2=m2->mc_next) {
2382 m3 = &m2->mc_xcursor->mx_cursor;
2383 if (m3->mc_snum < mc->mc_snum) continue;
2384 if (m3->mc_pg[mc->mc_top] == mp)
2385 m3->mc_pg[mc->mc_top] = np;
2388 for (; m2; m2=m2->mc_next) {
2389 if (m2->mc_snum < mc->mc_snum) continue;
2390 if (m2->mc_pg[mc->mc_top] == mp) {
2391 m2->mc_pg[mc->mc_top] = np;
2392 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2394 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2396 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2397 if (!(leaf->mn_flags & F_SUBDATA))
2398 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2406 txn->mt_flags |= MDB_TXN_ERROR;
2411 mdb_env_sync(MDB_env *env, int force)
2414 if (env->me_flags & MDB_RDONLY)
2416 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2417 if (env->me_flags & MDB_WRITEMAP) {
2418 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2419 ? MS_ASYNC : MS_SYNC;
2420 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2423 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2427 #ifdef BROKEN_FDATASYNC
2428 if (env->me_flags & MDB_FSYNCONLY) {
2429 if (fsync(env->me_fd))
2433 if (MDB_FDATASYNC(env->me_fd))
2440 /** Back up parent txn's cursors, then grab the originals for tracking */
2442 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2444 MDB_cursor *mc, *bk;
2449 for (i = src->mt_numdbs; --i >= 0; ) {
2450 if ((mc = src->mt_cursors[i]) != NULL) {
2451 size = sizeof(MDB_cursor);
2453 size += sizeof(MDB_xcursor);
2454 for (; mc; mc = bk->mc_next) {
2460 mc->mc_db = &dst->mt_dbs[i];
2461 /* Kill pointers into src - and dst to reduce abuse: The
2462 * user may not use mc until dst ends. Otherwise we'd...
2464 mc->mc_txn = NULL; /* ...set this to dst */
2465 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2466 if ((mx = mc->mc_xcursor) != NULL) {
2467 *(MDB_xcursor *)(bk+1) = *mx;
2468 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2470 mc->mc_next = dst->mt_cursors[i];
2471 dst->mt_cursors[i] = mc;
2478 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2479 * @param[in] txn the transaction handle.
2480 * @param[in] merge true to keep changes to parent cursors, false to revert.
2481 * @return 0 on success, non-zero on failure.
2484 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2486 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2490 for (i = txn->mt_numdbs; --i >= 0; ) {
2491 for (mc = cursors[i]; mc; mc = next) {
2493 if ((bk = mc->mc_backup) != NULL) {
2495 /* Commit changes to parent txn */
2496 mc->mc_next = bk->mc_next;
2497 mc->mc_backup = bk->mc_backup;
2498 mc->mc_txn = bk->mc_txn;
2499 mc->mc_db = bk->mc_db;
2500 mc->mc_dbflag = bk->mc_dbflag;
2501 if ((mx = mc->mc_xcursor) != NULL)
2502 mx->mx_cursor.mc_txn = bk->mc_txn;
2504 /* Abort nested txn */
2506 if ((mx = mc->mc_xcursor) != NULL)
2507 *mx = *(MDB_xcursor *)(bk+1);
2511 /* Only malloced cursors are permanently tracked. */
2518 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2524 Pidset = F_SETLK, Pidcheck = F_GETLK
2528 /** Set or check a pid lock. Set returns 0 on success.
2529 * Check returns 0 if the process is certainly dead, nonzero if it may
2530 * be alive (the lock exists or an error happened so we do not know).
2532 * On Windows Pidset is a no-op, we merely check for the existence
2533 * of the process with the given pid. On POSIX we use a single byte
2534 * lock on the lockfile, set at an offset equal to the pid.
2537 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2539 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2542 if (op == Pidcheck) {
2543 h = OpenProcess(env->me_pidquery, FALSE, pid);
2544 /* No documented "no such process" code, but other program use this: */
2546 return ErrCode() != ERROR_INVALID_PARAMETER;
2547 /* A process exists until all handles to it close. Has it exited? */
2548 ret = WaitForSingleObject(h, 0) != 0;
2555 struct flock lock_info;
2556 memset(&lock_info, 0, sizeof(lock_info));
2557 lock_info.l_type = F_WRLCK;
2558 lock_info.l_whence = SEEK_SET;
2559 lock_info.l_start = pid;
2560 lock_info.l_len = 1;
2561 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2562 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2564 } else if ((rc = ErrCode()) == EINTR) {
2572 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2573 * @param[in] txn the transaction handle to initialize
2574 * @return 0 on success, non-zero on failure.
2577 mdb_txn_renew0(MDB_txn *txn)
2579 MDB_env *env = txn->mt_env;
2580 MDB_txninfo *ti = env->me_txns;
2582 unsigned int i, nr, flags = txn->mt_flags;
2584 int rc, new_notls = 0;
2586 if ((flags &= MDB_TXN_RDONLY) != 0) {
2588 meta = mdb_env_pick_meta(env);
2589 txn->mt_txnid = meta->mm_txnid;
2590 txn->mt_u.reader = NULL;
2592 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2593 pthread_getspecific(env->me_txkey);
2595 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2596 return MDB_BAD_RSLOT;
2598 MDB_PID_T pid = env->me_pid;
2599 MDB_THR_T tid = pthread_self();
2600 mdb_mutexref_t rmutex = env->me_rmutex;
2602 if (!env->me_live_reader) {
2603 rc = mdb_reader_pid(env, Pidset, pid);
2606 env->me_live_reader = 1;
2609 if (LOCK_MUTEX(rc, env, rmutex))
2611 nr = ti->mti_numreaders;
2612 for (i=0; i<nr; i++)
2613 if (ti->mti_readers[i].mr_pid == 0)
2615 if (i == env->me_maxreaders) {
2616 UNLOCK_MUTEX(rmutex);
2617 return MDB_READERS_FULL;
2619 r = &ti->mti_readers[i];
2620 /* Claim the reader slot, carefully since other code
2621 * uses the reader table un-mutexed: First reset the
2622 * slot, next publish it in mti_numreaders. After
2623 * that, it is safe for mdb_env_close() to touch it.
2624 * When it will be closed, we can finally claim it.
2627 r->mr_txnid = (txnid_t)-1;
2630 ti->mti_numreaders = ++nr;
2631 env->me_close_readers = nr;
2633 UNLOCK_MUTEX(rmutex);
2635 new_notls = (env->me_flags & MDB_NOTLS);
2636 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2641 do /* LY: Retry on a race, ITS#7970. */
2642 r->mr_txnid = ti->mti_txnid;
2643 while(r->mr_txnid != ti->mti_txnid);
2644 txn->mt_txnid = r->mr_txnid;
2645 txn->mt_u.reader = r;
2646 meta = env->me_metas[txn->mt_txnid & 1];
2650 /* Not yet touching txn == env->me_txn0, it may be active */
2652 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2654 txn->mt_txnid = ti->mti_txnid;
2655 meta = env->me_metas[txn->mt_txnid & 1];
2657 meta = mdb_env_pick_meta(env);
2658 txn->mt_txnid = meta->mm_txnid;
2662 if (txn->mt_txnid == mdb_debug_start)
2665 txn->mt_child = NULL;
2666 txn->mt_loose_pgs = NULL;
2667 txn->mt_loose_count = 0;
2668 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2669 txn->mt_u.dirty_list = env->me_dirty_list;
2670 txn->mt_u.dirty_list[0].mid = 0;
2671 txn->mt_free_pgs = env->me_free_pgs;
2672 txn->mt_free_pgs[0] = 0;
2673 txn->mt_spill_pgs = NULL;
2675 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2678 /* Copy the DB info and flags */
2679 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
2681 /* Moved to here to avoid a data race in read TXNs */
2682 txn->mt_next_pgno = meta->mm_last_pg+1;
2684 txn->mt_flags = flags;
2687 txn->mt_numdbs = env->me_numdbs;
2688 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
2689 x = env->me_dbflags[i];
2690 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2691 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
2693 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
2694 txn->mt_dbflags[FREE_DBI] = DB_VALID;
2696 if (env->me_flags & MDB_FATAL_ERROR) {
2697 DPUTS("environment had fatal error, must shutdown!");
2699 } else if (env->me_maxpg < txn->mt_next_pgno) {
2700 rc = MDB_MAP_RESIZED;
2704 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
2709 mdb_txn_renew(MDB_txn *txn)
2713 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
2716 rc = mdb_txn_renew0(txn);
2717 if (rc == MDB_SUCCESS) {
2718 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2719 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2720 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2726 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2730 int rc, size, tsize;
2732 flags &= MDB_TXN_BEGIN_FLAGS;
2733 flags |= env->me_flags & MDB_WRITEMAP;
2735 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
2739 /* Nested transactions: Max 1 child, write txns only, no writemap */
2740 flags |= parent->mt_flags;
2741 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
2742 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2744 /* Child txns save MDB_pgstate and use own copy of cursors */
2745 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
2746 size += tsize = sizeof(MDB_ntxn);
2747 } else if (flags & MDB_RDONLY) {
2748 size = env->me_maxdbs * (sizeof(MDB_db)+1);
2749 size += tsize = sizeof(MDB_txn);
2751 /* Reuse preallocated write txn. However, do not touch it until
2752 * mdb_txn_renew0() succeeds, since it currently may be active.
2757 if ((txn = calloc(1, size)) == NULL) {
2758 DPRINTF(("calloc: %s", strerror(errno)));
2761 txn->mt_dbxs = env->me_dbxs; /* static */
2762 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2763 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
2764 txn->mt_flags = flags;
2769 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2770 txn->mt_dbiseqs = parent->mt_dbiseqs;
2771 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2772 if (!txn->mt_u.dirty_list ||
2773 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2775 free(txn->mt_u.dirty_list);
2779 txn->mt_txnid = parent->mt_txnid;
2780 txn->mt_dirty_room = parent->mt_dirty_room;
2781 txn->mt_u.dirty_list[0].mid = 0;
2782 txn->mt_spill_pgs = NULL;
2783 txn->mt_next_pgno = parent->mt_next_pgno;
2784 parent->mt_flags |= MDB_TXN_HAS_CHILD;
2785 parent->mt_child = txn;
2786 txn->mt_parent = parent;
2787 txn->mt_numdbs = parent->mt_numdbs;
2788 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2789 /* Copy parent's mt_dbflags, but clear DB_NEW */
2790 for (i=0; i<txn->mt_numdbs; i++)
2791 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2793 ntxn = (MDB_ntxn *)txn;
2794 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2795 if (env->me_pghead) {
2796 size = MDB_IDL_SIZEOF(env->me_pghead);
2797 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2799 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2804 rc = mdb_cursor_shadow(parent, txn);
2806 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
2807 } else { /* MDB_RDONLY */
2808 txn->mt_dbiseqs = env->me_dbiseqs;
2810 rc = mdb_txn_renew0(txn);
2813 if (txn != env->me_txn0)
2816 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
2818 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2819 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
2820 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2827 mdb_txn_env(MDB_txn *txn)
2829 if(!txn) return NULL;
2834 mdb_txn_id(MDB_txn *txn)
2837 return txn->mt_txnid;
2840 /** Export or close DBI handles opened in this txn. */
2842 mdb_dbis_update(MDB_txn *txn, int keep)
2845 MDB_dbi n = txn->mt_numdbs;
2846 MDB_env *env = txn->mt_env;
2847 unsigned char *tdbflags = txn->mt_dbflags;
2849 for (i = n; --i >= CORE_DBS;) {
2850 if (tdbflags[i] & DB_NEW) {
2852 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2854 char *ptr = env->me_dbxs[i].md_name.mv_data;
2856 env->me_dbxs[i].md_name.mv_data = NULL;
2857 env->me_dbxs[i].md_name.mv_size = 0;
2858 env->me_dbflags[i] = 0;
2859 env->me_dbiseqs[i]++;
2865 if (keep && env->me_numdbs < n)
2869 /** End a transaction, except successful commit of a nested transaction.
2870 * May be called twice for readonly txns: First reset it, then abort.
2871 * @param[in] txn the transaction handle to end
2872 * @param[in] mode why and how to end the transaction
2875 mdb_txn_end(MDB_txn *txn, unsigned mode)
2877 MDB_env *env = txn->mt_env;
2879 static const char *const names[] = MDB_END_NAMES;
2882 /* Export or close DBI handles opened in this txn */
2883 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
2885 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2886 names[mode & MDB_END_OPMASK],
2887 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2888 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2890 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2891 if (txn->mt_u.reader) {
2892 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2893 if (!(env->me_flags & MDB_NOTLS)) {
2894 txn->mt_u.reader = NULL; /* txn does not own reader */
2895 } else if (mode & MDB_END_SLOT) {
2896 txn->mt_u.reader->mr_pid = 0;
2897 txn->mt_u.reader = NULL;
2898 } /* else txn owns the slot until it does MDB_END_SLOT */
2900 txn->mt_numdbs = 0; /* prevent further DBI activity */
2901 txn->mt_flags |= MDB_TXN_FINISHED;
2903 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
2904 pgno_t *pghead = env->me_pghead;
2906 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
2907 mdb_cursors_close(txn, 0);
2908 if (!(env->me_flags & MDB_WRITEMAP)) {
2909 mdb_dlist_free(txn);
2913 txn->mt_flags = MDB_TXN_FINISHED;
2915 if (!txn->mt_parent) {
2916 mdb_midl_shrink(&txn->mt_free_pgs);
2917 env->me_free_pgs = txn->mt_free_pgs;
2919 env->me_pghead = NULL;
2923 mode = 0; /* txn == env->me_txn0, do not free() it */
2925 /* The writer mutex was locked in mdb_txn_begin. */
2927 UNLOCK_MUTEX(env->me_wmutex);
2929 txn->mt_parent->mt_child = NULL;
2930 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
2931 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2932 mdb_midl_free(txn->mt_free_pgs);
2933 mdb_midl_free(txn->mt_spill_pgs);
2934 free(txn->mt_u.dirty_list);
2937 mdb_midl_free(pghead);
2940 if (mode & MDB_END_FREE)
2945 mdb_txn_reset(MDB_txn *txn)
2950 /* This call is only valid for read-only txns */
2951 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2954 mdb_txn_end(txn, MDB_END_RESET);
2958 mdb_txn_abort(MDB_txn *txn)
2964 mdb_txn_abort(txn->mt_child);
2966 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
2969 /** Save the freelist as of this transaction to the freeDB.
2970 * This changes the freelist. Keep trying until it stabilizes.
2973 mdb_freelist_save(MDB_txn *txn)
2975 /* env->me_pghead[] can grow and shrink during this call.
2976 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2977 * Page numbers cannot disappear from txn->mt_free_pgs[].
2980 MDB_env *env = txn->mt_env;
2981 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2982 txnid_t pglast = 0, head_id = 0;
2983 pgno_t freecnt = 0, *free_pgs, *mop;
2984 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2986 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2988 if (env->me_pghead) {
2989 /* Make sure first page of freeDB is touched and on freelist */
2990 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2991 if (rc && rc != MDB_NOTFOUND)
2995 if (!env->me_pghead && txn->mt_loose_pgs) {
2996 /* Put loose page numbers in mt_free_pgs, since
2997 * we may be unable to return them to me_pghead.
2999 MDB_page *mp = txn->mt_loose_pgs;
3000 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3002 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3003 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3004 txn->mt_loose_pgs = NULL;
3005 txn->mt_loose_count = 0;
3008 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3009 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3010 ? SSIZE_MAX : maxfree_1pg;
3013 /* Come back here after each Put() in case freelist changed */
3018 /* If using records from freeDB which we have not yet
3019 * deleted, delete them and any we reserved for me_pghead.
3021 while (pglast < env->me_pglast) {
3022 rc = mdb_cursor_first(&mc, &key, NULL);
3025 pglast = head_id = *(txnid_t *)key.mv_data;
3026 total_room = head_room = 0;
3027 mdb_tassert(txn, pglast <= env->me_pglast);
3028 rc = mdb_cursor_del(&mc, 0);
3033 /* Save the IDL of pages freed by this txn, to a single record */
3034 if (freecnt < txn->mt_free_pgs[0]) {
3036 /* Make sure last page of freeDB is touched and on freelist */
3037 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3038 if (rc && rc != MDB_NOTFOUND)
3041 free_pgs = txn->mt_free_pgs;
3042 /* Write to last page of freeDB */
3043 key.mv_size = sizeof(txn->mt_txnid);
3044 key.mv_data = &txn->mt_txnid;
3046 freecnt = free_pgs[0];
3047 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3048 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3051 /* Retry if mt_free_pgs[] grew during the Put() */
3052 free_pgs = txn->mt_free_pgs;
3053 } while (freecnt < free_pgs[0]);
3054 mdb_midl_sort(free_pgs);
3055 memcpy(data.mv_data, free_pgs, data.mv_size);
3058 unsigned int i = free_pgs[0];
3059 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
3060 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3062 DPRINTF(("IDL %"Z"u", free_pgs[i]));
3068 mop = env->me_pghead;
3069 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3071 /* Reserve records for me_pghead[]. Split it if multi-page,
3072 * to avoid searching freeDB for a page range. Use keys in
3073 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3075 if (total_room >= mop_len) {
3076 if (total_room == mop_len || --more < 0)
3078 } else if (head_room >= maxfree_1pg && head_id > 1) {
3079 /* Keep current record (overflow page), add a new one */
3083 /* (Re)write {key = head_id, IDL length = head_room} */
3084 total_room -= head_room;
3085 head_room = mop_len - total_room;
3086 if (head_room > maxfree_1pg && head_id > 1) {
3087 /* Overflow multi-page for part of me_pghead */
3088 head_room /= head_id; /* amortize page sizes */
3089 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3090 } else if (head_room < 0) {
3091 /* Rare case, not bothering to delete this record */
3094 key.mv_size = sizeof(head_id);
3095 key.mv_data = &head_id;
3096 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3097 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3100 /* IDL is initially empty, zero out at least the length */
3101 pgs = (pgno_t *)data.mv_data;
3102 j = head_room > clean_limit ? head_room : 0;
3106 total_room += head_room;
3109 /* Return loose page numbers to me_pghead, though usually none are
3110 * left at this point. The pages themselves remain in dirty_list.
3112 if (txn->mt_loose_pgs) {
3113 MDB_page *mp = txn->mt_loose_pgs;
3114 unsigned count = txn->mt_loose_count;
3116 /* Room for loose pages + temp IDL with same */
3117 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3119 mop = env->me_pghead;
3120 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3121 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3122 loose[ ++count ] = mp->mp_pgno;
3124 mdb_midl_sort(loose);
3125 mdb_midl_xmerge(mop, loose);
3126 txn->mt_loose_pgs = NULL;
3127 txn->mt_loose_count = 0;
3131 /* Fill in the reserved me_pghead records */
3137 rc = mdb_cursor_first(&mc, &key, &data);
3138 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3139 txnid_t id = *(txnid_t *)key.mv_data;
3140 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3143 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3145 if (len > mop_len) {
3147 data.mv_size = (len + 1) * sizeof(MDB_ID);
3149 data.mv_data = mop -= len;
3152 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3154 if (rc || !(mop_len -= len))
3161 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3162 * @param[in] txn the transaction that's being committed
3163 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3164 * @return 0 on success, non-zero on failure.
3167 mdb_page_flush(MDB_txn *txn, int keep)
3169 MDB_env *env = txn->mt_env;
3170 MDB_ID2L dl = txn->mt_u.dirty_list;
3171 unsigned psize = env->me_psize, j;
3172 int i, pagecount = dl[0].mid, rc;
3173 size_t size = 0, pos = 0;
3175 MDB_page *dp = NULL;
3179 struct iovec iov[MDB_COMMIT_PAGES];
3180 ssize_t wpos = 0, wsize = 0, wres;
3181 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3187 if (env->me_flags & MDB_WRITEMAP) {
3188 /* Clear dirty flags */
3189 while (++i <= pagecount) {
3191 /* Don't flush this page yet */
3192 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3193 dp->mp_flags &= ~P_KEEP;
3197 dp->mp_flags &= ~P_DIRTY;
3202 /* Write the pages */
3204 if (++i <= pagecount) {
3206 /* Don't flush this page yet */
3207 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3208 dp->mp_flags &= ~P_KEEP;
3213 /* clear dirty flag */
3214 dp->mp_flags &= ~P_DIRTY;
3217 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3222 /* Windows actually supports scatter/gather I/O, but only on
3223 * unbuffered file handles. Since we're relying on the OS page
3224 * cache for all our data, that's self-defeating. So we just
3225 * write pages one at a time. We use the ov structure to set
3226 * the write offset, to at least save the overhead of a Seek
3229 DPRINTF(("committing page %"Z"u", pgno));
3230 memset(&ov, 0, sizeof(ov));
3231 ov.Offset = pos & 0xffffffff;
3232 ov.OffsetHigh = pos >> 16 >> 16;
3233 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3235 DPRINTF(("WriteFile: %d", rc));
3239 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3240 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3243 /* Write previous page(s) */
3244 #ifdef MDB_USE_PWRITEV
3245 wres = pwritev(env->me_fd, iov, n, wpos);
3248 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3251 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3255 DPRINTF(("lseek: %s", strerror(rc)));
3258 wres = writev(env->me_fd, iov, n);
3261 if (wres != wsize) {
3266 DPRINTF(("Write error: %s", strerror(rc)));
3268 rc = EIO; /* TODO: Use which error code? */
3269 DPUTS("short write, filesystem full?");
3280 DPRINTF(("committing page %"Z"u", pgno));
3281 next_pos = pos + size;
3282 iov[n].iov_len = size;
3283 iov[n].iov_base = (char *)dp;
3289 /* MIPS has cache coherency issues, this is a no-op everywhere else
3290 * Note: for any size >= on-chip cache size, entire on-chip cache is
3293 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3295 for (i = keep; ++i <= pagecount; ) {
3297 /* This is a page we skipped above */
3300 dl[j].mid = dp->mp_pgno;
3303 mdb_dpage_free(env, dp);
3308 txn->mt_dirty_room += i - j;
3314 mdb_txn_commit(MDB_txn *txn)
3317 unsigned int i, end_mode;
3323 /* mdb_txn_end() mode for a commit which writes nothing */
3324 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3326 if (txn->mt_child) {
3327 rc = mdb_txn_commit(txn->mt_child);
3334 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3338 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3339 DPUTS("txn has failed/finished, can't commit");
3341 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3346 if (txn->mt_parent) {
3347 MDB_txn *parent = txn->mt_parent;
3351 unsigned x, y, len, ps_len;
3353 /* Append our free list to parent's */
3354 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3357 mdb_midl_free(txn->mt_free_pgs);
3358 /* Failures after this must either undo the changes
3359 * to the parent or set MDB_TXN_ERROR in the parent.
3362 parent->mt_next_pgno = txn->mt_next_pgno;
3363 parent->mt_flags = txn->mt_flags;
3365 /* Merge our cursors into parent's and close them */
3366 mdb_cursors_close(txn, 1);
3368 /* Update parent's DB table. */
3369 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3370 parent->mt_numdbs = txn->mt_numdbs;
3371 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3372 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3373 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3374 /* preserve parent's DB_NEW status */
3375 x = parent->mt_dbflags[i] & DB_NEW;
3376 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3379 dst = parent->mt_u.dirty_list;
3380 src = txn->mt_u.dirty_list;
3381 /* Remove anything in our dirty list from parent's spill list */
3382 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3384 pspill[0] = (pgno_t)-1;
3385 /* Mark our dirty pages as deleted in parent spill list */
3386 for (i=0, len=src[0].mid; ++i <= len; ) {
3387 MDB_ID pn = src[i].mid << 1;
3388 while (pn > pspill[x])
3390 if (pn == pspill[x]) {
3395 /* Squash deleted pagenums if we deleted any */
3396 for (x=y; ++x <= ps_len; )
3397 if (!(pspill[x] & 1))
3398 pspill[++y] = pspill[x];
3402 /* Find len = length of merging our dirty list with parent's */
3404 dst[0].mid = 0; /* simplify loops */
3405 if (parent->mt_parent) {
3406 len = x + src[0].mid;
3407 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3408 for (i = x; y && i; y--) {
3409 pgno_t yp = src[y].mid;
3410 while (yp < dst[i].mid)
3412 if (yp == dst[i].mid) {
3417 } else { /* Simplify the above for single-ancestor case */
3418 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3420 /* Merge our dirty list with parent's */
3422 for (i = len; y; dst[i--] = src[y--]) {
3423 pgno_t yp = src[y].mid;
3424 while (yp < dst[x].mid)
3425 dst[i--] = dst[x--];
3426 if (yp == dst[x].mid)
3427 free(dst[x--].mptr);
3429 mdb_tassert(txn, i == x);
3431 free(txn->mt_u.dirty_list);
3432 parent->mt_dirty_room = txn->mt_dirty_room;
3433 if (txn->mt_spill_pgs) {
3434 if (parent->mt_spill_pgs) {
3435 /* TODO: Prevent failure here, so parent does not fail */
3436 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3438 parent->mt_flags |= MDB_TXN_ERROR;
3439 mdb_midl_free(txn->mt_spill_pgs);
3440 mdb_midl_sort(parent->mt_spill_pgs);
3442 parent->mt_spill_pgs = txn->mt_spill_pgs;
3446 /* Append our loose page list to parent's */
3447 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(lp))
3449 *lp = txn->mt_loose_pgs;
3450 parent->mt_loose_count += txn->mt_loose_count;
3452 parent->mt_child = NULL;
3453 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3458 if (txn != env->me_txn) {
3459 DPUTS("attempt to commit unknown transaction");
3464 mdb_cursors_close(txn, 0);
3466 if (!txn->mt_u.dirty_list[0].mid &&
3467 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3470 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3471 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3473 /* Update DB root pointers */
3474 if (txn->mt_numdbs > CORE_DBS) {
3478 data.mv_size = sizeof(MDB_db);
3480 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3481 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3482 if (txn->mt_dbflags[i] & DB_DIRTY) {
3483 if (TXN_DBI_CHANGED(txn, i)) {
3487 data.mv_data = &txn->mt_dbs[i];
3488 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3496 rc = mdb_freelist_save(txn);
3500 mdb_midl_free(env->me_pghead);
3501 env->me_pghead = NULL;
3502 mdb_midl_shrink(&txn->mt_free_pgs);
3508 if ((rc = mdb_page_flush(txn, 0)) ||
3509 (rc = mdb_env_sync(env, 0)) ||
3510 (rc = mdb_env_write_meta(txn)))
3512 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3515 mdb_txn_end(txn, end_mode);
3523 /** Read the environment parameters of a DB environment before
3524 * mapping it into memory.
3525 * @param[in] env the environment handle
3526 * @param[out] meta address of where to store the meta information
3527 * @return 0 on success, non-zero on failure.
3530 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3536 enum { Size = sizeof(pbuf) };
3538 /* We don't know the page size yet, so use a minimum value.
3539 * Read both meta pages so we can use the latest one.
3542 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3546 memset(&ov, 0, sizeof(ov));
3548 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3549 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3552 rc = pread(env->me_fd, &pbuf, Size, off);
3555 if (rc == 0 && off == 0)
3557 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3558 DPRINTF(("read: %s", mdb_strerror(rc)));
3562 p = (MDB_page *)&pbuf;
3564 if (!F_ISSET(p->mp_flags, P_META)) {
3565 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3570 if (m->mm_magic != MDB_MAGIC) {
3571 DPUTS("meta has invalid magic");
3575 if (m->mm_version != MDB_DATA_VERSION) {
3576 DPRINTF(("database is version %u, expected version %u",
3577 m->mm_version, MDB_DATA_VERSION));
3578 return MDB_VERSION_MISMATCH;
3581 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3587 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3589 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3591 meta->mm_magic = MDB_MAGIC;
3592 meta->mm_version = MDB_DATA_VERSION;
3593 meta->mm_mapsize = env->me_mapsize;
3594 meta->mm_psize = env->me_psize;
3595 meta->mm_last_pg = NUM_METAS-1;
3596 meta->mm_flags = env->me_flags & 0xffff;
3597 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3598 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3599 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3602 /** Write the environment parameters of a freshly created DB environment.
3603 * @param[in] env the environment handle
3604 * @param[in] meta the #MDB_meta to write
3605 * @return 0 on success, non-zero on failure.
3608 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3616 memset(&ov, 0, sizeof(ov));
3617 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3619 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3622 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3623 len = pwrite(fd, ptr, size, pos); \
3624 if (len == -1 && ErrCode() == EINTR) continue; \
3625 rc = (len >= 0); break; } while(1)
3628 DPUTS("writing new meta page");
3630 psize = env->me_psize;
3632 p = calloc(NUM_METAS, psize);
3637 p->mp_flags = P_META;
3638 *(MDB_meta *)METADATA(p) = *meta;
3640 q = (MDB_page *)((char *)p + psize);
3642 q->mp_flags = P_META;
3643 *(MDB_meta *)METADATA(q) = *meta;
3645 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
3648 else if ((unsigned) len == psize * NUM_METAS)
3656 /** Update the environment info to commit a transaction.
3657 * @param[in] txn the transaction that's being committed
3658 * @return 0 on success, non-zero on failure.
3661 mdb_env_write_meta(MDB_txn *txn)
3664 MDB_meta meta, metab, *mp;
3668 int rc, len, toggle;
3677 toggle = txn->mt_txnid & 1;
3678 DPRINTF(("writing meta page %d for root page %"Z"u",
3679 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3682 flags = env->me_flags;
3683 mp = env->me_metas[toggle];
3684 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3685 /* Persist any increases of mapsize config */
3686 if (mapsize < env->me_mapsize)
3687 mapsize = env->me_mapsize;
3689 if (flags & MDB_WRITEMAP) {
3690 mp->mm_mapsize = mapsize;
3691 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3692 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3693 mp->mm_last_pg = txn->mt_next_pgno - 1;
3694 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
3695 !(defined(__i386__) || defined(__x86_64__))
3696 /* LY: issue a memory barrier, if not x86. ITS#7969 */
3697 __sync_synchronize();
3699 mp->mm_txnid = txn->mt_txnid;
3700 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3701 unsigned meta_size = env->me_psize;
3702 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3703 ptr = (char *)mp - PAGEHDRSZ;
3704 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3705 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
3709 if (MDB_MSYNC(ptr, meta_size, rc)) {
3716 metab.mm_txnid = mp->mm_txnid;
3717 metab.mm_last_pg = mp->mm_last_pg;
3719 meta.mm_mapsize = mapsize;
3720 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3721 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3722 meta.mm_last_pg = txn->mt_next_pgno - 1;
3723 meta.mm_txnid = txn->mt_txnid;
3725 off = offsetof(MDB_meta, mm_mapsize);
3726 ptr = (char *)&meta + off;
3727 len = sizeof(MDB_meta) - off;
3728 off += (char *)mp - env->me_map;
3730 /* Write to the SYNC fd */
3731 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
3734 memset(&ov, 0, sizeof(ov));
3736 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3741 rc = pwrite(mfd, ptr, len, off);
3744 rc = rc < 0 ? ErrCode() : EIO;
3749 DPUTS("write failed, disk error?");
3750 /* On a failure, the pagecache still contains the new data.
3751 * Write some old data back, to prevent it from being used.
3752 * Use the non-SYNC fd; we know it will fail anyway.
3754 meta.mm_last_pg = metab.mm_last_pg;
3755 meta.mm_txnid = metab.mm_txnid;
3757 memset(&ov, 0, sizeof(ov));
3759 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3761 r2 = pwrite(env->me_fd, ptr, len, off);
3762 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3765 env->me_flags |= MDB_FATAL_ERROR;
3768 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3769 CACHEFLUSH(env->me_map + off, len, DCACHE);
3771 /* Memory ordering issues are irrelevant; since the entire writer
3772 * is wrapped by wmutex, all of these changes will become visible
3773 * after the wmutex is unlocked. Since the DB is multi-version,
3774 * readers will get consistent data regardless of how fresh or
3775 * how stale their view of these values is.
3778 env->me_txns->mti_txnid = txn->mt_txnid;
3783 /** Check both meta pages to see which one is newer.
3784 * @param[in] env the environment handle
3785 * @return newest #MDB_meta.
3788 mdb_env_pick_meta(const MDB_env *env)
3790 MDB_meta *const *metas = env->me_metas;
3791 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
3795 mdb_env_create(MDB_env **env)
3799 e = calloc(1, sizeof(MDB_env));
3803 e->me_maxreaders = DEFAULT_READERS;
3804 e->me_maxdbs = e->me_numdbs = CORE_DBS;
3805 e->me_fd = INVALID_HANDLE_VALUE;
3806 e->me_lfd = INVALID_HANDLE_VALUE;
3807 e->me_mfd = INVALID_HANDLE_VALUE;
3808 #ifdef MDB_USE_POSIX_SEM
3809 e->me_rmutex = SEM_FAILED;
3810 e->me_wmutex = SEM_FAILED;
3812 e->me_pid = getpid();
3813 GET_PAGESIZE(e->me_os_psize);
3814 VGMEMP_CREATE(e,0,0);
3820 mdb_env_map(MDB_env *env, void *addr)
3823 unsigned int flags = env->me_flags;
3827 LONG sizelo, sizehi;
3830 if (flags & MDB_RDONLY) {
3831 /* Don't set explicit map size, use whatever exists */
3836 msize = env->me_mapsize;
3837 sizelo = msize & 0xffffffff;
3838 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3840 /* Windows won't create mappings for zero length files.
3841 * and won't map more than the file size.
3842 * Just set the maxsize right now.
3844 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3845 || !SetEndOfFile(env->me_fd)
3846 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3850 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3851 PAGE_READWRITE : PAGE_READONLY,
3852 sizehi, sizelo, NULL);
3855 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3856 FILE_MAP_WRITE : FILE_MAP_READ,
3858 rc = env->me_map ? 0 : ErrCode();
3863 int prot = PROT_READ;
3864 if (flags & MDB_WRITEMAP) {
3866 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3869 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3871 if (env->me_map == MAP_FAILED) {
3876 if (flags & MDB_NORDAHEAD) {
3877 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3879 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3881 #ifdef POSIX_MADV_RANDOM
3882 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3883 #endif /* POSIX_MADV_RANDOM */
3884 #endif /* MADV_RANDOM */
3888 /* Can happen because the address argument to mmap() is just a
3889 * hint. mmap() can pick another, e.g. if the range is in use.
3890 * The MAP_FIXED flag would prevent that, but then mmap could
3891 * instead unmap existing pages to make room for the new map.
3893 if (addr && env->me_map != addr)
3894 return EBUSY; /* TODO: Make a new MDB_* error code? */
3896 p = (MDB_page *)env->me_map;
3897 env->me_metas[0] = METADATA(p);
3898 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3904 mdb_env_set_mapsize(MDB_env *env, size_t size)
3906 /* If env is already open, caller is responsible for making
3907 * sure there are no active txns.
3915 meta = mdb_env_pick_meta(env);
3917 size = meta->mm_mapsize;
3919 /* Silently round up to minimum if the size is too small */
3920 size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
3924 munmap(env->me_map, env->me_mapsize);
3925 env->me_mapsize = size;
3926 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3927 rc = mdb_env_map(env, old);
3931 env->me_mapsize = size;
3933 env->me_maxpg = env->me_mapsize / env->me_psize;
3938 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3942 env->me_maxdbs = dbs + CORE_DBS;
3947 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3949 if (env->me_map || readers < 1)
3951 env->me_maxreaders = readers;
3956 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3958 if (!env || !readers)
3960 *readers = env->me_maxreaders;
3965 mdb_fsize(HANDLE fd, size_t *size)
3968 LARGE_INTEGER fsize;
3970 if (!GetFileSizeEx(fd, &fsize))
3973 *size = fsize.QuadPart;
3985 #ifdef BROKEN_FDATASYNC
3986 #include <sys/utsname.h>
3987 #include <sys/vfs.h>
3990 /** Further setup required for opening an LMDB environment
3993 mdb_env_open2(MDB_env *env)
3995 unsigned int flags = env->me_flags;
3996 int i, newenv = 0, rc;
4000 /* See if we should use QueryLimited */
4002 if ((rc & 0xff) > 5)
4003 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4005 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4008 #ifdef BROKEN_FDATASYNC
4009 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4010 * https://lkml.org/lkml/2012/9/3/83
4011 * Kernels after 3.6-rc6 are known good.
4012 * https://lkml.org/lkml/2012/9/10/556
4013 * See if the DB is on ext3/ext4, then check for new enough kernel
4014 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4019 fstatfs(env->me_fd, &st);
4020 while (st.f_type == 0xEF53) {
4024 if (uts.release[0] < '3') {
4025 if (!strncmp(uts.release, "2.6.32.", 7)) {
4026 i = atoi(uts.release+7);
4028 break; /* 2.6.32.60 and newer is OK */
4029 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4030 i = atoi(uts.release+7);
4032 break; /* 2.6.34.15 and newer is OK */
4034 } else if (uts.release[0] == '3') {
4035 i = atoi(uts.release+2);
4037 break; /* 3.6 and newer is OK */
4039 i = atoi(uts.release+4);
4041 break; /* 3.5.4 and newer is OK */
4042 } else if (i == 2) {
4043 i = atoi(uts.release+4);
4045 break; /* 3.2.30 and newer is OK */
4047 } else { /* 4.x and newer is OK */
4050 env->me_flags |= MDB_FSYNCONLY;
4056 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4059 DPUTS("new mdbenv");
4061 env->me_psize = env->me_os_psize;
4062 if (env->me_psize > MAX_PAGESIZE)
4063 env->me_psize = MAX_PAGESIZE;
4064 memset(&meta, 0, sizeof(meta));
4065 mdb_env_init_meta0(env, &meta);
4066 meta.mm_mapsize = DEFAULT_MAPSIZE;
4068 env->me_psize = meta.mm_psize;
4071 /* Was a mapsize configured? */
4072 if (!env->me_mapsize) {
4073 env->me_mapsize = meta.mm_mapsize;
4076 /* Make sure mapsize >= committed data size. Even when using
4077 * mm_mapsize, which could be broken in old files (ITS#7789).
4079 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4080 if (env->me_mapsize < minsize)
4081 env->me_mapsize = minsize;
4083 meta.mm_mapsize = env->me_mapsize;
4085 if (newenv && !(flags & MDB_FIXEDMAP)) {
4086 /* mdb_env_map() may grow the datafile. Write the metapages
4087 * first, so the file will be valid if initialization fails.
4088 * Except with FIXEDMAP, since we do not yet know mm_address.
4089 * We could fill in mm_address later, but then a different
4090 * program might end up doing that - one with a memory layout
4091 * and map address which does not suit the main program.
4093 rc = mdb_env_init_meta(env, &meta);
4099 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4104 if (flags & MDB_FIXEDMAP)
4105 meta.mm_address = env->me_map;
4106 i = mdb_env_init_meta(env, &meta);
4107 if (i != MDB_SUCCESS) {
4112 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4113 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4115 #if !(MDB_MAXKEYSIZE)
4116 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4118 env->me_maxpg = env->me_mapsize / env->me_psize;
4122 MDB_meta *meta = mdb_env_pick_meta(env);
4123 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4125 DPRINTF(("opened database version %u, pagesize %u",
4126 meta->mm_version, env->me_psize));
4127 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4128 DPRINTF(("depth: %u", db->md_depth));
4129 DPRINTF(("entries: %"Z"u", db->md_entries));
4130 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
4131 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
4132 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
4133 DPRINTF(("root: %"Z"u", db->md_root));
4141 /** Release a reader thread's slot in the reader lock table.
4142 * This function is called automatically when a thread exits.
4143 * @param[in] ptr This points to the slot in the reader lock table.
4146 mdb_env_reader_dest(void *ptr)
4148 MDB_reader *reader = ptr;
4154 /** Junk for arranging thread-specific callbacks on Windows. This is
4155 * necessarily platform and compiler-specific. Windows supports up
4156 * to 1088 keys. Let's assume nobody opens more than 64 environments
4157 * in a single process, for now. They can override this if needed.
4159 #ifndef MAX_TLS_KEYS
4160 #define MAX_TLS_KEYS 64
4162 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4163 static int mdb_tls_nkeys;
4165 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4169 case DLL_PROCESS_ATTACH: break;
4170 case DLL_THREAD_ATTACH: break;
4171 case DLL_THREAD_DETACH:
4172 for (i=0; i<mdb_tls_nkeys; i++) {
4173 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4175 mdb_env_reader_dest(r);
4179 case DLL_PROCESS_DETACH: break;
4184 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4186 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4190 /* Force some symbol references.
4191 * _tls_used forces the linker to create the TLS directory if not already done
4192 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4194 #pragma comment(linker, "/INCLUDE:_tls_used")
4195 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4196 #pragma const_seg(".CRT$XLB")
4197 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4198 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4201 #pragma comment(linker, "/INCLUDE:__tls_used")
4202 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4203 #pragma data_seg(".CRT$XLB")
4204 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4206 #endif /* WIN 32/64 */
4207 #endif /* !__GNUC__ */
4210 /** Downgrade the exclusive lock on the region back to shared */
4212 mdb_env_share_locks(MDB_env *env, int *excl)
4215 MDB_meta *meta = mdb_env_pick_meta(env);
4217 env->me_txns->mti_txnid = meta->mm_txnid;
4222 /* First acquire a shared lock. The Unlock will
4223 * then release the existing exclusive lock.
4225 memset(&ov, 0, sizeof(ov));
4226 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4229 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4235 struct flock lock_info;
4236 /* The shared lock replaces the existing lock */
4237 memset((void *)&lock_info, 0, sizeof(lock_info));
4238 lock_info.l_type = F_RDLCK;
4239 lock_info.l_whence = SEEK_SET;
4240 lock_info.l_start = 0;
4241 lock_info.l_len = 1;
4242 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4243 (rc = ErrCode()) == EINTR) ;
4244 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4251 /** Try to get exclusive lock, otherwise shared.
4252 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4255 mdb_env_excl_lock(MDB_env *env, int *excl)
4259 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4263 memset(&ov, 0, sizeof(ov));
4264 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4271 struct flock lock_info;
4272 memset((void *)&lock_info, 0, sizeof(lock_info));
4273 lock_info.l_type = F_WRLCK;
4274 lock_info.l_whence = SEEK_SET;
4275 lock_info.l_start = 0;
4276 lock_info.l_len = 1;
4277 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4278 (rc = ErrCode()) == EINTR) ;
4282 # ifndef MDB_USE_POSIX_MUTEX
4283 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4286 lock_info.l_type = F_RDLCK;
4287 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4288 (rc = ErrCode()) == EINTR) ;
4298 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4300 * @(#) $Revision: 5.1 $
4301 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4302 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4304 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4308 * Please do not copyright this code. This code is in the public domain.
4310 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4311 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4312 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4313 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4314 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4315 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4316 * PERFORMANCE OF THIS SOFTWARE.
4319 * chongo <Landon Curt Noll> /\oo/\
4320 * http://www.isthe.com/chongo/
4322 * Share and Enjoy! :-)
4325 typedef unsigned long long mdb_hash_t;
4326 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4328 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4329 * @param[in] val value to hash
4330 * @param[in] hval initial value for hash
4331 * @return 64 bit hash
4333 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4334 * hval arg on the first call.
4337 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4339 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4340 unsigned char *end = s + val->mv_size;
4342 * FNV-1a hash each octet of the string
4345 /* xor the bottom with the current octet */
4346 hval ^= (mdb_hash_t)*s++;
4348 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4349 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4350 (hval << 7) + (hval << 8) + (hval << 40);
4352 /* return our new hash value */
4356 /** Hash the string and output the encoded hash.
4357 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4358 * very short name limits. We don't care about the encoding being reversible,
4359 * we just want to preserve as many bits of the input as possible in a
4360 * small printable string.
4361 * @param[in] str string to hash
4362 * @param[out] encbuf an array of 11 chars to hold the hash
4364 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4367 mdb_pack85(unsigned long l, char *out)
4371 for (i=0; i<5; i++) {
4372 *out++ = mdb_a85[l % 85];
4378 mdb_hash_enc(MDB_val *val, char *encbuf)
4380 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4382 mdb_pack85(h, encbuf);
4383 mdb_pack85(h>>32, encbuf+5);
4388 /** Open and/or initialize the lock region for the environment.
4389 * @param[in] env The LMDB environment.
4390 * @param[in] lpath The pathname of the file used for the lock region.
4391 * @param[in] mode The Unix permissions for the file, if we create it.
4392 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4393 * @return 0 on success, non-zero on failure.
4396 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4399 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4401 # define MDB_ERRCODE_ROFS EROFS
4402 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4403 # define MDB_CLOEXEC O_CLOEXEC
4406 # define MDB_CLOEXEC 0
4413 env->me_lfd = CreateFileA(lpath, GENERIC_READ|GENERIC_WRITE,
4414 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4415 FILE_ATTRIBUTE_NORMAL, NULL);
4417 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4419 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4421 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4426 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4427 /* Lose record locks when exec*() */
4428 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4429 fcntl(env->me_lfd, F_SETFD, fdflags);
4432 if (!(env->me_flags & MDB_NOTLS)) {
4433 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4436 env->me_flags |= MDB_ENV_TXKEY;
4438 /* Windows TLS callbacks need help finding their TLS info. */
4439 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4443 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4447 /* Try to get exclusive lock. If we succeed, then
4448 * nobody is using the lock region and we should initialize it.
4450 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4453 size = GetFileSize(env->me_lfd, NULL);
4455 size = lseek(env->me_lfd, 0, SEEK_END);
4456 if (size == -1) goto fail_errno;
4458 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4459 if (size < rsize && *excl > 0) {
4461 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4462 || !SetEndOfFile(env->me_lfd))
4465 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4469 size = rsize - sizeof(MDB_txninfo);
4470 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4475 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4477 if (!mh) goto fail_errno;
4478 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4480 if (!env->me_txns) goto fail_errno;
4482 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4484 if (m == MAP_FAILED) goto fail_errno;
4490 BY_HANDLE_FILE_INFORMATION stbuf;
4499 if (!mdb_sec_inited) {
4500 InitializeSecurityDescriptor(&mdb_null_sd,
4501 SECURITY_DESCRIPTOR_REVISION);
4502 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4503 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4504 mdb_all_sa.bInheritHandle = FALSE;
4505 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4508 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4509 idbuf.volume = stbuf.dwVolumeSerialNumber;
4510 idbuf.nhigh = stbuf.nFileIndexHigh;
4511 idbuf.nlow = stbuf.nFileIndexLow;
4512 val.mv_data = &idbuf;
4513 val.mv_size = sizeof(idbuf);
4514 mdb_hash_enc(&val, encbuf);
4515 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4516 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4517 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4518 if (!env->me_rmutex) goto fail_errno;
4519 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4520 if (!env->me_wmutex) goto fail_errno;
4521 #elif defined(MDB_USE_POSIX_SEM)
4530 #if defined(__NetBSD__)
4531 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4533 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4534 idbuf.dev = stbuf.st_dev;
4535 idbuf.ino = stbuf.st_ino;
4536 val.mv_data = &idbuf;
4537 val.mv_size = sizeof(idbuf);
4538 mdb_hash_enc(&val, encbuf);
4539 #ifdef MDB_SHORT_SEMNAMES
4540 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4542 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4543 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4544 /* Clean up after a previous run, if needed: Try to
4545 * remove both semaphores before doing anything else.
4547 sem_unlink(env->me_txns->mti_rmname);
4548 sem_unlink(env->me_txns->mti_wmname);
4549 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4550 O_CREAT|O_EXCL, mode, 1);
4551 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4552 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4553 O_CREAT|O_EXCL, mode, 1);
4554 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4555 #else /* MDB_USE_POSIX_MUTEX: */
4556 pthread_mutexattr_t mattr;
4558 if ((rc = pthread_mutexattr_init(&mattr))
4559 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4560 #ifdef MDB_ROBUST_SUPPORTED
4561 || (rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST))
4563 || (rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr))
4564 || (rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr)))
4566 pthread_mutexattr_destroy(&mattr);
4567 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4569 env->me_txns->mti_magic = MDB_MAGIC;
4570 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4571 env->me_txns->mti_txnid = 0;
4572 env->me_txns->mti_numreaders = 0;
4575 if (env->me_txns->mti_magic != MDB_MAGIC) {
4576 DPUTS("lock region has invalid magic");
4580 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4581 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4582 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4583 rc = MDB_VERSION_MISMATCH;
4587 if (rc && rc != EACCES && rc != EAGAIN) {
4591 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4592 if (!env->me_rmutex) goto fail_errno;
4593 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4594 if (!env->me_wmutex) goto fail_errno;
4595 #elif defined(MDB_USE_POSIX_SEM)
4596 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4597 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4598 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4599 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4610 /** The name of the lock file in the DB environment */
4611 #define LOCKNAME "/lock.mdb"
4612 /** The name of the data file in the DB environment */
4613 #define DATANAME "/data.mdb"
4614 /** The suffix of the lock file when no subdir is used */
4615 #define LOCKSUFF "-lock"
4616 /** Only a subset of the @ref mdb_env flags can be changed
4617 * at runtime. Changing other flags requires closing the
4618 * environment and re-opening it with the new flags.
4620 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4621 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
4622 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4624 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4625 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4629 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4631 int oflags, rc, len, excl = -1;
4632 char *lpath, *dpath;
4634 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4638 if (flags & MDB_NOSUBDIR) {
4639 rc = len + sizeof(LOCKSUFF) + len + 1;
4641 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4646 if (flags & MDB_NOSUBDIR) {
4647 dpath = lpath + len + sizeof(LOCKSUFF);
4648 sprintf(lpath, "%s" LOCKSUFF, path);
4649 strcpy(dpath, path);
4651 dpath = lpath + len + sizeof(LOCKNAME);
4652 sprintf(lpath, "%s" LOCKNAME, path);
4653 sprintf(dpath, "%s" DATANAME, path);
4657 flags |= env->me_flags;
4658 if (flags & MDB_RDONLY) {
4659 /* silently ignore WRITEMAP when we're only getting read access */
4660 flags &= ~MDB_WRITEMAP;
4662 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4663 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4666 env->me_flags = flags |= MDB_ENV_ACTIVE;
4670 env->me_path = strdup(path);
4671 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4672 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4673 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4674 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4678 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
4680 /* For RDONLY, get lockfile after we know datafile exists */
4681 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4682 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4688 if (F_ISSET(flags, MDB_RDONLY)) {
4689 oflags = GENERIC_READ;
4690 len = OPEN_EXISTING;
4692 oflags = GENERIC_READ|GENERIC_WRITE;
4695 mode = FILE_ATTRIBUTE_NORMAL;
4696 env->me_fd = CreateFileA(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4697 NULL, len, mode, NULL);
4699 if (F_ISSET(flags, MDB_RDONLY))
4702 oflags = O_RDWR | O_CREAT;
4704 env->me_fd = open(dpath, oflags, mode);
4706 if (env->me_fd == INVALID_HANDLE_VALUE) {
4711 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4712 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4717 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4718 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4719 env->me_mfd = env->me_fd;
4721 /* Synchronous fd for meta writes. Needed even with
4722 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4725 len = OPEN_EXISTING;
4726 env->me_mfd = CreateFileA(dpath, oflags,
4727 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4728 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4731 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4733 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4738 DPRINTF(("opened dbenv %p", (void *) env));
4740 rc = mdb_env_share_locks(env, &excl);
4744 if (!(flags & MDB_RDONLY)) {
4746 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
4747 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
4748 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
4749 (txn = calloc(1, size)))
4751 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
4752 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
4753 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
4754 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
4756 txn->mt_dbxs = env->me_dbxs;
4757 txn->mt_flags = MDB_TXN_FINISHED;
4767 mdb_env_close0(env, excl);
4773 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4775 mdb_env_close0(MDB_env *env, int excl)
4779 if (!(env->me_flags & MDB_ENV_ACTIVE))
4782 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4784 for (i = env->me_maxdbs; --i >= CORE_DBS; )
4785 free(env->me_dbxs[i].md_name.mv_data);
4790 free(env->me_dbiseqs);
4791 free(env->me_dbflags);
4793 free(env->me_dirty_list);
4795 mdb_midl_free(env->me_free_pgs);
4797 if (env->me_flags & MDB_ENV_TXKEY) {
4798 pthread_key_delete(env->me_txkey);
4800 /* Delete our key from the global list */
4801 for (i=0; i<mdb_tls_nkeys; i++)
4802 if (mdb_tls_keys[i] == env->me_txkey) {
4803 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4811 munmap(env->me_map, env->me_mapsize);
4813 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4814 (void) close(env->me_mfd);
4815 if (env->me_fd != INVALID_HANDLE_VALUE)
4816 (void) close(env->me_fd);
4818 MDB_PID_T pid = env->me_pid;
4819 /* Clearing readers is done in this function because
4820 * me_txkey with its destructor must be disabled first.
4822 * We skip the the reader mutex, so we touch only
4823 * data owned by this process (me_close_readers and
4824 * our readers), and clear each reader atomically.
4826 for (i = env->me_close_readers; --i >= 0; )
4827 if (env->me_txns->mti_readers[i].mr_pid == pid)
4828 env->me_txns->mti_readers[i].mr_pid = 0;
4830 if (env->me_rmutex) {
4831 CloseHandle(env->me_rmutex);
4832 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4834 /* Windows automatically destroys the mutexes when
4835 * the last handle closes.
4837 #elif defined(MDB_USE_POSIX_SEM)
4838 if (env->me_rmutex != SEM_FAILED) {
4839 sem_close(env->me_rmutex);
4840 if (env->me_wmutex != SEM_FAILED)
4841 sem_close(env->me_wmutex);
4842 /* If we have the filelock: If we are the
4843 * only remaining user, clean up semaphores.
4846 mdb_env_excl_lock(env, &excl);
4848 sem_unlink(env->me_txns->mti_rmname);
4849 sem_unlink(env->me_txns->mti_wmname);
4853 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4855 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4858 /* Unlock the lockfile. Windows would have unlocked it
4859 * after closing anyway, but not necessarily at once.
4861 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4864 (void) close(env->me_lfd);
4867 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4871 mdb_env_close(MDB_env *env)
4878 VGMEMP_DESTROY(env);
4879 while ((dp = env->me_dpages) != NULL) {
4880 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4881 env->me_dpages = dp->mp_next;
4885 mdb_env_close0(env, 0);
4889 /** Compare two items pointing at aligned size_t's */
4891 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4893 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4894 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4897 /** Compare two items pointing at aligned unsigned int's.
4899 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
4900 * but #mdb_cmp_clong() is called instead if the data type is size_t.
4903 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4905 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4906 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4909 /** Compare two items pointing at unsigned ints of unknown alignment.
4910 * Nodes and keys are guaranteed to be 2-byte aligned.
4913 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4915 #if BYTE_ORDER == LITTLE_ENDIAN
4916 unsigned short *u, *c;
4919 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4920 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4923 } while(!x && u > (unsigned short *)a->mv_data);
4926 unsigned short *u, *c, *end;
4929 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4930 u = (unsigned short *)a->mv_data;
4931 c = (unsigned short *)b->mv_data;
4934 } while(!x && u < end);
4939 /** Compare two items lexically */
4941 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4948 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4954 diff = memcmp(a->mv_data, b->mv_data, len);
4955 return diff ? diff : len_diff<0 ? -1 : len_diff;
4958 /** Compare two items in reverse byte order */
4960 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4962 const unsigned char *p1, *p2, *p1_lim;
4966 p1_lim = (const unsigned char *)a->mv_data;
4967 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4968 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4970 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4976 while (p1 > p1_lim) {
4977 diff = *--p1 - *--p2;
4981 return len_diff<0 ? -1 : len_diff;
4984 /** Search for key within a page, using binary search.
4985 * Returns the smallest entry larger or equal to the key.
4986 * If exactp is non-null, stores whether the found entry was an exact match
4987 * in *exactp (1 or 0).
4988 * Updates the cursor index with the index of the found entry.
4989 * If no entry larger or equal to the key is found, returns NULL.
4992 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4994 unsigned int i = 0, nkeys;
4997 MDB_page *mp = mc->mc_pg[mc->mc_top];
4998 MDB_node *node = NULL;
5003 nkeys = NUMKEYS(mp);
5005 DPRINTF(("searching %u keys in %s %spage %"Z"u",
5006 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5009 low = IS_LEAF(mp) ? 0 : 1;
5011 cmp = mc->mc_dbx->md_cmp;
5013 /* Branch pages have no data, so if using integer keys,
5014 * alignment is guaranteed. Use faster mdb_cmp_int.
5016 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5017 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
5024 nodekey.mv_size = mc->mc_db->md_pad;
5025 node = NODEPTR(mp, 0); /* fake */
5026 while (low <= high) {
5027 i = (low + high) >> 1;
5028 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5029 rc = cmp(key, &nodekey);
5030 DPRINTF(("found leaf index %u [%s], rc = %i",
5031 i, DKEY(&nodekey), rc));
5040 while (low <= high) {
5041 i = (low + high) >> 1;
5043 node = NODEPTR(mp, i);
5044 nodekey.mv_size = NODEKSZ(node);
5045 nodekey.mv_data = NODEKEY(node);
5047 rc = cmp(key, &nodekey);
5050 DPRINTF(("found leaf index %u [%s], rc = %i",
5051 i, DKEY(&nodekey), rc));
5053 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
5054 i, DKEY(&nodekey), NODEPGNO(node), rc));
5065 if (rc > 0) { /* Found entry is less than the key. */
5066 i++; /* Skip to get the smallest entry larger than key. */
5068 node = NODEPTR(mp, i);
5071 *exactp = (rc == 0 && nkeys > 0);
5072 /* store the key index */
5073 mc->mc_ki[mc->mc_top] = i;
5075 /* There is no entry larger or equal to the key. */
5078 /* nodeptr is fake for LEAF2 */
5084 mdb_cursor_adjust(MDB_cursor *mc, func)
5088 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5089 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5096 /** Pop a page off the top of the cursor's stack. */
5098 mdb_cursor_pop(MDB_cursor *mc)
5101 DPRINTF(("popping page %"Z"u off db %d cursor %p",
5102 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5110 /** Push a page onto the top of the cursor's stack. */
5112 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5114 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
5115 DDBI(mc), (void *) mc));
5117 if (mc->mc_snum >= CURSOR_STACK) {
5118 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5119 return MDB_CURSOR_FULL;
5122 mc->mc_top = mc->mc_snum++;
5123 mc->mc_pg[mc->mc_top] = mp;
5124 mc->mc_ki[mc->mc_top] = 0;
5129 /** Find the address of the page corresponding to a given page number.
5130 * @param[in] txn the transaction for this access.
5131 * @param[in] pgno the page number for the page to retrieve.
5132 * @param[out] ret address of a pointer where the page's address will be stored.
5133 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5134 * @return 0 on success, non-zero on failure.
5137 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
5139 MDB_env *env = txn->mt_env;
5143 if (! (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_WRITEMAP))) {
5147 MDB_ID2L dl = tx2->mt_u.dirty_list;
5149 /* Spilled pages were dirtied in this txn and flushed
5150 * because the dirty list got full. Bring this page
5151 * back in from the map (but don't unspill it here,
5152 * leave that unless page_touch happens again).
5154 if (tx2->mt_spill_pgs) {
5155 MDB_ID pn = pgno << 1;
5156 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5157 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5158 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5163 unsigned x = mdb_mid2l_search(dl, pgno);
5164 if (x <= dl[0].mid && dl[x].mid == pgno) {
5170 } while ((tx2 = tx2->mt_parent) != NULL);
5173 if (pgno < txn->mt_next_pgno) {
5175 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5177 DPRINTF(("page %"Z"u not found", pgno));
5178 txn->mt_flags |= MDB_TXN_ERROR;
5179 return MDB_PAGE_NOTFOUND;
5189 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
5190 * The cursor is at the root page, set up the rest of it.
5193 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
5195 MDB_page *mp = mc->mc_pg[mc->mc_top];
5199 while (IS_BRANCH(mp)) {
5203 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
5204 mdb_cassert(mc, NUMKEYS(mp) > 1);
5205 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
5207 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
5209 if (flags & MDB_PS_LAST)
5210 i = NUMKEYS(mp) - 1;
5213 node = mdb_node_search(mc, key, &exact);
5215 i = NUMKEYS(mp) - 1;
5217 i = mc->mc_ki[mc->mc_top];
5219 mdb_cassert(mc, i > 0);
5223 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
5226 mdb_cassert(mc, i < NUMKEYS(mp));
5227 node = NODEPTR(mp, i);
5229 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5232 mc->mc_ki[mc->mc_top] = i;
5233 if ((rc = mdb_cursor_push(mc, mp)))
5236 if (flags & MDB_PS_MODIFY) {
5237 if ((rc = mdb_page_touch(mc)) != 0)
5239 mp = mc->mc_pg[mc->mc_top];
5244 DPRINTF(("internal error, index points to a %02X page!?",
5246 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5247 return MDB_CORRUPTED;
5250 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
5251 key ? DKEY(key) : "null"));
5252 mc->mc_flags |= C_INITIALIZED;
5253 mc->mc_flags &= ~C_EOF;
5258 /** Search for the lowest key under the current branch page.
5259 * This just bypasses a NUMKEYS check in the current page
5260 * before calling mdb_page_search_root(), because the callers
5261 * are all in situations where the current page is known to
5265 mdb_page_search_lowest(MDB_cursor *mc)
5267 MDB_page *mp = mc->mc_pg[mc->mc_top];
5268 MDB_node *node = NODEPTR(mp, 0);
5271 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5274 mc->mc_ki[mc->mc_top] = 0;
5275 if ((rc = mdb_cursor_push(mc, mp)))
5277 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5280 /** Search for the page a given key should be in.
5281 * Push it and its parent pages on the cursor stack.
5282 * @param[in,out] mc the cursor for this operation.
5283 * @param[in] key the key to search for, or NULL for first/last page.
5284 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5285 * are touched (updated with new page numbers).
5286 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5287 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5288 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5289 * @return 0 on success, non-zero on failure.
5292 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5297 /* Make sure the txn is still viable, then find the root from
5298 * the txn's db table and set it as the root of the cursor's stack.
5300 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
5301 DPUTS("transaction may not be used now");
5304 /* Make sure we're using an up-to-date root */
5305 if (*mc->mc_dbflag & DB_STALE) {
5307 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5309 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5310 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5317 MDB_node *leaf = mdb_node_search(&mc2,
5318 &mc->mc_dbx->md_name, &exact);
5320 return MDB_NOTFOUND;
5321 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
5322 return MDB_INCOMPATIBLE; /* not a named DB */
5323 rc = mdb_node_read(mc->mc_txn, leaf, &data);
5326 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5328 /* The txn may not know this DBI, or another process may
5329 * have dropped and recreated the DB with other flags.
5331 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5332 return MDB_INCOMPATIBLE;
5333 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5335 *mc->mc_dbflag &= ~DB_STALE;
5337 root = mc->mc_db->md_root;
5339 if (root == P_INVALID) { /* Tree is empty. */
5340 DPUTS("tree is empty");
5341 return MDB_NOTFOUND;
5345 mdb_cassert(mc, root > 1);
5346 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5347 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
5353 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5354 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5356 if (flags & MDB_PS_MODIFY) {
5357 if ((rc = mdb_page_touch(mc)))
5361 if (flags & MDB_PS_ROOTONLY)
5364 return mdb_page_search_root(mc, key, flags);
5368 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5370 MDB_txn *txn = mc->mc_txn;
5371 pgno_t pg = mp->mp_pgno;
5372 unsigned x = 0, ovpages = mp->mp_pages;
5373 MDB_env *env = txn->mt_env;
5374 MDB_IDL sl = txn->mt_spill_pgs;
5375 MDB_ID pn = pg << 1;
5378 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5379 /* If the page is dirty or on the spill list we just acquired it,
5380 * so we should give it back to our current free list, if any.
5381 * Otherwise put it onto the list of pages we freed in this txn.
5383 * Won't create me_pghead: me_pglast must be inited along with it.
5384 * Unsupported in nested txns: They would need to hide the page
5385 * range in ancestor txns' dirty and spilled lists.
5387 if (env->me_pghead &&
5389 ((mp->mp_flags & P_DIRTY) ||
5390 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5394 MDB_ID2 *dl, ix, iy;
5395 rc = mdb_midl_need(&env->me_pghead, ovpages);
5398 if (!(mp->mp_flags & P_DIRTY)) {
5399 /* This page is no longer spilled */
5406 /* Remove from dirty list */
5407 dl = txn->mt_u.dirty_list;
5409 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5415 mdb_cassert(mc, x > 1);
5417 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5418 txn->mt_flags |= MDB_TXN_ERROR;
5419 return MDB_CORRUPTED;
5422 if (!(env->me_flags & MDB_WRITEMAP))
5423 mdb_dpage_free(env, mp);
5425 /* Insert in me_pghead */
5426 mop = env->me_pghead;
5427 j = mop[0] + ovpages;
5428 for (i = mop[0]; i && mop[i] < pg; i--)
5434 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5438 mc->mc_db->md_overflow_pages -= ovpages;
5442 /** Return the data associated with a given node.
5443 * @param[in] txn The transaction for this operation.
5444 * @param[in] leaf The node being read.
5445 * @param[out] data Updated to point to the node's data.
5446 * @return 0 on success, non-zero on failure.
5449 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5451 MDB_page *omp; /* overflow page */
5455 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5456 data->mv_size = NODEDSZ(leaf);
5457 data->mv_data = NODEDATA(leaf);
5461 /* Read overflow data.
5463 data->mv_size = NODEDSZ(leaf);
5464 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5465 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5466 DPRINTF(("read overflow page %"Z"u failed", pgno));
5469 data->mv_data = METADATA(omp);
5475 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5476 MDB_val *key, MDB_val *data)
5483 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5485 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
5488 if (txn->mt_flags & MDB_TXN_BLOCKED)
5491 mdb_cursor_init(&mc, txn, dbi, &mx);
5492 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5495 /** Find a sibling for a page.
5496 * Replaces the page at the top of the cursor's stack with the
5497 * specified sibling, if one exists.
5498 * @param[in] mc The cursor for this operation.
5499 * @param[in] move_right Non-zero if the right sibling is requested,
5500 * otherwise the left sibling.
5501 * @return 0 on success, non-zero on failure.
5504 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5510 if (mc->mc_snum < 2) {
5511 return MDB_NOTFOUND; /* root has no siblings */
5515 DPRINTF(("parent page is page %"Z"u, index %u",
5516 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5518 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5519 : (mc->mc_ki[mc->mc_top] == 0)) {
5520 DPRINTF(("no more keys left, moving to %s sibling",
5521 move_right ? "right" : "left"));
5522 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5523 /* undo cursor_pop before returning */
5530 mc->mc_ki[mc->mc_top]++;
5532 mc->mc_ki[mc->mc_top]--;
5533 DPRINTF(("just moving to %s index key %u",
5534 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5536 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5538 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5539 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5540 /* mc will be inconsistent if caller does mc_snum++ as above */
5541 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5545 mdb_cursor_push(mc, mp);
5547 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5552 /** Move the cursor to the next data item. */
5554 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5560 if (mc->mc_flags & C_EOF) {
5561 return MDB_NOTFOUND;
5564 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5566 mp = mc->mc_pg[mc->mc_top];
5568 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5569 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5570 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5571 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5572 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5573 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5574 if (rc == MDB_SUCCESS)
5575 MDB_GET_KEY(leaf, key);
5580 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5581 if (op == MDB_NEXT_DUP)
5582 return MDB_NOTFOUND;
5586 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5587 mdb_dbg_pgno(mp), (void *) mc));
5588 if (mc->mc_flags & C_DEL)
5591 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5592 DPUTS("=====> move to next sibling page");
5593 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5594 mc->mc_flags |= C_EOF;
5597 mp = mc->mc_pg[mc->mc_top];
5598 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5600 mc->mc_ki[mc->mc_top]++;
5603 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5604 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5607 key->mv_size = mc->mc_db->md_pad;
5608 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5612 mdb_cassert(mc, IS_LEAF(mp));
5613 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5615 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5616 mdb_xcursor_init1(mc, leaf);
5619 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5622 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5623 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5624 if (rc != MDB_SUCCESS)
5629 MDB_GET_KEY(leaf, key);
5633 /** Move the cursor to the previous data item. */
5635 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5641 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5643 mp = mc->mc_pg[mc->mc_top];
5645 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5646 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5647 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5648 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5649 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5650 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5651 if (rc == MDB_SUCCESS) {
5652 MDB_GET_KEY(leaf, key);
5653 mc->mc_flags &= ~C_EOF;
5659 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5660 if (op == MDB_PREV_DUP)
5661 return MDB_NOTFOUND;
5665 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5666 mdb_dbg_pgno(mp), (void *) mc));
5668 if (mc->mc_ki[mc->mc_top] == 0) {
5669 DPUTS("=====> move to prev sibling page");
5670 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5673 mp = mc->mc_pg[mc->mc_top];
5674 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5675 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5677 mc->mc_ki[mc->mc_top]--;
5679 mc->mc_flags &= ~C_EOF;
5681 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5682 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5685 key->mv_size = mc->mc_db->md_pad;
5686 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5690 mdb_cassert(mc, IS_LEAF(mp));
5691 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5693 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5694 mdb_xcursor_init1(mc, leaf);
5697 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5700 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5701 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5702 if (rc != MDB_SUCCESS)
5707 MDB_GET_KEY(leaf, key);
5711 /** Set the cursor on a specific data item. */
5713 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5714 MDB_cursor_op op, int *exactp)
5718 MDB_node *leaf = NULL;
5721 if (key->mv_size == 0)
5722 return MDB_BAD_VALSIZE;
5725 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5727 /* See if we're already on the right page */
5728 if (mc->mc_flags & C_INITIALIZED) {
5731 mp = mc->mc_pg[mc->mc_top];
5733 mc->mc_ki[mc->mc_top] = 0;
5734 return MDB_NOTFOUND;
5736 if (mp->mp_flags & P_LEAF2) {
5737 nodekey.mv_size = mc->mc_db->md_pad;
5738 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5740 leaf = NODEPTR(mp, 0);
5741 MDB_GET_KEY2(leaf, nodekey);
5743 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5745 /* Probably happens rarely, but first node on the page
5746 * was the one we wanted.
5748 mc->mc_ki[mc->mc_top] = 0;
5755 unsigned int nkeys = NUMKEYS(mp);
5757 if (mp->mp_flags & P_LEAF2) {
5758 nodekey.mv_data = LEAF2KEY(mp,
5759 nkeys-1, nodekey.mv_size);
5761 leaf = NODEPTR(mp, nkeys-1);
5762 MDB_GET_KEY2(leaf, nodekey);
5764 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5766 /* last node was the one we wanted */
5767 mc->mc_ki[mc->mc_top] = nkeys-1;
5773 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5774 /* This is definitely the right page, skip search_page */
5775 if (mp->mp_flags & P_LEAF2) {
5776 nodekey.mv_data = LEAF2KEY(mp,
5777 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5779 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5780 MDB_GET_KEY2(leaf, nodekey);
5782 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5784 /* current node was the one we wanted */
5794 /* If any parents have right-sibs, search.
5795 * Otherwise, there's nothing further.
5797 for (i=0; i<mc->mc_top; i++)
5799 NUMKEYS(mc->mc_pg[i])-1)
5801 if (i == mc->mc_top) {
5802 /* There are no other pages */
5803 mc->mc_ki[mc->mc_top] = nkeys;
5804 return MDB_NOTFOUND;
5808 /* There are no other pages */
5809 mc->mc_ki[mc->mc_top] = 0;
5810 if (op == MDB_SET_RANGE && !exactp) {
5814 return MDB_NOTFOUND;
5818 rc = mdb_page_search(mc, key, 0);
5819 if (rc != MDB_SUCCESS)
5822 mp = mc->mc_pg[mc->mc_top];
5823 mdb_cassert(mc, IS_LEAF(mp));
5826 leaf = mdb_node_search(mc, key, exactp);
5827 if (exactp != NULL && !*exactp) {
5828 /* MDB_SET specified and not an exact match. */
5829 return MDB_NOTFOUND;
5833 DPUTS("===> inexact leaf not found, goto sibling");
5834 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5835 mc->mc_flags |= C_EOF;
5836 return rc; /* no entries matched */
5838 mp = mc->mc_pg[mc->mc_top];
5839 mdb_cassert(mc, IS_LEAF(mp));
5840 leaf = NODEPTR(mp, 0);
5844 mc->mc_flags |= C_INITIALIZED;
5845 mc->mc_flags &= ~C_EOF;
5848 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5849 key->mv_size = mc->mc_db->md_pad;
5850 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5855 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5856 mdb_xcursor_init1(mc, leaf);
5859 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5860 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5861 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5864 if (op == MDB_GET_BOTH) {
5870 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5871 if (rc != MDB_SUCCESS)
5874 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5877 if ((rc = mdb_node_read(mc->mc_txn, leaf, &olddata)) != MDB_SUCCESS)
5879 dcmp = mc->mc_dbx->md_dcmp;
5880 #if UINT_MAX < SIZE_MAX
5881 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
5882 dcmp = mdb_cmp_clong;
5884 rc = dcmp(data, &olddata);
5886 if (op == MDB_GET_BOTH || rc > 0)
5887 return MDB_NOTFOUND;
5894 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5895 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5900 /* The key already matches in all other cases */
5901 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5902 MDB_GET_KEY(leaf, key);
5903 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5908 /** Move the cursor to the first item in the database. */
5910 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5916 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5918 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5919 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5920 if (rc != MDB_SUCCESS)
5923 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5925 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5926 mc->mc_flags |= C_INITIALIZED;
5927 mc->mc_flags &= ~C_EOF;
5929 mc->mc_ki[mc->mc_top] = 0;
5931 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5932 key->mv_size = mc->mc_db->md_pad;
5933 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5938 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5939 mdb_xcursor_init1(mc, leaf);
5940 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5944 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5948 MDB_GET_KEY(leaf, key);
5952 /** Move the cursor to the last item in the database. */
5954 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5960 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5962 if (!(mc->mc_flags & C_EOF)) {
5964 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5965 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5966 if (rc != MDB_SUCCESS)
5969 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5972 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5973 mc->mc_flags |= C_INITIALIZED|C_EOF;
5974 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5976 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5977 key->mv_size = mc->mc_db->md_pad;
5978 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5983 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5984 mdb_xcursor_init1(mc, leaf);
5985 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5989 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5994 MDB_GET_KEY(leaf, key);
5999 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6004 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
6009 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
6013 case MDB_GET_CURRENT:
6014 if (!(mc->mc_flags & C_INITIALIZED)) {
6017 MDB_page *mp = mc->mc_pg[mc->mc_top];
6018 int nkeys = NUMKEYS(mp);
6019 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
6020 mc->mc_ki[mc->mc_top] = nkeys;
6026 key->mv_size = mc->mc_db->md_pad;
6027 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6029 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6030 MDB_GET_KEY(leaf, key);
6032 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6033 if (mc->mc_flags & C_DEL)
6034 mdb_xcursor_init1(mc, leaf);
6035 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
6037 rc = mdb_node_read(mc->mc_txn, leaf, data);
6044 case MDB_GET_BOTH_RANGE:
6049 if (mc->mc_xcursor == NULL) {
6050 rc = MDB_INCOMPATIBLE;
6060 rc = mdb_cursor_set(mc, key, data, op,
6061 op == MDB_SET_RANGE ? NULL : &exact);
6064 case MDB_GET_MULTIPLE:
6065 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6069 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6070 rc = MDB_INCOMPATIBLE;
6074 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6075 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6078 case MDB_NEXT_MULTIPLE:
6083 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6084 rc = MDB_INCOMPATIBLE;
6087 if (!(mc->mc_flags & C_INITIALIZED))
6088 rc = mdb_cursor_first(mc, key, data);
6090 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6091 if (rc == MDB_SUCCESS) {
6092 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6095 mx = &mc->mc_xcursor->mx_cursor;
6096 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
6098 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
6099 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
6107 case MDB_NEXT_NODUP:
6108 if (!(mc->mc_flags & C_INITIALIZED))
6109 rc = mdb_cursor_first(mc, key, data);
6111 rc = mdb_cursor_next(mc, key, data, op);
6115 case MDB_PREV_NODUP:
6116 if (!(mc->mc_flags & C_INITIALIZED)) {
6117 rc = mdb_cursor_last(mc, key, data);
6120 mc->mc_flags |= C_INITIALIZED;
6121 mc->mc_ki[mc->mc_top]++;
6123 rc = mdb_cursor_prev(mc, key, data, op);
6126 rc = mdb_cursor_first(mc, key, data);
6129 mfunc = mdb_cursor_first;
6131 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6135 if (mc->mc_xcursor == NULL) {
6136 rc = MDB_INCOMPATIBLE;
6140 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6141 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6142 MDB_GET_KEY(leaf, key);
6143 rc = mdb_node_read(mc->mc_txn, leaf, data);
6147 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6151 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
6154 rc = mdb_cursor_last(mc, key, data);
6157 mfunc = mdb_cursor_last;
6160 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
6165 if (mc->mc_flags & C_DEL)
6166 mc->mc_flags ^= C_DEL;
6171 /** Touch all the pages in the cursor stack. Set mc_top.
6172 * Makes sure all the pages are writable, before attempting a write operation.
6173 * @param[in] mc The cursor to operate on.
6176 mdb_cursor_touch(MDB_cursor *mc)
6178 int rc = MDB_SUCCESS;
6180 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & DB_DIRTY)) {
6183 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6185 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
6186 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
6189 *mc->mc_dbflag |= DB_DIRTY;
6194 rc = mdb_page_touch(mc);
6195 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
6196 mc->mc_top = mc->mc_snum-1;
6201 /** Do not spill pages to disk if txn is getting full, may fail instead */
6202 #define MDB_NOSPILL 0x8000
6205 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6209 MDB_node *leaf = NULL;
6210 MDB_page *fp, *mp, *sub_root = NULL;
6212 MDB_val xdata, *rdata, dkey, olddata;
6214 int do_sub = 0, insert_key, insert_data;
6215 unsigned int mcount = 0, dcount = 0, nospill;
6218 unsigned int nflags;
6221 if (mc == NULL || key == NULL)
6224 env = mc->mc_txn->mt_env;
6226 /* Check this first so counter will always be zero on any
6229 if (flags & MDB_MULTIPLE) {
6230 dcount = data[1].mv_size;
6231 data[1].mv_size = 0;
6232 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
6233 return MDB_INCOMPATIBLE;
6236 nospill = flags & MDB_NOSPILL;
6237 flags &= ~MDB_NOSPILL;
6239 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6240 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6242 if (key->mv_size-1 >= ENV_MAXKEY(env))
6243 return MDB_BAD_VALSIZE;
6245 #if SIZE_MAX > MAXDATASIZE
6246 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
6247 return MDB_BAD_VALSIZE;
6249 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
6250 return MDB_BAD_VALSIZE;
6253 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
6254 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
6258 if (flags == MDB_CURRENT) {
6259 if (!(mc->mc_flags & C_INITIALIZED))
6262 } else if (mc->mc_db->md_root == P_INVALID) {
6263 /* new database, cursor has nothing to point to */
6266 mc->mc_flags &= ~C_INITIALIZED;
6271 if (flags & MDB_APPEND) {
6273 rc = mdb_cursor_last(mc, &k2, &d2);
6275 rc = mc->mc_dbx->md_cmp(key, &k2);
6278 mc->mc_ki[mc->mc_top]++;
6280 /* new key is <= last key */
6285 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6287 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6288 DPRINTF(("duplicate key [%s]", DKEY(key)));
6290 return MDB_KEYEXIST;
6292 if (rc && rc != MDB_NOTFOUND)
6296 if (mc->mc_flags & C_DEL)
6297 mc->mc_flags ^= C_DEL;
6299 /* Cursor is positioned, check for room in the dirty list */
6301 if (flags & MDB_MULTIPLE) {
6303 xdata.mv_size = data->mv_size * dcount;
6307 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6311 if (rc == MDB_NO_ROOT) {
6313 /* new database, write a root leaf page */
6314 DPUTS("allocating new root leaf page");
6315 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6318 mdb_cursor_push(mc, np);
6319 mc->mc_db->md_root = np->mp_pgno;
6320 mc->mc_db->md_depth++;
6321 *mc->mc_dbflag |= DB_DIRTY;
6322 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6324 np->mp_flags |= P_LEAF2;
6325 mc->mc_flags |= C_INITIALIZED;
6327 /* make sure all cursor pages are writable */
6328 rc2 = mdb_cursor_touch(mc);
6333 insert_key = insert_data = rc;
6335 /* The key does not exist */
6336 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6337 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6338 LEAFSIZE(key, data) > env->me_nodemax)
6340 /* Too big for a node, insert in sub-DB. Set up an empty
6341 * "old sub-page" for prep_subDB to expand to a full page.
6343 fp_flags = P_LEAF|P_DIRTY;
6345 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6346 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6347 olddata.mv_size = PAGEHDRSZ;
6351 /* there's only a key anyway, so this is a no-op */
6352 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6354 unsigned int ksize = mc->mc_db->md_pad;
6355 if (key->mv_size != ksize)
6356 return MDB_BAD_VALSIZE;
6357 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6358 memcpy(ptr, key->mv_data, ksize);
6360 /* if overwriting slot 0 of leaf, need to
6361 * update branch key if there is a parent page
6363 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6364 unsigned short top = mc->mc_top;
6366 /* slot 0 is always an empty key, find real slot */
6367 while (mc->mc_top && !mc->mc_ki[mc->mc_top])
6369 if (mc->mc_ki[mc->mc_top])
6370 rc2 = mdb_update_key(mc, key);
6381 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6382 olddata.mv_size = NODEDSZ(leaf);
6383 olddata.mv_data = NODEDATA(leaf);
6386 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6387 /* Prepare (sub-)page/sub-DB to accept the new item,
6388 * if needed. fp: old sub-page or a header faking
6389 * it. mp: new (sub-)page. offset: growth in page
6390 * size. xdata: node data with new page or DB.
6392 unsigned i, offset = 0;
6393 mp = fp = xdata.mv_data = env->me_pbuf;
6394 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6396 /* Was a single item before, must convert now */
6397 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6399 /* Just overwrite the current item */
6400 if (flags == MDB_CURRENT)
6402 dcmp = mc->mc_dbx->md_dcmp;
6403 #if UINT_MAX < SIZE_MAX
6404 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6405 dcmp = mdb_cmp_clong;
6407 /* does data match? */
6408 if (!dcmp(data, &olddata)) {
6409 if (flags & MDB_NODUPDATA)
6410 return MDB_KEYEXIST;
6415 /* Back up original data item */
6416 dkey.mv_size = olddata.mv_size;
6417 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6419 /* Make sub-page header for the dup items, with dummy body */
6420 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6421 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6422 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6423 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6424 fp->mp_flags |= P_LEAF2;
6425 fp->mp_pad = data->mv_size;
6426 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6428 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6429 (dkey.mv_size & 1) + (data->mv_size & 1);
6431 fp->mp_upper = xdata.mv_size - PAGEBASE;
6432 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6433 } else if (leaf->mn_flags & F_SUBDATA) {
6434 /* Data is on sub-DB, just store it */
6435 flags |= F_DUPDATA|F_SUBDATA;
6438 /* Data is on sub-page */
6439 fp = olddata.mv_data;
6442 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6443 offset = EVEN(NODESIZE + sizeof(indx_t) +
6447 offset = fp->mp_pad;
6448 if (SIZELEFT(fp) < offset) {
6449 offset *= 4; /* space for 4 more */
6452 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6454 fp->mp_flags |= P_DIRTY;
6455 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6456 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6460 xdata.mv_size = olddata.mv_size + offset;
6463 fp_flags = fp->mp_flags;
6464 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6465 /* Too big for a sub-page, convert to sub-DB */
6466 fp_flags &= ~P_SUBP;
6468 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6469 fp_flags |= P_LEAF2;
6470 dummy.md_pad = fp->mp_pad;
6471 dummy.md_flags = MDB_DUPFIXED;
6472 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6473 dummy.md_flags |= MDB_INTEGERKEY;
6479 dummy.md_branch_pages = 0;
6480 dummy.md_leaf_pages = 1;
6481 dummy.md_overflow_pages = 0;
6482 dummy.md_entries = NUMKEYS(fp);
6483 xdata.mv_size = sizeof(MDB_db);
6484 xdata.mv_data = &dummy;
6485 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6487 offset = env->me_psize - olddata.mv_size;
6488 flags |= F_DUPDATA|F_SUBDATA;
6489 dummy.md_root = mp->mp_pgno;
6493 mp->mp_flags = fp_flags | P_DIRTY;
6494 mp->mp_pad = fp->mp_pad;
6495 mp->mp_lower = fp->mp_lower;
6496 mp->mp_upper = fp->mp_upper + offset;
6497 if (fp_flags & P_LEAF2) {
6498 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6500 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6501 olddata.mv_size - fp->mp_upper - PAGEBASE);
6502 for (i=0; i<NUMKEYS(fp); i++)
6503 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6511 mdb_node_del(mc, 0);
6515 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
6516 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
6517 return MDB_INCOMPATIBLE;
6518 /* overflow page overwrites need special handling */
6519 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6522 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6524 memcpy(&pg, olddata.mv_data, sizeof(pg));
6525 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6527 ovpages = omp->mp_pages;
6529 /* Is the ov page large enough? */
6530 if (ovpages >= dpages) {
6531 if (!(omp->mp_flags & P_DIRTY) &&
6532 (level || (env->me_flags & MDB_WRITEMAP)))
6534 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6537 level = 0; /* dirty in this txn or clean */
6540 if (omp->mp_flags & P_DIRTY) {
6541 /* yes, overwrite it. Note in this case we don't
6542 * bother to try shrinking the page if the new data
6543 * is smaller than the overflow threshold.
6546 /* It is writable only in a parent txn */
6547 size_t sz = (size_t) env->me_psize * ovpages, off;
6548 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6554 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6555 mdb_cassert(mc, rc2 == 0);
6556 if (!(flags & MDB_RESERVE)) {
6557 /* Copy end of page, adjusting alignment so
6558 * compiler may copy words instead of bytes.
6560 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6561 memcpy((size_t *)((char *)np + off),
6562 (size_t *)((char *)omp + off), sz - off);
6565 memcpy(np, omp, sz); /* Copy beginning of page */
6568 SETDSZ(leaf, data->mv_size);
6569 if (F_ISSET(flags, MDB_RESERVE))
6570 data->mv_data = METADATA(omp);
6572 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6576 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6578 } else if (data->mv_size == olddata.mv_size) {
6579 /* same size, just replace it. Note that we could
6580 * also reuse this node if the new data is smaller,
6581 * but instead we opt to shrink the node in that case.
6583 if (F_ISSET(flags, MDB_RESERVE))
6584 data->mv_data = olddata.mv_data;
6585 else if (!(mc->mc_flags & C_SUB))
6586 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6588 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6593 mdb_node_del(mc, 0);
6599 nflags = flags & NODE_ADD_FLAGS;
6600 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6601 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6602 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6603 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6605 nflags |= MDB_SPLIT_REPLACE;
6606 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6608 /* There is room already in this leaf page. */
6609 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6610 if (rc == 0 && insert_key) {
6611 /* Adjust other cursors pointing to mp */
6612 MDB_cursor *m2, *m3;
6613 MDB_dbi dbi = mc->mc_dbi;
6614 unsigned i = mc->mc_top;
6615 MDB_page *mp = mc->mc_pg[i];
6617 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6618 if (mc->mc_flags & C_SUB)
6619 m3 = &m2->mc_xcursor->mx_cursor;
6622 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6623 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6630 if (rc == MDB_SUCCESS) {
6631 /* Now store the actual data in the child DB. Note that we're
6632 * storing the user data in the keys field, so there are strict
6633 * size limits on dupdata. The actual data fields of the child
6634 * DB are all zero size.
6637 int xflags, new_dupdata;
6642 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6643 if (flags & MDB_CURRENT) {
6644 xflags = MDB_CURRENT|MDB_NOSPILL;
6646 mdb_xcursor_init1(mc, leaf);
6647 xflags = (flags & MDB_NODUPDATA) ?
6648 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6651 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
6652 new_dupdata = (int)dkey.mv_size;
6653 /* converted, write the original data first */
6655 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6658 /* we've done our job */
6661 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
6662 /* Adjust other cursors pointing to mp */
6664 MDB_xcursor *mx = mc->mc_xcursor;
6665 unsigned i = mc->mc_top;
6666 MDB_page *mp = mc->mc_pg[i];
6668 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6669 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6670 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6671 if (m2->mc_pg[i] == mp) {
6672 if (m2->mc_ki[i] == mc->mc_ki[i]) {
6673 mdb_xcursor_init2(m2, mx, new_dupdata);
6674 } else if (!insert_key) {
6675 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[i]);
6676 if (!(n2->mn_flags & F_SUBDATA))
6677 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
6682 ecount = mc->mc_xcursor->mx_db.md_entries;
6683 if (flags & MDB_APPENDDUP)
6684 xflags |= MDB_APPEND;
6685 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6686 if (flags & F_SUBDATA) {
6687 void *db = NODEDATA(leaf);
6688 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6690 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6692 /* Increment count unless we just replaced an existing item. */
6694 mc->mc_db->md_entries++;
6696 /* Invalidate txn if we created an empty sub-DB */
6699 /* If we succeeded and the key didn't exist before,
6700 * make sure the cursor is marked valid.
6702 mc->mc_flags |= C_INITIALIZED;
6704 if (flags & MDB_MULTIPLE) {
6707 /* let caller know how many succeeded, if any */
6708 data[1].mv_size = mcount;
6709 if (mcount < dcount) {
6710 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6711 insert_key = insert_data = 0;
6718 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6721 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6726 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6732 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6733 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6735 if (!(mc->mc_flags & C_INITIALIZED))
6738 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6739 return MDB_NOTFOUND;
6741 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6744 rc = mdb_cursor_touch(mc);
6748 mp = mc->mc_pg[mc->mc_top];
6751 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6753 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6754 if (flags & MDB_NODUPDATA) {
6755 /* mdb_cursor_del0() will subtract the final entry */
6756 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6758 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6759 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6761 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6764 /* If sub-DB still has entries, we're done */
6765 if (mc->mc_xcursor->mx_db.md_entries) {
6766 if (leaf->mn_flags & F_SUBDATA) {
6767 /* update subDB info */
6768 void *db = NODEDATA(leaf);
6769 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6772 /* shrink fake page */
6773 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6774 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6775 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6776 /* fix other sub-DB cursors pointed at fake pages on this page */
6777 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6778 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6779 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6780 if (m2->mc_pg[mc->mc_top] == mp) {
6781 if (m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top]) {
6782 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6784 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
6785 if (!(n2->mn_flags & F_SUBDATA))
6786 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
6791 mc->mc_db->md_entries--;
6792 mc->mc_flags |= C_DEL;
6795 /* otherwise fall thru and delete the sub-DB */
6798 if (leaf->mn_flags & F_SUBDATA) {
6799 /* add all the child DB's pages to the free list */
6800 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6805 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
6806 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
6807 rc = MDB_INCOMPATIBLE;
6811 /* add overflow pages to free list */
6812 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6816 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6817 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6818 (rc = mdb_ovpage_free(mc, omp)))
6823 return mdb_cursor_del0(mc);
6826 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6830 /** Allocate and initialize new pages for a database.
6831 * @param[in] mc a cursor on the database being added to.
6832 * @param[in] flags flags defining what type of page is being allocated.
6833 * @param[in] num the number of pages to allocate. This is usually 1,
6834 * unless allocating overflow pages for a large record.
6835 * @param[out] mp Address of a page, or NULL on failure.
6836 * @return 0 on success, non-zero on failure.
6839 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6844 if ((rc = mdb_page_alloc(mc, num, &np)))
6846 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6847 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6848 np->mp_flags = flags | P_DIRTY;
6849 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
6850 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
6853 mc->mc_db->md_branch_pages++;
6854 else if (IS_LEAF(np))
6855 mc->mc_db->md_leaf_pages++;
6856 else if (IS_OVERFLOW(np)) {
6857 mc->mc_db->md_overflow_pages += num;
6865 /** Calculate the size of a leaf node.
6866 * The size depends on the environment's page size; if a data item
6867 * is too large it will be put onto an overflow page and the node
6868 * size will only include the key and not the data. Sizes are always
6869 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6870 * of the #MDB_node headers.
6871 * @param[in] env The environment handle.
6872 * @param[in] key The key for the node.
6873 * @param[in] data The data for the node.
6874 * @return The number of bytes needed to store the node.
6877 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6881 sz = LEAFSIZE(key, data);
6882 if (sz > env->me_nodemax) {
6883 /* put on overflow page */
6884 sz -= data->mv_size - sizeof(pgno_t);
6887 return EVEN(sz + sizeof(indx_t));
6890 /** Calculate the size of a branch node.
6891 * The size should depend on the environment's page size but since
6892 * we currently don't support spilling large keys onto overflow
6893 * pages, it's simply the size of the #MDB_node header plus the
6894 * size of the key. Sizes are always rounded up to an even number
6895 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6896 * @param[in] env The environment handle.
6897 * @param[in] key The key for the node.
6898 * @return The number of bytes needed to store the node.
6901 mdb_branch_size(MDB_env *env, MDB_val *key)
6906 if (sz > env->me_nodemax) {
6907 /* put on overflow page */
6908 /* not implemented */
6909 /* sz -= key->size - sizeof(pgno_t); */
6912 return sz + sizeof(indx_t);
6915 /** Add a node to the page pointed to by the cursor.
6916 * @param[in] mc The cursor for this operation.
6917 * @param[in] indx The index on the page where the new node should be added.
6918 * @param[in] key The key for the new node.
6919 * @param[in] data The data for the new node, if any.
6920 * @param[in] pgno The page number, if adding a branch node.
6921 * @param[in] flags Flags for the node.
6922 * @return 0 on success, non-zero on failure. Possible errors are:
6924 * <li>ENOMEM - failed to allocate overflow pages for the node.
6925 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6926 * should never happen since all callers already calculate the
6927 * page's free space before calling this function.
6931 mdb_node_add(MDB_cursor *mc, indx_t indx,
6932 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6935 size_t node_size = NODESIZE;
6939 MDB_page *mp = mc->mc_pg[mc->mc_top];
6940 MDB_page *ofp = NULL; /* overflow page */
6944 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
6946 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6947 IS_LEAF(mp) ? "leaf" : "branch",
6948 IS_SUBP(mp) ? "sub-" : "",
6949 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
6950 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6953 /* Move higher keys up one slot. */
6954 int ksize = mc->mc_db->md_pad, dif;
6955 char *ptr = LEAF2KEY(mp, indx, ksize);
6956 dif = NUMKEYS(mp) - indx;
6958 memmove(ptr+ksize, ptr, dif*ksize);
6959 /* insert new key */
6960 memcpy(ptr, key->mv_data, ksize);
6962 /* Just using these for counting */
6963 mp->mp_lower += sizeof(indx_t);
6964 mp->mp_upper -= ksize - sizeof(indx_t);
6968 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6970 node_size += key->mv_size;
6972 mdb_cassert(mc, key && data);
6973 if (F_ISSET(flags, F_BIGDATA)) {
6974 /* Data already on overflow page. */
6975 node_size += sizeof(pgno_t);
6976 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
6977 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6979 /* Put data on overflow page. */
6980 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6981 data->mv_size, node_size+data->mv_size));
6982 node_size = EVEN(node_size + sizeof(pgno_t));
6983 if ((ssize_t)node_size > room)
6985 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6987 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6991 node_size += data->mv_size;
6994 node_size = EVEN(node_size);
6995 if ((ssize_t)node_size > room)
6999 /* Move higher pointers up one slot. */
7000 for (i = NUMKEYS(mp); i > indx; i--)
7001 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
7003 /* Adjust free space offsets. */
7004 ofs = mp->mp_upper - node_size;
7005 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
7006 mp->mp_ptrs[indx] = ofs;
7008 mp->mp_lower += sizeof(indx_t);
7010 /* Write the node data. */
7011 node = NODEPTR(mp, indx);
7012 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
7013 node->mn_flags = flags;
7015 SETDSZ(node,data->mv_size);
7020 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7023 ndata = NODEDATA(node);
7025 if (F_ISSET(flags, F_BIGDATA))
7026 memcpy(ndata, data->mv_data, sizeof(pgno_t));
7027 else if (F_ISSET(flags, MDB_RESERVE))
7028 data->mv_data = ndata;
7030 memcpy(ndata, data->mv_data, data->mv_size);
7032 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
7033 ndata = METADATA(ofp);
7034 if (F_ISSET(flags, MDB_RESERVE))
7035 data->mv_data = ndata;
7037 memcpy(ndata, data->mv_data, data->mv_size);
7044 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
7045 mdb_dbg_pgno(mp), NUMKEYS(mp)));
7046 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
7047 DPRINTF(("node size = %"Z"u", node_size));
7048 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7049 return MDB_PAGE_FULL;
7052 /** Delete the specified node from a page.
7053 * @param[in] mc Cursor pointing to the node to delete.
7054 * @param[in] ksize The size of a node. Only used if the page is
7055 * part of a #MDB_DUPFIXED database.
7058 mdb_node_del(MDB_cursor *mc, int ksize)
7060 MDB_page *mp = mc->mc_pg[mc->mc_top];
7061 indx_t indx = mc->mc_ki[mc->mc_top];
7063 indx_t i, j, numkeys, ptr;
7067 DPRINTF(("delete node %u on %s page %"Z"u", indx,
7068 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
7069 numkeys = NUMKEYS(mp);
7070 mdb_cassert(mc, indx < numkeys);
7073 int x = numkeys - 1 - indx;
7074 base = LEAF2KEY(mp, indx, ksize);
7076 memmove(base, base + ksize, x * ksize);
7077 mp->mp_lower -= sizeof(indx_t);
7078 mp->mp_upper += ksize - sizeof(indx_t);
7082 node = NODEPTR(mp, indx);
7083 sz = NODESIZE + node->mn_ksize;
7085 if (F_ISSET(node->mn_flags, F_BIGDATA))
7086 sz += sizeof(pgno_t);
7088 sz += NODEDSZ(node);
7092 ptr = mp->mp_ptrs[indx];
7093 for (i = j = 0; i < numkeys; i++) {
7095 mp->mp_ptrs[j] = mp->mp_ptrs[i];
7096 if (mp->mp_ptrs[i] < ptr)
7097 mp->mp_ptrs[j] += sz;
7102 base = (char *)mp + mp->mp_upper + PAGEBASE;
7103 memmove(base + sz, base, ptr - mp->mp_upper);
7105 mp->mp_lower -= sizeof(indx_t);
7109 /** Compact the main page after deleting a node on a subpage.
7110 * @param[in] mp The main page to operate on.
7111 * @param[in] indx The index of the subpage on the main page.
7114 mdb_node_shrink(MDB_page *mp, indx_t indx)
7119 indx_t delta, nsize, len, ptr;
7122 node = NODEPTR(mp, indx);
7123 sp = (MDB_page *)NODEDATA(node);
7124 delta = SIZELEFT(sp);
7125 nsize = NODEDSZ(node) - delta;
7127 /* Prepare to shift upward, set len = length(subpage part to shift) */
7131 return; /* do not make the node uneven-sized */
7133 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
7134 for (i = NUMKEYS(sp); --i >= 0; )
7135 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
7138 sp->mp_upper = sp->mp_lower;
7139 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
7140 SETDSZ(node, nsize);
7142 /* Shift <lower nodes...initial part of subpage> upward */
7143 base = (char *)mp + mp->mp_upper + PAGEBASE;
7144 memmove(base + delta, base, (char *)sp + len - base);
7146 ptr = mp->mp_ptrs[indx];
7147 for (i = NUMKEYS(mp); --i >= 0; ) {
7148 if (mp->mp_ptrs[i] <= ptr)
7149 mp->mp_ptrs[i] += delta;
7151 mp->mp_upper += delta;
7154 /** Initial setup of a sorted-dups cursor.
7155 * Sorted duplicates are implemented as a sub-database for the given key.
7156 * The duplicate data items are actually keys of the sub-database.
7157 * Operations on the duplicate data items are performed using a sub-cursor
7158 * initialized when the sub-database is first accessed. This function does
7159 * the preliminary setup of the sub-cursor, filling in the fields that
7160 * depend only on the parent DB.
7161 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7164 mdb_xcursor_init0(MDB_cursor *mc)
7166 MDB_xcursor *mx = mc->mc_xcursor;
7168 mx->mx_cursor.mc_xcursor = NULL;
7169 mx->mx_cursor.mc_txn = mc->mc_txn;
7170 mx->mx_cursor.mc_db = &mx->mx_db;
7171 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
7172 mx->mx_cursor.mc_dbi = mc->mc_dbi;
7173 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
7174 mx->mx_cursor.mc_snum = 0;
7175 mx->mx_cursor.mc_top = 0;
7176 mx->mx_cursor.mc_flags = C_SUB;
7177 mx->mx_dbx.md_name.mv_size = 0;
7178 mx->mx_dbx.md_name.mv_data = NULL;
7179 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
7180 mx->mx_dbx.md_dcmp = NULL;
7181 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
7184 /** Final setup of a sorted-dups cursor.
7185 * Sets up the fields that depend on the data from the main cursor.
7186 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7187 * @param[in] node The data containing the #MDB_db record for the
7188 * sorted-dup database.
7191 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
7193 MDB_xcursor *mx = mc->mc_xcursor;
7195 if (node->mn_flags & F_SUBDATA) {
7196 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
7197 mx->mx_cursor.mc_pg[0] = 0;
7198 mx->mx_cursor.mc_snum = 0;
7199 mx->mx_cursor.mc_top = 0;
7200 mx->mx_cursor.mc_flags = C_SUB;
7202 MDB_page *fp = NODEDATA(node);
7203 mx->mx_db.md_pad = 0;
7204 mx->mx_db.md_flags = 0;
7205 mx->mx_db.md_depth = 1;
7206 mx->mx_db.md_branch_pages = 0;
7207 mx->mx_db.md_leaf_pages = 1;
7208 mx->mx_db.md_overflow_pages = 0;
7209 mx->mx_db.md_entries = NUMKEYS(fp);
7210 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
7211 mx->mx_cursor.mc_snum = 1;
7212 mx->mx_cursor.mc_top = 0;
7213 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
7214 mx->mx_cursor.mc_pg[0] = fp;
7215 mx->mx_cursor.mc_ki[0] = 0;
7216 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7217 mx->mx_db.md_flags = MDB_DUPFIXED;
7218 mx->mx_db.md_pad = fp->mp_pad;
7219 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7220 mx->mx_db.md_flags |= MDB_INTEGERKEY;
7223 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7224 mx->mx_db.md_root));
7225 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
7226 #if UINT_MAX < SIZE_MAX
7227 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
7228 mx->mx_dbx.md_cmp = mdb_cmp_clong;
7233 /** Fixup a sorted-dups cursor due to underlying update.
7234 * Sets up some fields that depend on the data from the main cursor.
7235 * Almost the same as init1, but skips initialization steps if the
7236 * xcursor had already been used.
7237 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
7238 * @param[in] src_mx The xcursor of an up-to-date cursor.
7239 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
7242 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
7244 MDB_xcursor *mx = mc->mc_xcursor;
7247 mx->mx_cursor.mc_snum = 1;
7248 mx->mx_cursor.mc_top = 0;
7249 mx->mx_cursor.mc_flags |= C_INITIALIZED;
7250 mx->mx_cursor.mc_ki[0] = 0;
7251 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
7252 #if UINT_MAX < SIZE_MAX
7253 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
7255 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
7258 mx->mx_db = src_mx->mx_db;
7259 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
7260 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7261 mx->mx_db.md_root));
7264 /** Initialize a cursor for a given transaction and database. */
7266 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
7269 mc->mc_backup = NULL;
7272 mc->mc_db = &txn->mt_dbs[dbi];
7273 mc->mc_dbx = &txn->mt_dbxs[dbi];
7274 mc->mc_dbflag = &txn->mt_dbflags[dbi];
7280 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
7281 mdb_tassert(txn, mx != NULL);
7282 mc->mc_xcursor = mx;
7283 mdb_xcursor_init0(mc);
7285 mc->mc_xcursor = NULL;
7287 if (*mc->mc_dbflag & DB_STALE) {
7288 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
7293 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
7296 size_t size = sizeof(MDB_cursor);
7298 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
7301 if (txn->mt_flags & MDB_TXN_BLOCKED)
7304 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7307 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
7308 size += sizeof(MDB_xcursor);
7310 if ((mc = malloc(size)) != NULL) {
7311 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
7312 if (txn->mt_cursors) {
7313 mc->mc_next = txn->mt_cursors[dbi];
7314 txn->mt_cursors[dbi] = mc;
7315 mc->mc_flags |= C_UNTRACK;
7327 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
7329 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
7332 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
7335 if (txn->mt_flags & MDB_TXN_BLOCKED)
7338 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
7342 /* Return the count of duplicate data items for the current key */
7344 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7348 if (mc == NULL || countp == NULL)
7351 if (mc->mc_xcursor == NULL)
7352 return MDB_INCOMPATIBLE;
7354 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
7357 if (!(mc->mc_flags & C_INITIALIZED))
7360 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
7361 return MDB_NOTFOUND;
7363 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7364 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7367 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7370 *countp = mc->mc_xcursor->mx_db.md_entries;
7376 mdb_cursor_close(MDB_cursor *mc)
7378 if (mc && !mc->mc_backup) {
7379 /* remove from txn, if tracked */
7380 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7381 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7382 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7384 *prev = mc->mc_next;
7391 mdb_cursor_txn(MDB_cursor *mc)
7393 if (!mc) return NULL;
7398 mdb_cursor_dbi(MDB_cursor *mc)
7403 /** Replace the key for a branch node with a new key.
7404 * @param[in] mc Cursor pointing to the node to operate on.
7405 * @param[in] key The new key to use.
7406 * @return 0 on success, non-zero on failure.
7409 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7415 int delta, ksize, oksize;
7416 indx_t ptr, i, numkeys, indx;
7419 indx = mc->mc_ki[mc->mc_top];
7420 mp = mc->mc_pg[mc->mc_top];
7421 node = NODEPTR(mp, indx);
7422 ptr = mp->mp_ptrs[indx];
7426 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7427 k2.mv_data = NODEKEY(node);
7428 k2.mv_size = node->mn_ksize;
7429 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7431 mdb_dkey(&k2, kbuf2),
7437 /* Sizes must be 2-byte aligned. */
7438 ksize = EVEN(key->mv_size);
7439 oksize = EVEN(node->mn_ksize);
7440 delta = ksize - oksize;
7442 /* Shift node contents if EVEN(key length) changed. */
7444 if (delta > 0 && SIZELEFT(mp) < delta) {
7446 /* not enough space left, do a delete and split */
7447 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7448 pgno = NODEPGNO(node);
7449 mdb_node_del(mc, 0);
7450 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7453 numkeys = NUMKEYS(mp);
7454 for (i = 0; i < numkeys; i++) {
7455 if (mp->mp_ptrs[i] <= ptr)
7456 mp->mp_ptrs[i] -= delta;
7459 base = (char *)mp + mp->mp_upper + PAGEBASE;
7460 len = ptr - mp->mp_upper + NODESIZE;
7461 memmove(base - delta, base, len);
7462 mp->mp_upper -= delta;
7464 node = NODEPTR(mp, indx);
7467 /* But even if no shift was needed, update ksize */
7468 if (node->mn_ksize != key->mv_size)
7469 node->mn_ksize = key->mv_size;
7472 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7478 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7480 /** Move a node from csrc to cdst.
7483 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
7490 unsigned short flags;
7494 /* Mark src and dst as dirty. */
7495 if ((rc = mdb_page_touch(csrc)) ||
7496 (rc = mdb_page_touch(cdst)))
7499 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7500 key.mv_size = csrc->mc_db->md_pad;
7501 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7503 data.mv_data = NULL;
7507 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7508 mdb_cassert(csrc, !((size_t)srcnode & 1));
7509 srcpg = NODEPGNO(srcnode);
7510 flags = srcnode->mn_flags;
7511 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7512 unsigned int snum = csrc->mc_snum;
7514 /* must find the lowest key below src */
7515 rc = mdb_page_search_lowest(csrc);
7518 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7519 key.mv_size = csrc->mc_db->md_pad;
7520 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7522 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7523 key.mv_size = NODEKSZ(s2);
7524 key.mv_data = NODEKEY(s2);
7526 csrc->mc_snum = snum--;
7527 csrc->mc_top = snum;
7529 key.mv_size = NODEKSZ(srcnode);
7530 key.mv_data = NODEKEY(srcnode);
7532 data.mv_size = NODEDSZ(srcnode);
7533 data.mv_data = NODEDATA(srcnode);
7535 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7536 unsigned int snum = cdst->mc_snum;
7539 /* must find the lowest key below dst */
7540 mdb_cursor_copy(cdst, &mn);
7541 rc = mdb_page_search_lowest(&mn);
7544 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7545 bkey.mv_size = mn.mc_db->md_pad;
7546 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7548 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7549 bkey.mv_size = NODEKSZ(s2);
7550 bkey.mv_data = NODEKEY(s2);
7552 mn.mc_snum = snum--;
7555 rc = mdb_update_key(&mn, &bkey);
7560 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7561 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7562 csrc->mc_ki[csrc->mc_top],
7564 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7565 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7567 /* Add the node to the destination page.
7569 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7570 if (rc != MDB_SUCCESS)
7573 /* Delete the node from the source page.
7575 mdb_node_del(csrc, key.mv_size);
7578 /* Adjust other cursors pointing to mp */
7579 MDB_cursor *m2, *m3;
7580 MDB_dbi dbi = csrc->mc_dbi;
7583 mp = cdst->mc_pg[csrc->mc_top];
7584 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7585 if (csrc->mc_flags & C_SUB)
7586 m3 = &m2->mc_xcursor->mx_cursor;
7589 if (m3 == cdst) continue;
7590 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] >=
7591 cdst->mc_ki[csrc->mc_top]) {
7592 m3->mc_ki[csrc->mc_top]++;
7596 mp = csrc->mc_pg[csrc->mc_top];
7597 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7598 if (csrc->mc_flags & C_SUB)
7599 m3 = &m2->mc_xcursor->mx_cursor;
7602 if (m3 == csrc) continue;
7603 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
7604 csrc->mc_ki[csrc->mc_top]) {
7605 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7606 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7611 /* Update the parent separators.
7613 if (csrc->mc_ki[csrc->mc_top] == 0) {
7614 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7615 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7616 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7618 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7619 key.mv_size = NODEKSZ(srcnode);
7620 key.mv_data = NODEKEY(srcnode);
7622 DPRINTF(("update separator for source page %"Z"u to [%s]",
7623 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7624 mdb_cursor_copy(csrc, &mn);
7627 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7630 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7632 indx_t ix = csrc->mc_ki[csrc->mc_top];
7633 nullkey.mv_size = 0;
7634 csrc->mc_ki[csrc->mc_top] = 0;
7635 rc = mdb_update_key(csrc, &nullkey);
7636 csrc->mc_ki[csrc->mc_top] = ix;
7637 mdb_cassert(csrc, rc == MDB_SUCCESS);
7641 if (cdst->mc_ki[cdst->mc_top] == 0) {
7642 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7643 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7644 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7646 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7647 key.mv_size = NODEKSZ(srcnode);
7648 key.mv_data = NODEKEY(srcnode);
7650 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7651 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7652 mdb_cursor_copy(cdst, &mn);
7655 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7658 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7660 indx_t ix = cdst->mc_ki[cdst->mc_top];
7661 nullkey.mv_size = 0;
7662 cdst->mc_ki[cdst->mc_top] = 0;
7663 rc = mdb_update_key(cdst, &nullkey);
7664 cdst->mc_ki[cdst->mc_top] = ix;
7665 mdb_cassert(cdst, rc == MDB_SUCCESS);
7672 /** Merge one page into another.
7673 * The nodes from the page pointed to by \b csrc will
7674 * be copied to the page pointed to by \b cdst and then
7675 * the \b csrc page will be freed.
7676 * @param[in] csrc Cursor pointing to the source page.
7677 * @param[in] cdst Cursor pointing to the destination page.
7678 * @return 0 on success, non-zero on failure.
7681 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7683 MDB_page *psrc, *pdst;
7690 psrc = csrc->mc_pg[csrc->mc_top];
7691 pdst = cdst->mc_pg[cdst->mc_top];
7693 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7695 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7696 mdb_cassert(csrc, cdst->mc_snum > 1);
7698 /* Mark dst as dirty. */
7699 if ((rc = mdb_page_touch(cdst)))
7702 /* Move all nodes from src to dst.
7704 j = nkeys = NUMKEYS(pdst);
7705 if (IS_LEAF2(psrc)) {
7706 key.mv_size = csrc->mc_db->md_pad;
7707 key.mv_data = METADATA(psrc);
7708 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7709 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7710 if (rc != MDB_SUCCESS)
7712 key.mv_data = (char *)key.mv_data + key.mv_size;
7715 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7716 srcnode = NODEPTR(psrc, i);
7717 if (i == 0 && IS_BRANCH(psrc)) {
7720 mdb_cursor_copy(csrc, &mn);
7721 /* must find the lowest key below src */
7722 rc = mdb_page_search_lowest(&mn);
7725 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7726 key.mv_size = mn.mc_db->md_pad;
7727 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7729 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7730 key.mv_size = NODEKSZ(s2);
7731 key.mv_data = NODEKEY(s2);
7734 key.mv_size = srcnode->mn_ksize;
7735 key.mv_data = NODEKEY(srcnode);
7738 data.mv_size = NODEDSZ(srcnode);
7739 data.mv_data = NODEDATA(srcnode);
7740 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7741 if (rc != MDB_SUCCESS)
7746 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7747 pdst->mp_pgno, NUMKEYS(pdst),
7748 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7750 /* Unlink the src page from parent and add to free list.
7753 mdb_node_del(csrc, 0);
7754 if (csrc->mc_ki[csrc->mc_top] == 0) {
7756 rc = mdb_update_key(csrc, &key);
7764 psrc = csrc->mc_pg[csrc->mc_top];
7765 /* If not operating on FreeDB, allow this page to be reused
7766 * in this txn. Otherwise just add to free list.
7768 rc = mdb_page_loose(csrc, psrc);
7772 csrc->mc_db->md_leaf_pages--;
7774 csrc->mc_db->md_branch_pages--;
7776 /* Adjust other cursors pointing to mp */
7777 MDB_cursor *m2, *m3;
7778 MDB_dbi dbi = csrc->mc_dbi;
7780 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7781 if (csrc->mc_flags & C_SUB)
7782 m3 = &m2->mc_xcursor->mx_cursor;
7785 if (m3 == csrc) continue;
7786 if (m3->mc_snum < csrc->mc_snum) continue;
7787 if (m3->mc_pg[csrc->mc_top] == psrc) {
7788 m3->mc_pg[csrc->mc_top] = pdst;
7789 m3->mc_ki[csrc->mc_top] += nkeys;
7794 unsigned int snum = cdst->mc_snum;
7795 uint16_t depth = cdst->mc_db->md_depth;
7796 mdb_cursor_pop(cdst);
7797 rc = mdb_rebalance(cdst);
7798 /* Did the tree height change? */
7799 if (depth != cdst->mc_db->md_depth)
7800 snum += cdst->mc_db->md_depth - depth;
7801 cdst->mc_snum = snum;
7802 cdst->mc_top = snum-1;
7807 /** Copy the contents of a cursor.
7808 * @param[in] csrc The cursor to copy from.
7809 * @param[out] cdst The cursor to copy to.
7812 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7816 cdst->mc_txn = csrc->mc_txn;
7817 cdst->mc_dbi = csrc->mc_dbi;
7818 cdst->mc_db = csrc->mc_db;
7819 cdst->mc_dbx = csrc->mc_dbx;
7820 cdst->mc_snum = csrc->mc_snum;
7821 cdst->mc_top = csrc->mc_top;
7822 cdst->mc_flags = csrc->mc_flags;
7824 for (i=0; i<csrc->mc_snum; i++) {
7825 cdst->mc_pg[i] = csrc->mc_pg[i];
7826 cdst->mc_ki[i] = csrc->mc_ki[i];
7830 /** Rebalance the tree after a delete operation.
7831 * @param[in] mc Cursor pointing to the page where rebalancing
7833 * @return 0 on success, non-zero on failure.
7836 mdb_rebalance(MDB_cursor *mc)
7840 unsigned int ptop, minkeys, thresh;
7844 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
7849 thresh = FILL_THRESHOLD;
7851 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7852 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7853 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7854 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7856 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
7857 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7858 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7859 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7863 if (mc->mc_snum < 2) {
7864 MDB_page *mp = mc->mc_pg[0];
7866 DPUTS("Can't rebalance a subpage, ignoring");
7869 if (NUMKEYS(mp) == 0) {
7870 DPUTS("tree is completely empty");
7871 mc->mc_db->md_root = P_INVALID;
7872 mc->mc_db->md_depth = 0;
7873 mc->mc_db->md_leaf_pages = 0;
7874 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7877 /* Adjust cursors pointing to mp */
7880 mc->mc_flags &= ~C_INITIALIZED;
7882 MDB_cursor *m2, *m3;
7883 MDB_dbi dbi = mc->mc_dbi;
7885 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7886 if (mc->mc_flags & C_SUB)
7887 m3 = &m2->mc_xcursor->mx_cursor;
7890 if (m3->mc_snum < mc->mc_snum) continue;
7891 if (m3->mc_pg[0] == mp) {
7894 m3->mc_flags &= ~C_INITIALIZED;
7898 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7900 DPUTS("collapsing root page!");
7901 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7904 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7905 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7908 mc->mc_db->md_depth--;
7909 mc->mc_db->md_branch_pages--;
7910 mc->mc_ki[0] = mc->mc_ki[1];
7911 for (i = 1; i<mc->mc_db->md_depth; i++) {
7912 mc->mc_pg[i] = mc->mc_pg[i+1];
7913 mc->mc_ki[i] = mc->mc_ki[i+1];
7916 /* Adjust other cursors pointing to mp */
7917 MDB_cursor *m2, *m3;
7918 MDB_dbi dbi = mc->mc_dbi;
7920 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7921 if (mc->mc_flags & C_SUB)
7922 m3 = &m2->mc_xcursor->mx_cursor;
7925 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7926 if (m3->mc_pg[0] == mp) {
7927 for (i=0; i<m3->mc_snum; i++) {
7928 m3->mc_pg[i] = m3->mc_pg[i+1];
7929 m3->mc_ki[i] = m3->mc_ki[i+1];
7937 DPUTS("root page doesn't need rebalancing");
7941 /* The parent (branch page) must have at least 2 pointers,
7942 * otherwise the tree is invalid.
7944 ptop = mc->mc_top-1;
7945 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
7947 /* Leaf page fill factor is below the threshold.
7948 * Try to move keys from left or right neighbor, or
7949 * merge with a neighbor page.
7954 mdb_cursor_copy(mc, &mn);
7955 mn.mc_xcursor = NULL;
7957 oldki = mc->mc_ki[mc->mc_top];
7958 if (mc->mc_ki[ptop] == 0) {
7959 /* We're the leftmost leaf in our parent.
7961 DPUTS("reading right neighbor");
7963 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7964 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7967 mn.mc_ki[mn.mc_top] = 0;
7968 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7970 /* There is at least one neighbor to the left.
7972 DPUTS("reading left neighbor");
7974 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7975 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7978 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7979 mc->mc_ki[mc->mc_top] = 0;
7982 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7983 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7984 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7986 /* If the neighbor page is above threshold and has enough keys,
7987 * move one key from it. Otherwise we should try to merge them.
7988 * (A branch page must never have less than 2 keys.)
7990 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
7991 rc = mdb_node_move(&mn, mc);
7992 if (mc->mc_ki[mc->mc_top-1]) {
7996 if (mc->mc_ki[ptop] == 0) {
7997 rc = mdb_page_merge(&mn, mc);
8000 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
8001 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
8002 /* We want mdb_rebalance to find mn when doing fixups */
8003 if (mc->mc_flags & C_SUB) {
8004 dummy.mc_next = mc->mc_txn->mt_cursors[mc->mc_dbi];
8005 mc->mc_txn->mt_cursors[mc->mc_dbi] = &dummy;
8006 dummy.mc_xcursor = (MDB_xcursor *)&mn;
8008 mn.mc_next = mc->mc_txn->mt_cursors[mc->mc_dbi];
8009 mc->mc_txn->mt_cursors[mc->mc_dbi] = &mn;
8011 rc = mdb_page_merge(mc, &mn);
8012 if (mc->mc_flags & C_SUB)
8013 mc->mc_txn->mt_cursors[mc->mc_dbi] = dummy.mc_next;
8015 mc->mc_txn->mt_cursors[mc->mc_dbi] = mn.mc_next;
8016 mdb_cursor_copy(&mn, mc);
8018 mc->mc_flags &= ~C_EOF;
8020 mc->mc_ki[mc->mc_top] = oldki;
8024 /** Complete a delete operation started by #mdb_cursor_del(). */
8026 mdb_cursor_del0(MDB_cursor *mc)
8032 MDB_cursor *m2, *m3;
8033 MDB_dbi dbi = mc->mc_dbi;
8035 ki = mc->mc_ki[mc->mc_top];
8036 mp = mc->mc_pg[mc->mc_top];
8037 mdb_node_del(mc, mc->mc_db->md_pad);
8038 mc->mc_db->md_entries--;
8040 /* Adjust other cursors pointing to mp */
8041 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8042 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8043 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8045 if (m3 == mc || m3->mc_snum < mc->mc_snum)
8047 if (m3->mc_pg[mc->mc_top] == mp) {
8048 if (m3->mc_ki[mc->mc_top] >= ki) {
8049 m3->mc_flags |= C_DEL;
8050 if (m3->mc_ki[mc->mc_top] > ki)
8051 m3->mc_ki[mc->mc_top]--;
8052 else if (mc->mc_db->md_flags & MDB_DUPSORT)
8053 m3->mc_xcursor->mx_cursor.mc_flags |= C_EOF;
8058 rc = mdb_rebalance(mc);
8060 if (rc == MDB_SUCCESS) {
8061 /* DB is totally empty now, just bail out.
8062 * Other cursors adjustments were already done
8063 * by mdb_rebalance and aren't needed here.
8068 mp = mc->mc_pg[mc->mc_top];
8069 nkeys = NUMKEYS(mp);
8071 /* Adjust other cursors pointing to mp */
8072 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
8073 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8074 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8076 if (m3->mc_snum < mc->mc_snum)
8078 if (m3->mc_pg[mc->mc_top] == mp) {
8079 /* if m3 points past last node in page, find next sibling */
8080 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8081 rc = mdb_cursor_sibling(m3, 1);
8082 if (rc == MDB_NOTFOUND) {
8083 m3->mc_flags |= C_EOF;
8089 mc->mc_flags |= C_DEL;
8093 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8098 mdb_del(MDB_txn *txn, MDB_dbi dbi,
8099 MDB_val *key, MDB_val *data)
8101 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8104 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8105 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8107 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
8108 /* must ignore any data */
8112 return mdb_del0(txn, dbi, key, data, 0);
8116 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
8117 MDB_val *key, MDB_val *data, unsigned flags)
8122 MDB_val rdata, *xdata;
8126 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
8128 mdb_cursor_init(&mc, txn, dbi, &mx);
8137 flags |= MDB_NODUPDATA;
8139 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
8141 /* let mdb_page_split know about this cursor if needed:
8142 * delete will trigger a rebalance; if it needs to move
8143 * a node from one page to another, it will have to
8144 * update the parent's separator key(s). If the new sepkey
8145 * is larger than the current one, the parent page may
8146 * run out of space, triggering a split. We need this
8147 * cursor to be consistent until the end of the rebalance.
8149 mc.mc_flags |= C_UNTRACK;
8150 mc.mc_next = txn->mt_cursors[dbi];
8151 txn->mt_cursors[dbi] = &mc;
8152 rc = mdb_cursor_del(&mc, flags);
8153 txn->mt_cursors[dbi] = mc.mc_next;
8158 /** Split a page and insert a new node.
8159 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
8160 * The cursor will be updated to point to the actual page and index where
8161 * the node got inserted after the split.
8162 * @param[in] newkey The key for the newly inserted node.
8163 * @param[in] newdata The data for the newly inserted node.
8164 * @param[in] newpgno The page number, if the new node is a branch node.
8165 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
8166 * @return 0 on success, non-zero on failure.
8169 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
8170 unsigned int nflags)
8173 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
8176 int i, j, split_indx, nkeys, pmax;
8177 MDB_env *env = mc->mc_txn->mt_env;
8179 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
8180 MDB_page *copy = NULL;
8181 MDB_page *mp, *rp, *pp;
8186 mp = mc->mc_pg[mc->mc_top];
8187 newindx = mc->mc_ki[mc->mc_top];
8188 nkeys = NUMKEYS(mp);
8190 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
8191 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
8192 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
8194 /* Create a right sibling. */
8195 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
8197 rp->mp_pad = mp->mp_pad;
8198 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
8200 if (mc->mc_snum < 2) {
8201 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
8203 /* shift current top to make room for new parent */
8204 mc->mc_pg[1] = mc->mc_pg[0];
8205 mc->mc_ki[1] = mc->mc_ki[0];
8208 mc->mc_db->md_root = pp->mp_pgno;
8209 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
8210 new_root = mc->mc_db->md_depth++;
8212 /* Add left (implicit) pointer. */
8213 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
8214 /* undo the pre-push */
8215 mc->mc_pg[0] = mc->mc_pg[1];
8216 mc->mc_ki[0] = mc->mc_ki[1];
8217 mc->mc_db->md_root = mp->mp_pgno;
8218 mc->mc_db->md_depth--;
8225 ptop = mc->mc_top-1;
8226 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
8229 mc->mc_flags |= C_SPLITTING;
8230 mdb_cursor_copy(mc, &mn);
8231 mn.mc_pg[mn.mc_top] = rp;
8232 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
8234 if (nflags & MDB_APPEND) {
8235 mn.mc_ki[mn.mc_top] = 0;
8237 split_indx = newindx;
8241 split_indx = (nkeys+1) / 2;
8246 unsigned int lsize, rsize, ksize;
8247 /* Move half of the keys to the right sibling */
8248 x = mc->mc_ki[mc->mc_top] - split_indx;
8249 ksize = mc->mc_db->md_pad;
8250 split = LEAF2KEY(mp, split_indx, ksize);
8251 rsize = (nkeys - split_indx) * ksize;
8252 lsize = (nkeys - split_indx) * sizeof(indx_t);
8253 mp->mp_lower -= lsize;
8254 rp->mp_lower += lsize;
8255 mp->mp_upper += rsize - lsize;
8256 rp->mp_upper -= rsize - lsize;
8257 sepkey.mv_size = ksize;
8258 if (newindx == split_indx) {
8259 sepkey.mv_data = newkey->mv_data;
8261 sepkey.mv_data = split;
8264 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
8265 memcpy(rp->mp_ptrs, split, rsize);
8266 sepkey.mv_data = rp->mp_ptrs;
8267 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
8268 memcpy(ins, newkey->mv_data, ksize);
8269 mp->mp_lower += sizeof(indx_t);
8270 mp->mp_upper -= ksize - sizeof(indx_t);
8273 memcpy(rp->mp_ptrs, split, x * ksize);
8274 ins = LEAF2KEY(rp, x, ksize);
8275 memcpy(ins, newkey->mv_data, ksize);
8276 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
8277 rp->mp_lower += sizeof(indx_t);
8278 rp->mp_upper -= ksize - sizeof(indx_t);
8279 mc->mc_ki[mc->mc_top] = x;
8280 mc->mc_pg[mc->mc_top] = rp;
8283 int psize, nsize, k;
8284 /* Maximum free space in an empty page */
8285 pmax = env->me_psize - PAGEHDRSZ;
8287 nsize = mdb_leaf_size(env, newkey, newdata);
8289 nsize = mdb_branch_size(env, newkey);
8290 nsize = EVEN(nsize);
8292 /* grab a page to hold a temporary copy */
8293 copy = mdb_page_malloc(mc->mc_txn, 1);
8298 copy->mp_pgno = mp->mp_pgno;
8299 copy->mp_flags = mp->mp_flags;
8300 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
8301 copy->mp_upper = env->me_psize - PAGEBASE;
8303 /* prepare to insert */
8304 for (i=0, j=0; i<nkeys; i++) {
8306 copy->mp_ptrs[j++] = 0;
8308 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
8311 /* When items are relatively large the split point needs
8312 * to be checked, because being off-by-one will make the
8313 * difference between success or failure in mdb_node_add.
8315 * It's also relevant if a page happens to be laid out
8316 * such that one half of its nodes are all "small" and
8317 * the other half of its nodes are "large." If the new
8318 * item is also "large" and falls on the half with
8319 * "large" nodes, it also may not fit.
8321 * As a final tweak, if the new item goes on the last
8322 * spot on the page (and thus, onto the new page), bias
8323 * the split so the new page is emptier than the old page.
8324 * This yields better packing during sequential inserts.
8326 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
8327 /* Find split point */
8329 if (newindx <= split_indx || newindx >= nkeys) {
8331 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
8336 for (; i!=k; i+=j) {
8341 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8342 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
8344 if (F_ISSET(node->mn_flags, F_BIGDATA))
8345 psize += sizeof(pgno_t);
8347 psize += NODEDSZ(node);
8349 psize = EVEN(psize);
8351 if (psize > pmax || i == k-j) {
8352 split_indx = i + (j<0);
8357 if (split_indx == newindx) {
8358 sepkey.mv_size = newkey->mv_size;
8359 sepkey.mv_data = newkey->mv_data;
8361 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
8362 sepkey.mv_size = node->mn_ksize;
8363 sepkey.mv_data = NODEKEY(node);
8368 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
8370 /* Copy separator key to the parent.
8372 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
8376 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
8381 if (mn.mc_snum == mc->mc_snum) {
8382 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
8383 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
8384 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
8385 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
8390 /* Right page might now have changed parent.
8391 * Check if left page also changed parent.
8393 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8394 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8395 for (i=0; i<ptop; i++) {
8396 mc->mc_pg[i] = mn.mc_pg[i];
8397 mc->mc_ki[i] = mn.mc_ki[i];
8399 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8400 if (mn.mc_ki[ptop]) {
8401 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8403 /* find right page's left sibling */
8404 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8405 mdb_cursor_sibling(mc, 0);
8410 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8413 mc->mc_flags ^= C_SPLITTING;
8414 if (rc != MDB_SUCCESS) {
8417 if (nflags & MDB_APPEND) {
8418 mc->mc_pg[mc->mc_top] = rp;
8419 mc->mc_ki[mc->mc_top] = 0;
8420 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8423 for (i=0; i<mc->mc_top; i++)
8424 mc->mc_ki[i] = mn.mc_ki[i];
8425 } else if (!IS_LEAF2(mp)) {
8427 mc->mc_pg[mc->mc_top] = rp;
8432 rkey.mv_data = newkey->mv_data;
8433 rkey.mv_size = newkey->mv_size;
8439 /* Update index for the new key. */
8440 mc->mc_ki[mc->mc_top] = j;
8442 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8443 rkey.mv_data = NODEKEY(node);
8444 rkey.mv_size = node->mn_ksize;
8446 xdata.mv_data = NODEDATA(node);
8447 xdata.mv_size = NODEDSZ(node);
8450 pgno = NODEPGNO(node);
8451 flags = node->mn_flags;
8454 if (!IS_LEAF(mp) && j == 0) {
8455 /* First branch index doesn't need key data. */
8459 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8465 mc->mc_pg[mc->mc_top] = copy;
8470 } while (i != split_indx);
8472 nkeys = NUMKEYS(copy);
8473 for (i=0; i<nkeys; i++)
8474 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8475 mp->mp_lower = copy->mp_lower;
8476 mp->mp_upper = copy->mp_upper;
8477 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8478 env->me_psize - copy->mp_upper - PAGEBASE);
8480 /* reset back to original page */
8481 if (newindx < split_indx) {
8482 mc->mc_pg[mc->mc_top] = mp;
8483 if (nflags & MDB_RESERVE) {
8484 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
8485 if (!(node->mn_flags & F_BIGDATA))
8486 newdata->mv_data = NODEDATA(node);
8489 mc->mc_pg[mc->mc_top] = rp;
8491 /* Make sure mc_ki is still valid.
8493 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8494 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8495 for (i=0; i<=ptop; i++) {
8496 mc->mc_pg[i] = mn.mc_pg[i];
8497 mc->mc_ki[i] = mn.mc_ki[i];
8504 /* Adjust other cursors pointing to mp */
8505 MDB_cursor *m2, *m3;
8506 MDB_dbi dbi = mc->mc_dbi;
8507 int fixup = NUMKEYS(mp);
8509 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8510 if (mc->mc_flags & C_SUB)
8511 m3 = &m2->mc_xcursor->mx_cursor;
8516 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8518 if (m3->mc_flags & C_SPLITTING)
8523 for (k=new_root; k>=0; k--) {
8524 m3->mc_ki[k+1] = m3->mc_ki[k];
8525 m3->mc_pg[k+1] = m3->mc_pg[k];
8527 if (m3->mc_ki[0] >= split_indx) {
8532 m3->mc_pg[0] = mc->mc_pg[0];
8536 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8537 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8538 m3->mc_ki[mc->mc_top]++;
8539 if (m3->mc_ki[mc->mc_top] >= fixup) {
8540 m3->mc_pg[mc->mc_top] = rp;
8541 m3->mc_ki[mc->mc_top] -= fixup;
8542 m3->mc_ki[ptop] = mn.mc_ki[ptop];
8544 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8545 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8550 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8553 if (copy) /* tmp page */
8554 mdb_page_free(env, copy);
8556 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8561 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8562 MDB_val *key, MDB_val *data, unsigned int flags)
8567 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8570 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
8573 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8574 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8576 mdb_cursor_init(&mc, txn, dbi, &mx);
8577 return mdb_cursor_put(&mc, key, data, flags);
8581 #define MDB_WBUF (1024*1024)
8584 /** State needed for a compacting copy. */
8585 typedef struct mdb_copy {
8586 pthread_mutex_t mc_mutex;
8587 pthread_cond_t mc_cond;
8594 pgno_t mc_next_pgno;
8597 volatile int mc_new;
8602 /** Dedicated writer thread for compacting copy. */
8603 static THREAD_RET ESECT CALL_CONV
8604 mdb_env_copythr(void *arg)
8608 int toggle = 0, wsize, rc;
8611 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8614 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8617 pthread_mutex_lock(&my->mc_mutex);
8619 pthread_cond_signal(&my->mc_cond);
8622 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8623 if (my->mc_new < 0) {
8628 wsize = my->mc_wlen[toggle];
8629 ptr = my->mc_wbuf[toggle];
8632 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8636 } else if (len > 0) {
8650 /* If there's an overflow page tail, write it too */
8651 if (my->mc_olen[toggle]) {
8652 wsize = my->mc_olen[toggle];
8653 ptr = my->mc_over[toggle];
8654 my->mc_olen[toggle] = 0;
8657 my->mc_wlen[toggle] = 0;
8659 pthread_cond_signal(&my->mc_cond);
8661 pthread_cond_signal(&my->mc_cond);
8662 pthread_mutex_unlock(&my->mc_mutex);
8663 return (THREAD_RET)0;
8667 /** Tell the writer thread there's a buffer ready to write */
8669 mdb_env_cthr_toggle(mdb_copy *my, int st)
8671 int toggle = my->mc_toggle ^ 1;
8672 pthread_mutex_lock(&my->mc_mutex);
8673 if (my->mc_status) {
8674 pthread_mutex_unlock(&my->mc_mutex);
8675 return my->mc_status;
8677 while (my->mc_new == 1)
8678 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8680 my->mc_toggle = toggle;
8681 pthread_cond_signal(&my->mc_cond);
8682 pthread_mutex_unlock(&my->mc_mutex);
8686 /** Depth-first tree traversal for compacting copy. */
8688 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8691 MDB_txn *txn = my->mc_txn;
8693 MDB_page *mo, *mp, *leaf;
8698 /* Empty DB, nothing to do */
8699 if (*pg == P_INVALID)
8706 rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
8709 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8713 /* Make cursor pages writable */
8714 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8718 for (i=0; i<mc.mc_top; i++) {
8719 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8720 mc.mc_pg[i] = (MDB_page *)ptr;
8721 ptr += my->mc_env->me_psize;
8724 /* This is writable space for a leaf page. Usually not needed. */
8725 leaf = (MDB_page *)ptr;
8727 toggle = my->mc_toggle;
8728 while (mc.mc_snum > 0) {
8730 mp = mc.mc_pg[mc.mc_top];
8734 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8735 for (i=0; i<n; i++) {
8736 ni = NODEPTR(mp, i);
8737 if (ni->mn_flags & F_BIGDATA) {
8741 /* Need writable leaf */
8743 mc.mc_pg[mc.mc_top] = leaf;
8744 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8746 ni = NODEPTR(mp, i);
8749 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8750 rc = mdb_page_get(txn, pg, &omp, NULL);
8753 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8754 rc = mdb_env_cthr_toggle(my, 1);
8757 toggle = my->mc_toggle;
8759 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8760 memcpy(mo, omp, my->mc_env->me_psize);
8761 mo->mp_pgno = my->mc_next_pgno;
8762 my->mc_next_pgno += omp->mp_pages;
8763 my->mc_wlen[toggle] += my->mc_env->me_psize;
8764 if (omp->mp_pages > 1) {
8765 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
8766 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
8767 rc = mdb_env_cthr_toggle(my, 1);
8770 toggle = my->mc_toggle;
8772 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
8773 } else if (ni->mn_flags & F_SUBDATA) {
8776 /* Need writable leaf */
8778 mc.mc_pg[mc.mc_top] = leaf;
8779 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8781 ni = NODEPTR(mp, i);
8784 memcpy(&db, NODEDATA(ni), sizeof(db));
8785 my->mc_toggle = toggle;
8786 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
8789 toggle = my->mc_toggle;
8790 memcpy(NODEDATA(ni), &db, sizeof(db));
8795 mc.mc_ki[mc.mc_top]++;
8796 if (mc.mc_ki[mc.mc_top] < n) {
8799 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
8801 rc = mdb_page_get(txn, pg, &mp, NULL);
8806 mc.mc_ki[mc.mc_top] = 0;
8807 if (IS_BRANCH(mp)) {
8808 /* Whenever we advance to a sibling branch page,
8809 * we must proceed all the way down to its first leaf.
8811 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
8814 mc.mc_pg[mc.mc_top] = mp;
8818 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8819 rc = mdb_env_cthr_toggle(my, 1);
8822 toggle = my->mc_toggle;
8824 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8825 mdb_page_copy(mo, mp, my->mc_env->me_psize);
8826 mo->mp_pgno = my->mc_next_pgno++;
8827 my->mc_wlen[toggle] += my->mc_env->me_psize;
8829 /* Update parent if there is one */
8830 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
8831 SETPGNO(ni, mo->mp_pgno);
8832 mdb_cursor_pop(&mc);
8834 /* Otherwise we're done */
8844 /** Copy environment with compaction. */
8846 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
8851 MDB_txn *txn = NULL;
8856 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
8857 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
8858 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
8859 if (my.mc_wbuf[0] == NULL)
8862 pthread_mutex_init(&my.mc_mutex, NULL);
8863 pthread_cond_init(&my.mc_cond, NULL);
8864 #ifdef HAVE_MEMALIGN
8865 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
8866 if (my.mc_wbuf[0] == NULL)
8869 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_os_psize, MDB_WBUF*2);
8874 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
8875 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
8880 my.mc_next_pgno = NUM_METAS;
8886 THREAD_CREATE(thr, mdb_env_copythr, &my);
8888 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8892 mp = (MDB_page *)my.mc_wbuf[0];
8893 memset(mp, 0, NUM_METAS * env->me_psize);
8895 mp->mp_flags = P_META;
8896 mm = (MDB_meta *)METADATA(mp);
8897 mdb_env_init_meta0(env, mm);
8898 mm->mm_address = env->me_metas[0]->mm_address;
8900 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
8902 mp->mp_flags = P_META;
8903 *(MDB_meta *)METADATA(mp) = *mm;
8904 mm = (MDB_meta *)METADATA(mp);
8906 /* Count the number of free pages, subtract from lastpg to find
8907 * number of active pages
8910 MDB_ID freecount = 0;
8913 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
8914 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
8915 freecount += *(MDB_ID *)data.mv_data;
8916 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
8917 txn->mt_dbs[FREE_DBI].md_leaf_pages +
8918 txn->mt_dbs[FREE_DBI].md_overflow_pages;
8920 /* Set metapage 1 */
8921 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
8922 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
8923 if (mm->mm_last_pg > NUM_METAS-1) {
8924 mm->mm_dbs[MAIN_DBI].md_root = mm->mm_last_pg;
8927 mm->mm_dbs[MAIN_DBI].md_root = P_INVALID;
8930 my.mc_wlen[0] = env->me_psize * NUM_METAS;
8932 pthread_mutex_lock(&my.mc_mutex);
8934 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8935 pthread_mutex_unlock(&my.mc_mutex);
8936 rc = mdb_env_cwalk(&my, &txn->mt_dbs[MAIN_DBI].md_root, 0);
8937 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
8938 rc = mdb_env_cthr_toggle(&my, 1);
8939 mdb_env_cthr_toggle(&my, -1);
8940 pthread_mutex_lock(&my.mc_mutex);
8942 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8943 pthread_mutex_unlock(&my.mc_mutex);
8948 CloseHandle(my.mc_cond);
8949 CloseHandle(my.mc_mutex);
8950 _aligned_free(my.mc_wbuf[0]);
8952 pthread_cond_destroy(&my.mc_cond);
8953 pthread_mutex_destroy(&my.mc_mutex);
8954 free(my.mc_wbuf[0]);
8959 /** Copy environment as-is. */
8961 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
8963 MDB_txn *txn = NULL;
8964 mdb_mutexref_t wmutex = NULL;
8970 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8974 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8977 /* Do the lock/unlock of the reader mutex before starting the
8978 * write txn. Otherwise other read txns could block writers.
8980 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8985 /* We must start the actual read txn after blocking writers */
8986 mdb_txn_end(txn, MDB_END_RESET_TMP);
8988 /* Temporarily block writers until we snapshot the meta pages */
8989 wmutex = env->me_wmutex;
8990 if (LOCK_MUTEX(rc, env, wmutex))
8993 rc = mdb_txn_renew0(txn);
8995 UNLOCK_MUTEX(wmutex);
9000 wsize = env->me_psize * NUM_METAS;
9004 DO_WRITE(rc, fd, ptr, w2, len);
9008 } else if (len > 0) {
9014 /* Non-blocking or async handles are not supported */
9020 UNLOCK_MUTEX(wmutex);
9025 w2 = txn->mt_next_pgno * env->me_psize;
9028 if ((rc = mdb_fsize(env->me_fd, &fsize)))
9035 if (wsize > MAX_WRITE)
9039 DO_WRITE(rc, fd, ptr, w2, len);
9043 } else if (len > 0) {
9060 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
9062 if (flags & MDB_CP_COMPACT)
9063 return mdb_env_copyfd1(env, fd);
9065 return mdb_env_copyfd0(env, fd);
9069 mdb_env_copyfd(MDB_env *env, HANDLE fd)
9071 return mdb_env_copyfd2(env, fd, 0);
9075 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
9079 HANDLE newfd = INVALID_HANDLE_VALUE;
9081 if (env->me_flags & MDB_NOSUBDIR) {
9082 lpath = (char *)path;
9085 len += sizeof(DATANAME);
9086 lpath = malloc(len);
9089 sprintf(lpath, "%s" DATANAME, path);
9092 /* The destination path must exist, but the destination file must not.
9093 * We don't want the OS to cache the writes, since the source data is
9094 * already in the OS cache.
9097 newfd = CreateFileA(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
9098 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
9100 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
9102 if (newfd == INVALID_HANDLE_VALUE) {
9107 if (env->me_psize >= env->me_os_psize) {
9109 /* Set O_DIRECT if the file system supports it */
9110 if ((rc = fcntl(newfd, F_GETFL)) != -1)
9111 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
9113 #ifdef F_NOCACHE /* __APPLE__ */
9114 rc = fcntl(newfd, F_NOCACHE, 1);
9122 rc = mdb_env_copyfd2(env, newfd, flags);
9125 if (!(env->me_flags & MDB_NOSUBDIR))
9127 if (newfd != INVALID_HANDLE_VALUE)
9128 if (close(newfd) < 0 && rc == MDB_SUCCESS)
9135 mdb_env_copy(MDB_env *env, const char *path)
9137 return mdb_env_copy2(env, path, 0);
9141 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
9143 if (flag & ~CHANGEABLE)
9146 env->me_flags |= flag;
9148 env->me_flags &= ~flag;
9153 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
9158 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
9163 mdb_env_set_userctx(MDB_env *env, void *ctx)
9167 env->me_userctx = ctx;
9172 mdb_env_get_userctx(MDB_env *env)
9174 return env ? env->me_userctx : NULL;
9178 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
9183 env->me_assert_func = func;
9189 mdb_env_get_path(MDB_env *env, const char **arg)
9194 *arg = env->me_path;
9199 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
9208 /** Common code for #mdb_stat() and #mdb_env_stat().
9209 * @param[in] env the environment to operate in.
9210 * @param[in] db the #MDB_db record containing the stats to return.
9211 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
9212 * @return 0, this function always succeeds.
9215 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
9217 arg->ms_psize = env->me_psize;
9218 arg->ms_depth = db->md_depth;
9219 arg->ms_branch_pages = db->md_branch_pages;
9220 arg->ms_leaf_pages = db->md_leaf_pages;
9221 arg->ms_overflow_pages = db->md_overflow_pages;
9222 arg->ms_entries = db->md_entries;
9228 mdb_env_stat(MDB_env *env, MDB_stat *arg)
9232 if (env == NULL || arg == NULL)
9235 meta = mdb_env_pick_meta(env);
9237 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
9241 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
9245 if (env == NULL || arg == NULL)
9248 meta = mdb_env_pick_meta(env);
9249 arg->me_mapaddr = meta->mm_address;
9250 arg->me_last_pgno = meta->mm_last_pg;
9251 arg->me_last_txnid = meta->mm_txnid;
9253 arg->me_mapsize = env->me_mapsize;
9254 arg->me_maxreaders = env->me_maxreaders;
9255 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
9259 /** Set the default comparison functions for a database.
9260 * Called immediately after a database is opened to set the defaults.
9261 * The user can then override them with #mdb_set_compare() or
9262 * #mdb_set_dupsort().
9263 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
9264 * @param[in] dbi A database handle returned by #mdb_dbi_open()
9267 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
9269 uint16_t f = txn->mt_dbs[dbi].md_flags;
9271 txn->mt_dbxs[dbi].md_cmp =
9272 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
9273 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
9275 txn->mt_dbxs[dbi].md_dcmp =
9276 !(f & MDB_DUPSORT) ? 0 :
9277 ((f & MDB_INTEGERDUP)
9278 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
9279 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
9282 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
9288 int rc, dbflag, exact;
9289 unsigned int unused = 0, seq;
9292 if (flags & ~VALID_FLAGS)
9294 if (txn->mt_flags & MDB_TXN_BLOCKED)
9300 if (flags & PERSISTENT_FLAGS) {
9301 uint16_t f2 = flags & PERSISTENT_FLAGS;
9302 /* make sure flag changes get committed */
9303 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
9304 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
9305 txn->mt_flags |= MDB_TXN_DIRTY;
9308 mdb_default_cmp(txn, MAIN_DBI);
9312 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
9313 mdb_default_cmp(txn, MAIN_DBI);
9316 /* Is the DB already open? */
9318 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
9319 if (!txn->mt_dbxs[i].md_name.mv_size) {
9320 /* Remember this free slot */
9321 if (!unused) unused = i;
9324 if (len == txn->mt_dbxs[i].md_name.mv_size &&
9325 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
9331 /* If no free slot and max hit, fail */
9332 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
9333 return MDB_DBS_FULL;
9335 /* Cannot mix named databases with some mainDB flags */
9336 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
9337 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
9339 /* Find the DB info */
9340 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
9343 key.mv_data = (void *)name;
9344 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
9345 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
9346 if (rc == MDB_SUCCESS) {
9347 /* make sure this is actually a DB */
9348 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
9349 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
9350 return MDB_INCOMPATIBLE;
9351 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
9352 /* Create if requested */
9353 data.mv_size = sizeof(MDB_db);
9354 data.mv_data = &dummy;
9355 memset(&dummy, 0, sizeof(dummy));
9356 dummy.md_root = P_INVALID;
9357 dummy.md_flags = flags & PERSISTENT_FLAGS;
9358 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
9362 /* OK, got info, add to table */
9363 if (rc == MDB_SUCCESS) {
9364 unsigned int slot = unused ? unused : txn->mt_numdbs;
9365 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
9366 txn->mt_dbxs[slot].md_name.mv_size = len;
9367 txn->mt_dbxs[slot].md_rel = NULL;
9368 txn->mt_dbflags[slot] = dbflag;
9369 /* txn-> and env-> are the same in read txns, use
9370 * tmp variable to avoid undefined assignment
9372 seq = ++txn->mt_env->me_dbiseqs[slot];
9373 txn->mt_dbiseqs[slot] = seq;
9375 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
9377 mdb_default_cmp(txn, slot);
9387 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9389 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
9392 if (txn->mt_flags & MDB_TXN_BLOCKED)
9395 if (txn->mt_dbflags[dbi] & DB_STALE) {
9398 /* Stale, must read the DB's root. cursor_init does it for us. */
9399 mdb_cursor_init(&mc, txn, dbi, &mx);
9401 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9404 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9407 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
9409 ptr = env->me_dbxs[dbi].md_name.mv_data;
9410 /* If there was no name, this was already closed */
9412 env->me_dbxs[dbi].md_name.mv_data = NULL;
9413 env->me_dbxs[dbi].md_name.mv_size = 0;
9414 env->me_dbflags[dbi] = 0;
9415 env->me_dbiseqs[dbi]++;
9420 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9422 /* We could return the flags for the FREE_DBI too but what's the point? */
9423 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9425 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9429 /** Add all the DB's pages to the free list.
9430 * @param[in] mc Cursor on the DB to free.
9431 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9432 * @return 0 on success, non-zero on failure.
9435 mdb_drop0(MDB_cursor *mc, int subs)
9439 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9440 if (rc == MDB_SUCCESS) {
9441 MDB_txn *txn = mc->mc_txn;
9446 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
9447 * This also avoids any P_LEAF2 pages, which have no nodes.
9449 if (mc->mc_flags & C_SUB)
9452 mdb_cursor_copy(mc, &mx);
9453 while (mc->mc_snum > 0) {
9454 MDB_page *mp = mc->mc_pg[mc->mc_top];
9455 unsigned n = NUMKEYS(mp);
9457 for (i=0; i<n; i++) {
9458 ni = NODEPTR(mp, i);
9459 if (ni->mn_flags & F_BIGDATA) {
9462 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9463 rc = mdb_page_get(txn, pg, &omp, NULL);
9466 mdb_cassert(mc, IS_OVERFLOW(omp));
9467 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9471 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9472 mdb_xcursor_init1(mc, ni);
9473 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9479 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9481 for (i=0; i<n; i++) {
9483 ni = NODEPTR(mp, i);
9486 mdb_midl_xappend(txn->mt_free_pgs, pg);
9491 mc->mc_ki[mc->mc_top] = i;
9492 rc = mdb_cursor_sibling(mc, 1);
9494 if (rc != MDB_NOTFOUND)
9496 /* no more siblings, go back to beginning
9497 * of previous level.
9501 for (i=1; i<mc->mc_snum; i++) {
9503 mc->mc_pg[i] = mx.mc_pg[i];
9508 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9511 txn->mt_flags |= MDB_TXN_ERROR;
9512 } else if (rc == MDB_NOTFOUND) {
9518 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9520 MDB_cursor *mc, *m2;
9523 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9526 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9529 if (TXN_DBI_CHANGED(txn, dbi))
9532 rc = mdb_cursor_open(txn, dbi, &mc);
9536 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9537 /* Invalidate the dropped DB's cursors */
9538 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9539 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9543 /* Can't delete the main DB */
9544 if (del && dbi >= CORE_DBS) {
9545 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
9547 txn->mt_dbflags[dbi] = DB_STALE;
9548 mdb_dbi_close(txn->mt_env, dbi);
9550 txn->mt_flags |= MDB_TXN_ERROR;
9553 /* reset the DB record, mark it dirty */
9554 txn->mt_dbflags[dbi] |= DB_DIRTY;
9555 txn->mt_dbs[dbi].md_depth = 0;
9556 txn->mt_dbs[dbi].md_branch_pages = 0;
9557 txn->mt_dbs[dbi].md_leaf_pages = 0;
9558 txn->mt_dbs[dbi].md_overflow_pages = 0;
9559 txn->mt_dbs[dbi].md_entries = 0;
9560 txn->mt_dbs[dbi].md_root = P_INVALID;
9562 txn->mt_flags |= MDB_TXN_DIRTY;
9565 mdb_cursor_close(mc);
9569 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9571 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9574 txn->mt_dbxs[dbi].md_cmp = cmp;
9578 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9580 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9583 txn->mt_dbxs[dbi].md_dcmp = cmp;
9587 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9589 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9592 txn->mt_dbxs[dbi].md_rel = rel;
9596 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9598 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9601 txn->mt_dbxs[dbi].md_relctx = ctx;
9606 mdb_env_get_maxkeysize(MDB_env *env)
9608 return ENV_MAXKEY(env);
9612 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9614 unsigned int i, rdrs;
9617 int rc = 0, first = 1;
9621 if (!env->me_txns) {
9622 return func("(no reader locks)\n", ctx);
9624 rdrs = env->me_txns->mti_numreaders;
9625 mr = env->me_txns->mti_readers;
9626 for (i=0; i<rdrs; i++) {
9628 txnid_t txnid = mr[i].mr_txnid;
9629 sprintf(buf, txnid == (txnid_t)-1 ?
9630 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9631 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9634 rc = func(" pid thread txnid\n", ctx);
9638 rc = func(buf, ctx);
9644 rc = func("(no active readers)\n", ctx);
9649 /** Insert pid into list if not already present.
9650 * return -1 if already present.
9653 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9655 /* binary search of pid in list */
9657 unsigned cursor = 1;
9659 unsigned n = ids[0];
9662 unsigned pivot = n >> 1;
9663 cursor = base + pivot + 1;
9664 val = pid - ids[cursor];
9669 } else if ( val > 0 ) {
9674 /* found, so it's a duplicate */
9683 for (n = ids[0]; n > cursor; n--)
9690 mdb_reader_check(MDB_env *env, int *dead)
9696 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
9699 /** As #mdb_reader_check(). rlocked = <caller locked the reader mutex>. */
9701 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
9703 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
9704 unsigned int i, j, rdrs;
9706 MDB_PID_T *pids, pid;
9707 int rc = MDB_SUCCESS, count = 0;
9709 rdrs = env->me_txns->mti_numreaders;
9710 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
9714 mr = env->me_txns->mti_readers;
9715 for (i=0; i<rdrs; i++) {
9717 if (pid && pid != env->me_pid) {
9718 if (mdb_pid_insert(pids, pid) == 0) {
9719 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9720 /* Stale reader found */
9723 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
9724 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
9726 rdrs = 0; /* the above checked all readers */
9728 /* Recheck, a new process may have reused pid */
9729 if (mdb_reader_pid(env, Pidcheck, pid))
9734 if (mr[j].mr_pid == pid) {
9735 DPRINTF(("clear stale reader pid %u txn %"Z"d",
9736 (unsigned) pid, mr[j].mr_txnid));
9741 UNLOCK_MUTEX(rmutex);
9752 #ifdef MDB_ROBUST_SUPPORTED
9753 /** Handle #LOCK_MUTEX0() failure.
9754 * Try to repair the lock file if the mutex owner died.
9755 * @param[in] env the environment handle
9756 * @param[in] mutex LOCK_MUTEX0() mutex
9757 * @param[in] rc LOCK_MUTEX0() error (nonzero)
9758 * @return 0 on success with the mutex locked, or an error code on failure.
9761 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
9766 if (rc == MDB_OWNERDEAD) {
9767 /* We own the mutex. Clean up after dead previous owner. */
9769 rlocked = (mutex == env->me_rmutex);
9771 /* Keep mti_txnid updated, otherwise next writer can
9772 * overwrite data which latest meta page refers to.
9774 meta = mdb_env_pick_meta(env);
9775 env->me_txns->mti_txnid = meta->mm_txnid;
9776 /* env is hosed if the dead thread was ours */
9778 env->me_flags |= MDB_FATAL_ERROR;
9783 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
9784 (rc ? "this process' env is hosed" : "recovering")));
9785 rc2 = mdb_reader_check0(env, rlocked, NULL);
9787 rc2 = mdb_mutex_consistent(mutex);
9788 if (rc || (rc = rc2)) {
9789 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
9790 UNLOCK_MUTEX(mutex);
9796 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
9801 #endif /* MDB_ROBUST_SUPPORTED */