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-2014 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)
93 #if defined(__sun) || defined(ANDROID)
94 /* Most platforms have posix_memalign, older may only have memalign */
95 #define HAVE_MEMALIGN 1
99 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
100 #include <netinet/in.h>
101 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
104 #if defined(__APPLE__) || defined (BSD)
105 # define MDB_USE_SYSV_SEM 1
106 # define MDB_FDATASYNC fsync
107 #elif defined(ANDROID)
108 # define MDB_FDATASYNC fsync
113 #ifdef MDB_USE_SYSV_SEM
116 #ifdef _SEM_SEMUN_UNDEFINED
119 struct semid_ds *buf;
120 unsigned short *array;
122 #endif /* _SEM_SEMUN_UNDEFINED */
123 #endif /* MDB_USE_SYSV_SEM */
127 #include <valgrind/memcheck.h>
128 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
129 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
130 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
131 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
132 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
134 #define VGMEMP_CREATE(h,r,z)
135 #define VGMEMP_ALLOC(h,a,s)
136 #define VGMEMP_FREE(h,a)
137 #define VGMEMP_DESTROY(h)
138 #define VGMEMP_DEFINED(a,s)
142 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
143 /* Solaris just defines one or the other */
144 # define LITTLE_ENDIAN 1234
145 # define BIG_ENDIAN 4321
146 # ifdef _LITTLE_ENDIAN
147 # define BYTE_ORDER LITTLE_ENDIAN
149 # define BYTE_ORDER BIG_ENDIAN
152 # define BYTE_ORDER __BYTE_ORDER
156 #ifndef LITTLE_ENDIAN
157 #define LITTLE_ENDIAN __LITTLE_ENDIAN
160 #define BIG_ENDIAN __BIG_ENDIAN
163 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
164 #define MISALIGNED_OK 1
170 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
171 # error "Unknown or unsupported endianness (BYTE_ORDER)"
172 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
173 # error "Two's complement, reasonably sized integer types, please"
177 /** Put infrequently used env functions in separate section */
179 # define ESECT __attribute__ ((section("__TEXT,text_env")))
181 # define ESECT __attribute__ ((section("text_env")))
187 /** @defgroup internal LMDB Internals
190 /** @defgroup compat Compatibility Macros
191 * A bunch of macros to minimize the amount of platform-specific ifdefs
192 * needed throughout the rest of the code. When the features this library
193 * needs are similar enough to POSIX to be hidden in a one-or-two line
194 * replacement, this macro approach is used.
198 /** Features under development */
203 #if defined(_WIN32) || (defined(EOWNERDEAD) && !defined(MDB_USE_SYSV_SEM))
204 #define MDB_ROBUST_SUPPORTED 1
207 /** Wrapper around __func__, which is a C99 feature */
208 #if __STDC_VERSION__ >= 199901L
209 # define mdb_func_ __func__
210 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
211 # define mdb_func_ __FUNCTION__
213 /* If a debug message says <mdb_unknown>(), update the #if statements above */
214 # define mdb_func_ "<mdb_unknown>"
218 #define MDB_USE_HASH 1
219 #define MDB_PIDLOCK 0
220 #define THREAD_RET DWORD
221 #define pthread_t HANDLE
222 #define pthread_mutex_t HANDLE
223 #define pthread_cond_t HANDLE
224 typedef HANDLE mdb_mutex_t;
225 #define pthread_key_t DWORD
226 #define pthread_self() GetCurrentThreadId()
227 #define pthread_key_create(x,y) \
228 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
229 #define pthread_key_delete(x) TlsFree(x)
230 #define pthread_getspecific(x) TlsGetValue(x)
231 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
232 #define pthread_mutex_consistent(mutex) 0
233 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
234 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
235 #define pthread_cond_signal(x) SetEvent(*x)
236 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
237 #define THREAD_CREATE(thr,start,arg) thr=CreateThread(NULL,0,start,arg,0,NULL)
238 #define THREAD_FINISH(thr) WaitForSingleObject(thr, INFINITE)
239 #define MDB_MUTEX(env, rw) ((env)->me_##rw##mutex)
240 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
241 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
242 #define getpid() GetCurrentProcessId()
243 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
244 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
245 #define ErrCode() GetLastError()
246 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
247 #define close(fd) (CloseHandle(fd) ? 0 : -1)
248 #define munmap(ptr,len) UnmapViewOfFile(ptr)
249 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
250 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
252 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
256 #define THREAD_RET void *
257 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
258 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
259 #define Z "z" /**< printf format modifier for size_t */
261 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
262 #define MDB_PIDLOCK 1
264 #ifdef MDB_USE_SYSV_SEM
266 typedef struct mdb_mutex {
271 #define MDB_MUTEX(env, rw) (&(env)->me_##rw##mutex)
272 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
273 #define UNLOCK_MUTEX(mutex) do { \
274 struct sembuf sb = { 0, 1, SEM_UNDO }; \
275 sb.sem_num = (mutex)->semnum; \
276 semop((mutex)->semid, &sb, 1); \
280 mdb_sem_wait(mdb_mutex_t *sem)
283 struct sembuf sb = { 0, -1, SEM_UNDO };
284 sb.sem_num = sem->semnum;
285 while ((rc = semop(sem->semid, &sb, 1)) && (rc = errno) == EINTR) ;
290 /** Pointer/HANDLE type of shared mutex/semaphore.
292 typedef pthread_mutex_t mdb_mutex_t;
293 /** Mutex for the reader table (rw = r) or write transaction (rw = w).
295 #define MDB_MUTEX(env, rw) (&(env)->me_txns->mti_##rw##mutex)
296 /** Lock the reader or writer mutex.
297 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
299 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
300 /** Unlock the reader or writer mutex.
302 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
303 #endif /* MDB_USE_SYSV_SEM */
305 /** Get the error code for the last failed system function.
307 #define ErrCode() errno
309 /** An abstraction for a file handle.
310 * On POSIX systems file handles are small integers. On Windows
311 * they're opaque pointers.
315 /** A value for an invalid file handle.
316 * Mainly used to initialize file variables and signify that they are
319 #define INVALID_HANDLE_VALUE (-1)
321 /** Get the size of a memory page for the system.
322 * This is the basic size that the platform's memory manager uses, and is
323 * fundamental to the use of memory-mapped files.
325 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
330 #elif defined(MDB_USE_SYSV_SEM)
333 #define MNAME_LEN (sizeof(pthread_mutex_t))
338 #ifdef MDB_ROBUST_SUPPORTED
339 /** Lock mutex, handle any error, set rc = result.
340 * Return 0 on success, nonzero (not rc) on error.
342 #define LOCK_MUTEX(rc, env, mutex) \
343 (((rc) = LOCK_MUTEX0(mutex)) && \
344 ((rc) = mdb_mutex_failed(env, mutex, rc)))
345 static int mdb_mutex_failed(MDB_env *env, mdb_mutex_t *mutex, int rc);
347 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
348 #define mdb_mutex_failed(env, mutex, rc) (rc)
352 /** A flag for opening a file and requesting synchronous data writes.
353 * This is only used when writing a meta page. It's not strictly needed;
354 * we could just do a normal write and then immediately perform a flush.
355 * But if this flag is available it saves us an extra system call.
357 * @note If O_DSYNC is undefined but exists in /usr/include,
358 * preferably set some compiler flag to get the definition.
359 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
362 # define MDB_DSYNC O_DSYNC
366 /** Function for flushing the data of a file. Define this to fsync
367 * if fdatasync() is not supported.
369 #ifndef MDB_FDATASYNC
370 # define MDB_FDATASYNC fdatasync
374 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
385 /** A page number in the database.
386 * Note that 64 bit page numbers are overkill, since pages themselves
387 * already represent 12-13 bits of addressable memory, and the OS will
388 * always limit applications to a maximum of 63 bits of address space.
390 * @note In the #MDB_node structure, we only store 48 bits of this value,
391 * which thus limits us to only 60 bits of addressable data.
393 typedef MDB_ID pgno_t;
395 /** A transaction ID.
396 * See struct MDB_txn.mt_txnid for details.
398 typedef MDB_ID txnid_t;
400 /** @defgroup debug Debug Macros
404 /** Enable debug output. Needs variable argument macros (a C99 feature).
405 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
406 * read from and written to the database (used for free space management).
412 static int mdb_debug;
413 static txnid_t mdb_debug_start;
415 /** Print a debug message with printf formatting.
416 * Requires double parenthesis around 2 or more args.
418 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
419 # define DPRINTF0(fmt, ...) \
420 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
422 # define DPRINTF(args) ((void) 0)
424 /** Print a debug string.
425 * The string is printed literally, with no format processing.
427 #define DPUTS(arg) DPRINTF(("%s", arg))
428 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
430 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
433 /** @brief The maximum size of a database page.
435 * It is 32k or 64k, since value-PAGEBASE must fit in
436 * #MDB_page.%mp_upper.
438 * LMDB will use database pages < OS pages if needed.
439 * That causes more I/O in write transactions: The OS must
440 * know (read) the whole page before writing a partial page.
442 * Note that we don't currently support Huge pages. On Linux,
443 * regular data files cannot use Huge pages, and in general
444 * Huge pages aren't actually pageable. We rely on the OS
445 * demand-pager to read our data and page it out when memory
446 * pressure from other processes is high. So until OSs have
447 * actual paging support for Huge pages, they're not viable.
449 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
451 /** The minimum number of keys required in a database page.
452 * Setting this to a larger value will place a smaller bound on the
453 * maximum size of a data item. Data items larger than this size will
454 * be pushed into overflow pages instead of being stored directly in
455 * the B-tree node. This value used to default to 4. With a page size
456 * of 4096 bytes that meant that any item larger than 1024 bytes would
457 * go into an overflow page. That also meant that on average 2-3KB of
458 * each overflow page was wasted space. The value cannot be lower than
459 * 2 because then there would no longer be a tree structure. With this
460 * value, items larger than 2KB will go into overflow pages, and on
461 * average only 1KB will be wasted.
463 #define MDB_MINKEYS 2
465 /** A stamp that identifies a file as an LMDB file.
466 * There's nothing special about this value other than that it is easily
467 * recognizable, and it will reflect any byte order mismatches.
469 #define MDB_MAGIC 0xBEEFC0DE
471 /** The version number for a database's datafile format. */
472 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
473 /** The version number for a database's lockfile format. */
474 #define MDB_LOCK_VERSION ((MDB_DEVEL) ? 999 : 1)
476 /** @brief The max size of a key we can write, or 0 for dynamic max.
478 * Define this as 0 to compute the max from the page size. 511
479 * is default for backwards compat: liblmdb <= 0.9.10 can break
480 * when modifying a DB with keys/dupsort data bigger than its max.
481 * #MDB_DEVEL sets the default to 0.
483 * Data items in an #MDB_DUPSORT database are also limited to
484 * this size, since they're actually keys of a sub-DB. Keys and
485 * #MDB_DUPSORT data items must fit on a node in a regular page.
487 #ifndef MDB_MAXKEYSIZE
488 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
491 /** The maximum size of a key we can write to the environment. */
493 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
495 #define ENV_MAXKEY(env) ((env)->me_maxkey)
498 /** @brief The maximum size of a data item.
500 * We only store a 32 bit value for node sizes.
502 #define MAXDATASIZE 0xffffffffUL
505 /** Key size which fits in a #DKBUF.
508 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
511 * This is used for printing a hex dump of a key's contents.
513 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
514 /** Display a key in hex.
516 * Invoke a function to display a key in hex.
518 #define DKEY(x) mdb_dkey(x, kbuf)
524 /** An invalid page number.
525 * Mainly used to denote an empty tree.
527 #define P_INVALID (~(pgno_t)0)
529 /** Test if the flags \b f are set in a flag word \b w. */
530 #define F_ISSET(w, f) (((w) & (f)) == (f))
532 /** Round \b n up to an even number. */
533 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
535 /** Used for offsets within a single page.
536 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
539 typedef uint16_t indx_t;
541 /** Default size of memory map.
542 * This is certainly too small for any actual applications. Apps should always set
543 * the size explicitly using #mdb_env_set_mapsize().
545 #define DEFAULT_MAPSIZE 1048576
547 /** @defgroup readers Reader Lock Table
548 * Readers don't acquire any locks for their data access. Instead, they
549 * simply record their transaction ID in the reader table. The reader
550 * mutex is needed just to find an empty slot in the reader table. The
551 * slot's address is saved in thread-specific data so that subsequent read
552 * transactions started by the same thread need no further locking to proceed.
554 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
556 * No reader table is used if the database is on a read-only filesystem, or
557 * if #MDB_NOLOCK is set.
559 * Since the database uses multi-version concurrency control, readers don't
560 * actually need any locking. This table is used to keep track of which
561 * readers are using data from which old transactions, so that we'll know
562 * when a particular old transaction is no longer in use. Old transactions
563 * that have discarded any data pages can then have those pages reclaimed
564 * for use by a later write transaction.
566 * The lock table is constructed such that reader slots are aligned with the
567 * processor's cache line size. Any slot is only ever used by one thread.
568 * This alignment guarantees that there will be no contention or cache
569 * thrashing as threads update their own slot info, and also eliminates
570 * any need for locking when accessing a slot.
572 * A writer thread will scan every slot in the table to determine the oldest
573 * outstanding reader transaction. Any freed pages older than this will be
574 * reclaimed by the writer. The writer doesn't use any locks when scanning
575 * this table. This means that there's no guarantee that the writer will
576 * see the most up-to-date reader info, but that's not required for correct
577 * operation - all we need is to know the upper bound on the oldest reader,
578 * we don't care at all about the newest reader. So the only consequence of
579 * reading stale information here is that old pages might hang around a
580 * while longer before being reclaimed. That's actually good anyway, because
581 * the longer we delay reclaiming old pages, the more likely it is that a
582 * string of contiguous pages can be found after coalescing old pages from
583 * many old transactions together.
586 /** Number of slots in the reader table.
587 * This value was chosen somewhat arbitrarily. 126 readers plus a
588 * couple mutexes fit exactly into 8KB on my development machine.
589 * Applications should set the table size using #mdb_env_set_maxreaders().
591 #define DEFAULT_READERS 126
593 /** The size of a CPU cache line in bytes. We want our lock structures
594 * aligned to this size to avoid false cache line sharing in the
596 * This value works for most CPUs. For Itanium this should be 128.
602 /** The information we store in a single slot of the reader table.
603 * In addition to a transaction ID, we also record the process and
604 * thread ID that owns a slot, so that we can detect stale information,
605 * e.g. threads or processes that went away without cleaning up.
606 * @note We currently don't check for stale records. We simply re-init
607 * the table when we know that we're the only process opening the
610 typedef struct MDB_rxbody {
611 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
612 * Multiple readers that start at the same time will probably have the
613 * same ID here. Again, it's not important to exclude them from
614 * anything; all we need to know is which version of the DB they
615 * started from so we can avoid overwriting any data used in that
616 * particular version.
618 volatile txnid_t mrb_txnid;
619 /** The process ID of the process owning this reader txn. */
620 volatile MDB_PID_T mrb_pid;
621 /** The thread ID of the thread owning this txn. */
622 volatile MDB_THR_T mrb_tid;
625 /** The actual reader record, with cacheline padding. */
626 typedef struct MDB_reader {
629 /** shorthand for mrb_txnid */
630 #define mr_txnid mru.mrx.mrb_txnid
631 #define mr_pid mru.mrx.mrb_pid
632 #define mr_tid mru.mrx.mrb_tid
633 /** cache line alignment */
634 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
638 /** The header for the reader table.
639 * The table resides in a memory-mapped file. (This is a different file
640 * than is used for the main database.)
642 * For POSIX the actual mutexes reside in the shared memory of this
643 * mapped file. On Windows, mutexes are named objects allocated by the
644 * kernel; we store the mutex names in this mapped file so that other
645 * processes can grab them. This same approach is also used on
646 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
647 * process-shared POSIX mutexes. For these cases where a named object
648 * is used, the object name is derived from a 64 bit FNV hash of the
649 * environment pathname. As such, naming collisions are extremely
650 * unlikely. If a collision occurs, the results are unpredictable.
652 typedef struct MDB_txbody {
653 /** Stamp identifying this as an LMDB file. It must be set
656 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
659 char mtb_rmname[MNAME_LEN];
660 #elif defined(MDB_USE_SYSV_SEM)
663 /** Mutex protecting access to this table.
664 * This is the #MDB_MUTEX(env,r) reader table lock.
666 pthread_mutex_t mtb_rmutex;
668 /** The ID of the last transaction committed to the database.
669 * This is recorded here only for convenience; the value can always
670 * be determined by reading the main database meta pages.
672 volatile txnid_t mtb_txnid;
673 /** The number of slots that have been used in the reader table.
674 * This always records the maximum count, it is not decremented
675 * when readers release their slots.
677 volatile unsigned mtb_numreaders;
680 /** The actual reader table definition. */
681 typedef struct MDB_txninfo {
684 #define mti_magic mt1.mtb.mtb_magic
685 #define mti_format mt1.mtb.mtb_format
686 #define mti_rmutex mt1.mtb.mtb_rmutex
687 #define mti_rmname mt1.mtb.mtb_rmname
688 #define mti_txnid mt1.mtb.mtb_txnid
689 #define mti_numreaders mt1.mtb.mtb_numreaders
690 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
692 #ifdef MDB_USE_SYSV_SEM
693 #define mti_semid mt1.mtb.mtb_semid
697 char mt2_wmname[MNAME_LEN];
698 #define mti_wmname mt2.mt2_wmname
700 pthread_mutex_t mt2_wmutex;
701 #define mti_wmutex mt2.mt2_wmutex
703 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
706 MDB_reader mti_readers[1];
709 /** Lockfile format signature: version, features and field layout */
710 #define MDB_LOCK_FORMAT \
712 ((MDB_LOCK_VERSION) \
713 /* Flags which describe functionality */ \
714 + (((MNAME_LEN) == 0) << 18) /* MDB_USE_SYSV_SEM */ \
715 + (((MDB_PIDLOCK) != 0) << 16)))
718 /** Common header for all page types.
719 * Overflow records occupy a number of contiguous pages with no
720 * headers on any page after the first.
722 typedef struct MDB_page {
723 #define mp_pgno mp_p.p_pgno
724 #define mp_next mp_p.p_next
726 pgno_t p_pgno; /**< page number */
727 struct MDB_page *p_next; /**< for in-memory list of freed pages */
730 /** @defgroup mdb_page Page Flags
732 * Flags for the page headers.
735 #define P_BRANCH 0x01 /**< branch page */
736 #define P_LEAF 0x02 /**< leaf page */
737 #define P_OVERFLOW 0x04 /**< overflow page */
738 #define P_META 0x08 /**< meta page */
739 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
740 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
741 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
742 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
743 #define P_KEEP 0x8000 /**< leave this page alone during spill */
745 uint16_t mp_flags; /**< @ref mdb_page */
746 #define mp_lower mp_pb.pb.pb_lower
747 #define mp_upper mp_pb.pb.pb_upper
748 #define mp_pages mp_pb.pb_pages
751 indx_t pb_lower; /**< lower bound of free space */
752 indx_t pb_upper; /**< upper bound of free space */
754 uint32_t pb_pages; /**< number of overflow pages */
756 indx_t mp_ptrs[1]; /**< dynamic size */
759 /** Size of the page header, excluding dynamic data at the end */
760 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
762 /** Address of first usable data byte in a page, after the header */
763 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
765 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
766 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
768 /** Number of nodes on a page */
769 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
771 /** The amount of space remaining in the page */
772 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
774 /** The percentage of space used in the page, in tenths of a percent. */
775 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
776 ((env)->me_psize - PAGEHDRSZ))
777 /** The minimum page fill factor, in tenths of a percent.
778 * Pages emptier than this are candidates for merging.
780 #define FILL_THRESHOLD 250
782 /** Test if a page is a leaf page */
783 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
784 /** Test if a page is a LEAF2 page */
785 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
786 /** Test if a page is a branch page */
787 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
788 /** Test if a page is an overflow page */
789 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
790 /** Test if a page is a sub page */
791 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
793 /** The number of overflow pages needed to store the given size. */
794 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
796 /** Link in #MDB_txn.%mt_loose_pgs list */
797 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
799 /** Header for a single key/data pair within a page.
800 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
801 * We guarantee 2-byte alignment for 'MDB_node's.
803 typedef struct MDB_node {
804 /** lo and hi are used for data size on leaf nodes and for
805 * child pgno on branch nodes. On 64 bit platforms, flags
806 * is also used for pgno. (Branch nodes have no flags).
807 * They are in host byte order in case that lets some
808 * accesses be optimized into a 32-bit word access.
810 #if BYTE_ORDER == LITTLE_ENDIAN
811 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
813 unsigned short mn_hi, mn_lo;
815 /** @defgroup mdb_node Node Flags
817 * Flags for node headers.
820 #define F_BIGDATA 0x01 /**< data put on overflow page */
821 #define F_SUBDATA 0x02 /**< data is a sub-database */
822 #define F_DUPDATA 0x04 /**< data has duplicates */
824 /** valid flags for #mdb_node_add() */
825 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
828 unsigned short mn_flags; /**< @ref mdb_node */
829 unsigned short mn_ksize; /**< key size */
830 char mn_data[1]; /**< key and data are appended here */
833 /** Size of the node header, excluding dynamic data at the end */
834 #define NODESIZE offsetof(MDB_node, mn_data)
836 /** Bit position of top word in page number, for shifting mn_flags */
837 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
839 /** Size of a node in a branch page with a given key.
840 * This is just the node header plus the key, there is no data.
842 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
844 /** Size of a node in a leaf page with a given key and data.
845 * This is node header plus key plus data size.
847 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
849 /** Address of node \b i in page \b p */
850 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
852 /** Address of the key for the node */
853 #define NODEKEY(node) (void *)((node)->mn_data)
855 /** Address of the data for a node */
856 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
858 /** Get the page number pointed to by a branch node */
859 #define NODEPGNO(node) \
860 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
861 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
862 /** Set the page number in a branch node */
863 #define SETPGNO(node,pgno) do { \
864 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
865 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
867 /** Get the size of the data in a leaf node */
868 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
869 /** Set the size of the data for a leaf node */
870 #define SETDSZ(node,size) do { \
871 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
872 /** The size of a key in a node */
873 #define NODEKSZ(node) ((node)->mn_ksize)
875 /** Copy a page number from src to dst */
877 #define COPY_PGNO(dst,src) dst = src
879 #if SIZE_MAX > 4294967295UL
880 #define COPY_PGNO(dst,src) do { \
881 unsigned short *s, *d; \
882 s = (unsigned short *)&(src); \
883 d = (unsigned short *)&(dst); \
890 #define COPY_PGNO(dst,src) do { \
891 unsigned short *s, *d; \
892 s = (unsigned short *)&(src); \
893 d = (unsigned short *)&(dst); \
899 /** The address of a key in a LEAF2 page.
900 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
901 * There are no node headers, keys are stored contiguously.
903 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
905 /** Set the \b node's key into \b keyptr, if requested. */
906 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
907 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
909 /** Set the \b node's key into \b key. */
910 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
912 /** Information about a single database in the environment. */
913 typedef struct MDB_db {
914 uint32_t md_pad; /**< also ksize for LEAF2 pages */
915 uint16_t md_flags; /**< @ref mdb_dbi_open */
916 uint16_t md_depth; /**< depth of this tree */
917 pgno_t md_branch_pages; /**< number of internal pages */
918 pgno_t md_leaf_pages; /**< number of leaf pages */
919 pgno_t md_overflow_pages; /**< number of overflow pages */
920 size_t md_entries; /**< number of data items */
921 pgno_t md_root; /**< the root page of this tree */
924 /** mdb_dbi_open flags */
925 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
926 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
927 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
928 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
930 /** Handle for the DB used to track free pages. */
932 /** Handle for the default DB. */
935 /** Meta page content.
936 * A meta page is the start point for accessing a database snapshot.
937 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
939 typedef struct MDB_meta {
940 /** Stamp identifying this as an LMDB file. It must be set
943 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
945 void *mm_address; /**< address for fixed mapping */
946 size_t mm_mapsize; /**< size of mmap region */
947 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
948 /** The size of pages used in this DB */
949 #define mm_psize mm_dbs[0].md_pad
950 /** Any persistent environment flags. @ref mdb_env */
951 #define mm_flags mm_dbs[0].md_flags
952 pgno_t mm_last_pg; /**< last used page in file */
953 volatile txnid_t mm_txnid; /**< txnid that committed this page */
956 /** Buffer for a stack-allocated meta page.
957 * The members define size and alignment, and silence type
958 * aliasing warnings. They are not used directly; that could
959 * mean incorrectly using several union members in parallel.
961 typedef union MDB_metabuf {
964 char mm_pad[PAGEHDRSZ];
969 /** Auxiliary DB info.
970 * The information here is mostly static/read-only. There is
971 * only a single copy of this record in the environment.
973 typedef struct MDB_dbx {
974 MDB_val md_name; /**< name of the database */
975 MDB_cmp_func *md_cmp; /**< function for comparing keys */
976 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
977 MDB_rel_func *md_rel; /**< user relocate function */
978 void *md_relctx; /**< user-provided context for md_rel */
981 /** A database transaction.
982 * Every operation requires a transaction handle.
985 MDB_txn *mt_parent; /**< parent of a nested txn */
986 MDB_txn *mt_child; /**< nested txn under this txn */
987 pgno_t mt_next_pgno; /**< next unallocated page */
988 /** The ID of this transaction. IDs are integers incrementing from 1.
989 * Only committed write transactions increment the ID. If a transaction
990 * aborts, the ID may be re-used by the next writer.
993 MDB_env *mt_env; /**< the DB environment */
994 /** The list of pages that became unused during this transaction.
997 /** The list of loose pages that became unused and may be reused
998 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1000 MDB_page *mt_loose_pgs;
1001 /* #Number of loose pages (#mt_loose_pgs) */
1003 /** The sorted list of dirty pages we temporarily wrote to disk
1004 * because the dirty list was full. page numbers in here are
1005 * shifted left by 1, deleted slots have the LSB set.
1007 MDB_IDL mt_spill_pgs;
1009 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1010 MDB_ID2L dirty_list;
1011 /** For read txns: This thread/txn's reader table slot, or NULL. */
1014 /** Array of records for each DB known in the environment. */
1016 /** Array of MDB_db records for each known DB */
1018 /** Array of sequence numbers for each DB handle */
1019 unsigned int *mt_dbiseqs;
1020 /** @defgroup mt_dbflag Transaction DB Flags
1024 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
1025 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1026 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1027 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1029 /** In write txns, array of cursors for each DB */
1030 MDB_cursor **mt_cursors;
1031 /** Array of flags for each DB */
1032 unsigned char *mt_dbflags;
1033 /** Number of DB records in use. This number only ever increments;
1034 * we don't decrement it when individual DB handles are closed.
1038 /** @defgroup mdb_txn Transaction Flags
1042 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
1043 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1044 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1045 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1047 unsigned int mt_flags; /**< @ref mdb_txn */
1048 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1049 * Includes ancestor txns' dirty pages not hidden by other txns'
1050 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1051 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1053 unsigned int mt_dirty_room;
1056 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1057 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1058 * raise this on a 64 bit machine.
1060 #define CURSOR_STACK 32
1064 /** Cursors are used for all DB operations.
1065 * A cursor holds a path of (page pointer, key index) from the DB
1066 * root to a position in the DB, plus other state. #MDB_DUPSORT
1067 * cursors include an xcursor to the current data item. Write txns
1068 * track their cursors and keep them up to date when data moves.
1069 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1070 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1073 /** Next cursor on this DB in this txn */
1074 MDB_cursor *mc_next;
1075 /** Backup of the original cursor if this cursor is a shadow */
1076 MDB_cursor *mc_backup;
1077 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1078 struct MDB_xcursor *mc_xcursor;
1079 /** The transaction that owns this cursor */
1081 /** The database handle this cursor operates on */
1083 /** The database record for this cursor */
1085 /** The database auxiliary record for this cursor */
1087 /** The @ref mt_dbflag for this database */
1088 unsigned char *mc_dbflag;
1089 unsigned short mc_snum; /**< number of pushed pages */
1090 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1091 /** @defgroup mdb_cursor Cursor Flags
1093 * Cursor state flags.
1096 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1097 #define C_EOF 0x02 /**< No more data */
1098 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1099 #define C_DEL 0x08 /**< last op was a cursor_del */
1100 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
1101 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1103 unsigned int mc_flags; /**< @ref mdb_cursor */
1104 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1105 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1108 /** Context for sorted-dup records.
1109 * We could have gone to a fully recursive design, with arbitrarily
1110 * deep nesting of sub-databases. But for now we only handle these
1111 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1113 typedef struct MDB_xcursor {
1114 /** A sub-cursor for traversing the Dup DB */
1115 MDB_cursor mx_cursor;
1116 /** The database record for this Dup DB */
1118 /** The auxiliary DB record for this Dup DB */
1120 /** The @ref mt_dbflag for this Dup DB */
1121 unsigned char mx_dbflag;
1124 /** State of FreeDB old pages, stored in the MDB_env */
1125 typedef struct MDB_pgstate {
1126 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1127 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1130 /** The database environment. */
1132 HANDLE me_fd; /**< The main data file */
1133 HANDLE me_lfd; /**< The lock file */
1134 HANDLE me_mfd; /**< just for writing the meta pages */
1135 /** Failed to update the meta page. Probably an I/O error. */
1136 #define MDB_FATAL_ERROR 0x80000000U
1137 /** Some fields are initialized. */
1138 #define MDB_ENV_ACTIVE 0x20000000U
1139 /** me_txkey is set */
1140 #define MDB_ENV_TXKEY 0x10000000U
1141 uint32_t me_flags; /**< @ref mdb_env */
1142 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1143 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1144 unsigned int me_maxreaders; /**< size of the reader table */
1145 unsigned int me_numreaders; /**< max numreaders set by this env */
1146 MDB_dbi me_numdbs; /**< number of DBs opened */
1147 MDB_dbi me_maxdbs; /**< size of the DB table */
1148 MDB_PID_T me_pid; /**< process ID of this env */
1149 char *me_path; /**< path to the DB files */
1150 char *me_map; /**< the memory map of the data file */
1151 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1152 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
1153 void *me_pbuf; /**< scratch area for DUPSORT put() */
1154 MDB_txn *me_txn; /**< current write transaction */
1155 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1156 size_t me_mapsize; /**< size of the data memory map */
1157 off_t me_size; /**< current file size */
1158 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1159 MDB_dbx *me_dbxs; /**< array of static DB info */
1160 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1161 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1162 pthread_key_t me_txkey; /**< thread-key for readers */
1163 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1164 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1165 # define me_pglast me_pgstate.mf_pglast
1166 # define me_pghead me_pgstate.mf_pghead
1167 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1168 /** IDL of pages that became unused in a write txn */
1169 MDB_IDL me_free_pgs;
1170 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1171 MDB_ID2L me_dirty_list;
1172 /** Max number of freelist items that can fit in a single overflow page */
1174 /** Max size of a node on a page */
1175 unsigned int me_nodemax;
1176 #if !(MDB_MAXKEYSIZE)
1177 unsigned int me_maxkey; /**< max size of a key */
1179 int me_live_reader; /**< have liveness lock in reader table */
1181 int me_pidquery; /**< Used in OpenProcess */
1183 #if defined(_WIN32) || defined(MDB_USE_SYSV_SEM)
1184 /* Windows mutexes/SysV semaphores do not reside in shared mem */
1185 mdb_mutex_t me_rmutex;
1186 mdb_mutex_t me_wmutex;
1188 void *me_userctx; /**< User-settable context */
1189 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1192 /** Nested transaction */
1193 typedef struct MDB_ntxn {
1194 MDB_txn mnt_txn; /**< the transaction */
1195 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1198 /** max number of pages to commit in one writev() call */
1199 #define MDB_COMMIT_PAGES 64
1200 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1201 #undef MDB_COMMIT_PAGES
1202 #define MDB_COMMIT_PAGES IOV_MAX
1205 /** max bytes to write in one call */
1206 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1208 /** Check \b txn and \b dbi arguments to a function */
1209 #define TXN_DBI_EXIST(txn, dbi) \
1210 ((txn) && (dbi) < (txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & DB_VALID))
1212 /** Check for misused \b dbi handles */
1213 #define TXN_DBI_CHANGED(txn, dbi) \
1214 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1216 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1217 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1218 static int mdb_page_touch(MDB_cursor *mc);
1220 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1221 static int mdb_page_search_root(MDB_cursor *mc,
1222 MDB_val *key, int modify);
1223 #define MDB_PS_MODIFY 1
1224 #define MDB_PS_ROOTONLY 2
1225 #define MDB_PS_FIRST 4
1226 #define MDB_PS_LAST 8
1227 static int mdb_page_search(MDB_cursor *mc,
1228 MDB_val *key, int flags);
1229 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1231 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1232 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1233 pgno_t newpgno, unsigned int nflags);
1235 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1236 static int mdb_env_pick_meta(const MDB_env *env);
1237 static int mdb_env_write_meta(MDB_txn *txn);
1238 #if !(defined(_WIN32) || defined(MDB_USE_SYSV_SEM)) /* Drop unused excl arg */
1239 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1241 static void mdb_env_close0(MDB_env *env, int excl);
1243 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1244 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1245 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1246 static void mdb_node_del(MDB_cursor *mc, int ksize);
1247 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1248 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1249 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1250 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1251 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1253 static int mdb_rebalance(MDB_cursor *mc);
1254 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1256 static void mdb_cursor_pop(MDB_cursor *mc);
1257 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1259 static int mdb_cursor_del0(MDB_cursor *mc);
1260 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1261 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1262 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1263 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1264 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1266 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1267 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1269 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1270 static void mdb_xcursor_init0(MDB_cursor *mc);
1271 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1273 static int mdb_drop0(MDB_cursor *mc, int subs);
1274 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1275 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1278 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1282 static SECURITY_DESCRIPTOR mdb_null_sd;
1283 static SECURITY_ATTRIBUTES mdb_all_sa;
1284 static int mdb_sec_inited;
1287 /** Return the library version info. */
1289 mdb_version(int *major, int *minor, int *patch)
1291 if (major) *major = MDB_VERSION_MAJOR;
1292 if (minor) *minor = MDB_VERSION_MINOR;
1293 if (patch) *patch = MDB_VERSION_PATCH;
1294 return MDB_VERSION_STRING;
1297 /** Table of descriptions for LMDB @ref errors */
1298 static char *const mdb_errstr[] = {
1299 "MDB_KEYEXIST: Key/data pair already exists",
1300 "MDB_NOTFOUND: No matching key/data pair found",
1301 "MDB_PAGE_NOTFOUND: Requested page not found",
1302 "MDB_CORRUPTED: Located page was wrong type",
1303 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1304 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1305 "MDB_INVALID: File is not an LMDB file",
1306 "MDB_MAP_FULL: Environment mapsize limit reached",
1307 "MDB_DBS_FULL: Environment maxdbs limit reached",
1308 "MDB_READERS_FULL: Environment maxreaders limit reached",
1309 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1310 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1311 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1312 "MDB_PAGE_FULL: Internal error - page has no more space",
1313 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1314 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1315 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1316 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1317 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1318 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1322 mdb_strerror(int err)
1325 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1326 * This works as long as no function between the call to mdb_strerror
1327 * and the actual use of the message uses more than 4K of stack.
1330 char buf[1024], *ptr = buf;
1334 return ("Successful return: 0");
1336 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1337 i = err - MDB_KEYEXIST;
1338 return mdb_errstr[i];
1342 /* These are the C-runtime error codes we use. The comment indicates
1343 * their numeric value, and the Win32 error they would correspond to
1344 * if the error actually came from a Win32 API. A major mess, we should
1345 * have used LMDB-specific error codes for everything.
1348 case ENOENT: /* 2, FILE_NOT_FOUND */
1349 case EIO: /* 5, ACCESS_DENIED */
1350 case ENOMEM: /* 12, INVALID_ACCESS */
1351 case EACCES: /* 13, INVALID_DATA */
1352 case EBUSY: /* 16, CURRENT_DIRECTORY */
1353 case EINVAL: /* 22, BAD_COMMAND */
1354 case ENOSPC: /* 28, OUT_OF_PAPER */
1355 return strerror(err);
1360 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1361 FORMAT_MESSAGE_IGNORE_INSERTS,
1362 NULL, err, 0, ptr, sizeof(buf), (va_list *)pad);
1365 return strerror(err);
1369 /** assert(3) variant in cursor context */
1370 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1371 /** assert(3) variant in transaction context */
1372 #define mdb_tassert(mc, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1373 /** assert(3) variant in environment context */
1374 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1377 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1378 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1381 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1382 const char *func, const char *file, int line)
1385 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1386 file, line, expr_txt, func);
1387 if (env->me_assert_func)
1388 env->me_assert_func(env, buf);
1389 fprintf(stderr, "%s\n", buf);
1393 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1397 /** Return the page number of \b mp which may be sub-page, for debug output */
1399 mdb_dbg_pgno(MDB_page *mp)
1402 COPY_PGNO(ret, mp->mp_pgno);
1406 /** Display a key in hexadecimal and return the address of the result.
1407 * @param[in] key the key to display
1408 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1409 * @return The key in hexadecimal form.
1412 mdb_dkey(MDB_val *key, char *buf)
1415 unsigned char *c = key->mv_data;
1421 if (key->mv_size > DKBUF_MAXKEYSIZE)
1422 return "MDB_MAXKEYSIZE";
1423 /* may want to make this a dynamic check: if the key is mostly
1424 * printable characters, print it as-is instead of converting to hex.
1428 for (i=0; i<key->mv_size; i++)
1429 ptr += sprintf(ptr, "%02x", *c++);
1431 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1437 mdb_leafnode_type(MDB_node *n)
1439 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1440 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1441 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1444 /** Display all the keys in the page. */
1446 mdb_page_list(MDB_page *mp)
1448 pgno_t pgno = mdb_dbg_pgno(mp);
1449 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1451 unsigned int i, nkeys, nsize, total = 0;
1455 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1456 case P_BRANCH: type = "Branch page"; break;
1457 case P_LEAF: type = "Leaf page"; break;
1458 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1459 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1460 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1462 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1463 pgno, mp->mp_pages, state);
1466 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1467 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1470 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1474 nkeys = NUMKEYS(mp);
1475 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1477 for (i=0; i<nkeys; i++) {
1478 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1479 key.mv_size = nsize = mp->mp_pad;
1480 key.mv_data = LEAF2KEY(mp, i, nsize);
1482 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1485 node = NODEPTR(mp, i);
1486 key.mv_size = node->mn_ksize;
1487 key.mv_data = node->mn_data;
1488 nsize = NODESIZE + key.mv_size;
1489 if (IS_BRANCH(mp)) {
1490 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1494 if (F_ISSET(node->mn_flags, F_BIGDATA))
1495 nsize += sizeof(pgno_t);
1497 nsize += NODEDSZ(node);
1499 nsize += sizeof(indx_t);
1500 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1501 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1503 total = EVEN(total);
1505 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1506 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1510 mdb_cursor_chk(MDB_cursor *mc)
1516 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1517 for (i=0; i<mc->mc_top; i++) {
1519 node = NODEPTR(mp, mc->mc_ki[i]);
1520 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1523 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1529 /** Count all the pages in each DB and in the freelist
1530 * and make sure it matches the actual number of pages
1532 * All named DBs must be open for a correct count.
1534 static void mdb_audit(MDB_txn *txn)
1538 MDB_ID freecount, count;
1543 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1544 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1545 freecount += *(MDB_ID *)data.mv_data;
1546 mdb_tassert(txn, rc == MDB_NOTFOUND);
1549 for (i = 0; i<txn->mt_numdbs; i++) {
1551 if (!(txn->mt_dbflags[i] & DB_VALID))
1553 mdb_cursor_init(&mc, txn, i, &mx);
1554 if (txn->mt_dbs[i].md_root == P_INVALID)
1556 count += txn->mt_dbs[i].md_branch_pages +
1557 txn->mt_dbs[i].md_leaf_pages +
1558 txn->mt_dbs[i].md_overflow_pages;
1559 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1560 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1561 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1564 mp = mc.mc_pg[mc.mc_top];
1565 for (j=0; j<NUMKEYS(mp); j++) {
1566 MDB_node *leaf = NODEPTR(mp, j);
1567 if (leaf->mn_flags & F_SUBDATA) {
1569 memcpy(&db, NODEDATA(leaf), sizeof(db));
1570 count += db.md_branch_pages + db.md_leaf_pages +
1571 db.md_overflow_pages;
1575 mdb_tassert(txn, rc == MDB_NOTFOUND);
1578 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1579 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1580 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1586 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1588 return txn->mt_dbxs[dbi].md_cmp(a, b);
1592 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1594 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1597 /** Allocate memory for a page.
1598 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1601 mdb_page_malloc(MDB_txn *txn, unsigned num)
1603 MDB_env *env = txn->mt_env;
1604 MDB_page *ret = env->me_dpages;
1605 size_t psize = env->me_psize, sz = psize, off;
1606 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1607 * For a single page alloc, we init everything after the page header.
1608 * For multi-page, we init the final page; if the caller needed that
1609 * many pages they will be filling in at least up to the last page.
1613 VGMEMP_ALLOC(env, ret, sz);
1614 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1615 env->me_dpages = ret->mp_next;
1618 psize -= off = PAGEHDRSZ;
1623 if ((ret = malloc(sz)) != NULL) {
1624 VGMEMP_ALLOC(env, ret, sz);
1625 if (!(env->me_flags & MDB_NOMEMINIT)) {
1626 memset((char *)ret + off, 0, psize);
1630 txn->mt_flags |= MDB_TXN_ERROR;
1634 /** Free a single page.
1635 * Saves single pages to a list, for future reuse.
1636 * (This is not used for multi-page overflow pages.)
1639 mdb_page_free(MDB_env *env, MDB_page *mp)
1641 mp->mp_next = env->me_dpages;
1642 VGMEMP_FREE(env, mp);
1643 env->me_dpages = mp;
1646 /** Free a dirty page */
1648 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1650 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1651 mdb_page_free(env, dp);
1653 /* large pages just get freed directly */
1654 VGMEMP_FREE(env, dp);
1659 /** Return all dirty pages to dpage list */
1661 mdb_dlist_free(MDB_txn *txn)
1663 MDB_env *env = txn->mt_env;
1664 MDB_ID2L dl = txn->mt_u.dirty_list;
1665 unsigned i, n = dl[0].mid;
1667 for (i = 1; i <= n; i++) {
1668 mdb_dpage_free(env, dl[i].mptr);
1673 /** Loosen or free a single page.
1674 * Saves single pages to a list for future reuse
1675 * in this same txn. It has been pulled from the freeDB
1676 * and already resides on the dirty list, but has been
1677 * deleted. Use these pages first before pulling again
1680 * If the page wasn't dirtied in this txn, just add it
1681 * to this txn's free list.
1684 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1687 pgno_t pgno = mp->mp_pgno;
1688 MDB_txn *txn = mc->mc_txn;
1690 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1691 if (txn->mt_parent) {
1692 MDB_ID2 *dl = txn->mt_u.dirty_list;
1693 /* If txn has a parent, make sure the page is in our
1697 unsigned x = mdb_mid2l_search(dl, pgno);
1698 if (x <= dl[0].mid && dl[x].mid == pgno) {
1699 if (mp != dl[x].mptr) { /* bad cursor? */
1700 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1701 txn->mt_flags |= MDB_TXN_ERROR;
1702 return MDB_CORRUPTED;
1709 /* no parent txn, so it's just ours */
1714 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1716 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1717 txn->mt_loose_pgs = mp;
1718 txn->mt_loose_count++;
1719 mp->mp_flags |= P_LOOSE;
1721 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1729 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1730 * @param[in] mc A cursor handle for the current operation.
1731 * @param[in] pflags Flags of the pages to update:
1732 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1733 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1734 * @return 0 on success, non-zero on failure.
1737 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1739 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1740 MDB_txn *txn = mc->mc_txn;
1746 int rc = MDB_SUCCESS, level;
1748 /* Mark pages seen by cursors */
1749 if (mc->mc_flags & C_UNTRACK)
1750 mc = NULL; /* will find mc in mt_cursors */
1751 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1752 for (; mc; mc=mc->mc_next) {
1753 if (!(mc->mc_flags & C_INITIALIZED))
1755 for (m3 = mc;; m3 = &mx->mx_cursor) {
1757 for (j=0; j<m3->mc_snum; j++) {
1759 if ((mp->mp_flags & Mask) == pflags)
1760 mp->mp_flags ^= P_KEEP;
1762 mx = m3->mc_xcursor;
1763 /* Proceed to mx if it is at a sub-database */
1764 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1766 if (! (mp && (mp->mp_flags & P_LEAF)))
1768 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1769 if (!(leaf->mn_flags & F_SUBDATA))
1778 /* Mark dirty root pages */
1779 for (i=0; i<txn->mt_numdbs; i++) {
1780 if (txn->mt_dbflags[i] & DB_DIRTY) {
1781 pgno_t pgno = txn->mt_dbs[i].md_root;
1782 if (pgno == P_INVALID)
1784 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1786 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1787 dp->mp_flags ^= P_KEEP;
1795 static int mdb_page_flush(MDB_txn *txn, int keep);
1797 /** Spill pages from the dirty list back to disk.
1798 * This is intended to prevent running into #MDB_TXN_FULL situations,
1799 * but note that they may still occur in a few cases:
1800 * 1) our estimate of the txn size could be too small. Currently this
1801 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1802 * 2) child txns may run out of space if their parents dirtied a
1803 * lot of pages and never spilled them. TODO: we probably should do
1804 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1805 * the parent's dirty_room is below a given threshold.
1807 * Otherwise, if not using nested txns, it is expected that apps will
1808 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1809 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1810 * If the txn never references them again, they can be left alone.
1811 * If the txn only reads them, they can be used without any fuss.
1812 * If the txn writes them again, they can be dirtied immediately without
1813 * going thru all of the work of #mdb_page_touch(). Such references are
1814 * handled by #mdb_page_unspill().
1816 * Also note, we never spill DB root pages, nor pages of active cursors,
1817 * because we'll need these back again soon anyway. And in nested txns,
1818 * we can't spill a page in a child txn if it was already spilled in a
1819 * parent txn. That would alter the parent txns' data even though
1820 * the child hasn't committed yet, and we'd have no way to undo it if
1821 * the child aborted.
1823 * @param[in] m0 cursor A cursor handle identifying the transaction and
1824 * database for which we are checking space.
1825 * @param[in] key For a put operation, the key being stored.
1826 * @param[in] data For a put operation, the data being stored.
1827 * @return 0 on success, non-zero on failure.
1830 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1832 MDB_txn *txn = m0->mc_txn;
1834 MDB_ID2L dl = txn->mt_u.dirty_list;
1835 unsigned int i, j, need;
1838 if (m0->mc_flags & C_SUB)
1841 /* Estimate how much space this op will take */
1842 i = m0->mc_db->md_depth;
1843 /* Named DBs also dirty the main DB */
1844 if (m0->mc_dbi > MAIN_DBI)
1845 i += txn->mt_dbs[MAIN_DBI].md_depth;
1846 /* For puts, roughly factor in the key+data size */
1848 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1849 i += i; /* double it for good measure */
1852 if (txn->mt_dirty_room > i)
1855 if (!txn->mt_spill_pgs) {
1856 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1857 if (!txn->mt_spill_pgs)
1860 /* purge deleted slots */
1861 MDB_IDL sl = txn->mt_spill_pgs;
1862 unsigned int num = sl[0];
1864 for (i=1; i<=num; i++) {
1871 /* Preserve pages which may soon be dirtied again */
1872 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1875 /* Less aggressive spill - we originally spilled the entire dirty list,
1876 * with a few exceptions for cursor pages and DB root pages. But this
1877 * turns out to be a lot of wasted effort because in a large txn many
1878 * of those pages will need to be used again. So now we spill only 1/8th
1879 * of the dirty pages. Testing revealed this to be a good tradeoff,
1880 * better than 1/2, 1/4, or 1/10.
1882 if (need < MDB_IDL_UM_MAX / 8)
1883 need = MDB_IDL_UM_MAX / 8;
1885 /* Save the page IDs of all the pages we're flushing */
1886 /* flush from the tail forward, this saves a lot of shifting later on. */
1887 for (i=dl[0].mid; i && need; i--) {
1888 MDB_ID pn = dl[i].mid << 1;
1890 if (dp->mp_flags & (P_LOOSE|P_KEEP))
1892 /* Can't spill twice, make sure it's not already in a parent's
1895 if (txn->mt_parent) {
1897 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1898 if (tx2->mt_spill_pgs) {
1899 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1900 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1901 dp->mp_flags |= P_KEEP;
1909 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1913 mdb_midl_sort(txn->mt_spill_pgs);
1915 /* Flush the spilled part of dirty list */
1916 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1919 /* Reset any dirty pages we kept that page_flush didn't see */
1920 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1923 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1927 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1929 mdb_find_oldest(MDB_txn *txn)
1932 txnid_t mr, oldest = txn->mt_txnid - 1;
1933 if (txn->mt_env->me_txns) {
1934 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1935 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1946 /** Add a page to the txn's dirty list */
1948 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1951 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
1953 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1954 insert = mdb_mid2l_append;
1956 insert = mdb_mid2l_insert;
1958 mid.mid = mp->mp_pgno;
1960 rc = insert(txn->mt_u.dirty_list, &mid);
1961 mdb_tassert(txn, rc == 0);
1962 txn->mt_dirty_room--;
1965 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1966 * me_pghead and mt_next_pgno.
1968 * If there are free pages available from older transactions, they
1969 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1970 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1971 * and move me_pglast to say which records were consumed. Only this
1972 * function can create me_pghead and move me_pglast/mt_next_pgno.
1973 * @param[in] mc cursor A cursor handle identifying the transaction and
1974 * database for which we are allocating.
1975 * @param[in] num the number of pages to allocate.
1976 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1977 * will always be satisfied by a single contiguous chunk of memory.
1978 * @return 0 on success, non-zero on failure.
1981 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1983 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1984 /* Get at most <Max_retries> more freeDB records once me_pghead
1985 * has enough pages. If not enough, use new pages from the map.
1986 * If <Paranoid> and mc is updating the freeDB, only get new
1987 * records if me_pghead is empty. Then the freelist cannot play
1988 * catch-up with itself by growing while trying to save it.
1990 enum { Paranoid = 1, Max_retries = 500 };
1992 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1994 int rc, retry = num * 60;
1995 MDB_txn *txn = mc->mc_txn;
1996 MDB_env *env = txn->mt_env;
1997 pgno_t pgno, *mop = env->me_pghead;
1998 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2000 txnid_t oldest = 0, last;
2005 /* If there are any loose pages, just use them */
2006 if (num == 1 && txn->mt_loose_pgs) {
2007 np = txn->mt_loose_pgs;
2008 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2009 txn->mt_loose_count--;
2010 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
2018 /* If our dirty list is already full, we can't do anything */
2019 if (txn->mt_dirty_room == 0) {
2024 for (op = MDB_FIRST;; op = MDB_NEXT) {
2029 /* Seek a big enough contiguous page range. Prefer
2030 * pages at the tail, just truncating the list.
2036 if (mop[i-n2] == pgno+n2)
2043 if (op == MDB_FIRST) { /* 1st iteration */
2044 /* Prepare to fetch more and coalesce */
2045 last = env->me_pglast;
2046 oldest = env->me_pgoldest;
2047 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2050 key.mv_data = &last; /* will look up last+1 */
2051 key.mv_size = sizeof(last);
2053 if (Paranoid && mc->mc_dbi == FREE_DBI)
2056 if (Paranoid && retry < 0 && mop_len)
2060 /* Do not fetch more if the record will be too recent */
2061 if (oldest <= last) {
2063 oldest = mdb_find_oldest(txn);
2064 env->me_pgoldest = oldest;
2070 rc = mdb_cursor_get(&m2, &key, NULL, op);
2072 if (rc == MDB_NOTFOUND)
2076 last = *(txnid_t*)key.mv_data;
2077 if (oldest <= last) {
2079 oldest = mdb_find_oldest(txn);
2080 env->me_pgoldest = oldest;
2086 np = m2.mc_pg[m2.mc_top];
2087 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2088 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
2091 idl = (MDB_ID *) data.mv_data;
2094 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2099 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2101 mop = env->me_pghead;
2103 env->me_pglast = last;
2105 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2106 last, txn->mt_dbs[FREE_DBI].md_root, i));
2108 DPRINTF(("IDL %"Z"u", idl[j]));
2110 /* Merge in descending sorted order */
2111 mdb_midl_xmerge(mop, idl);
2115 /* Use new pages from the map when nothing suitable in the freeDB */
2117 pgno = txn->mt_next_pgno;
2118 if (pgno + num >= env->me_maxpg) {
2119 DPUTS("DB size maxed out");
2125 if (env->me_flags & MDB_WRITEMAP) {
2126 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2128 if (!(np = mdb_page_malloc(txn, num))) {
2134 mop[0] = mop_len -= num;
2135 /* Move any stragglers down */
2136 for (j = i-num; j < mop_len; )
2137 mop[++j] = mop[++i];
2139 txn->mt_next_pgno = pgno + num;
2142 mdb_page_dirty(txn, np);
2148 txn->mt_flags |= MDB_TXN_ERROR;
2152 /** Copy the used portions of a non-overflow page.
2153 * @param[in] dst page to copy into
2154 * @param[in] src page to copy from
2155 * @param[in] psize size of a page
2158 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2160 enum { Align = sizeof(pgno_t) };
2161 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2163 /* If page isn't full, just copy the used portion. Adjust
2164 * alignment so memcpy may copy words instead of bytes.
2166 if ((unused &= -Align) && !IS_LEAF2(src)) {
2167 upper = (upper + PAGEBASE) & -Align;
2168 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2169 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2172 memcpy(dst, src, psize - unused);
2176 /** Pull a page off the txn's spill list, if present.
2177 * If a page being referenced was spilled to disk in this txn, bring
2178 * it back and make it dirty/writable again.
2179 * @param[in] txn the transaction handle.
2180 * @param[in] mp the page being referenced. It must not be dirty.
2181 * @param[out] ret the writable page, if any. ret is unchanged if
2182 * mp wasn't spilled.
2185 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2187 MDB_env *env = txn->mt_env;
2190 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2192 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2193 if (!tx2->mt_spill_pgs)
2195 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2196 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2199 if (txn->mt_dirty_room == 0)
2200 return MDB_TXN_FULL;
2201 if (IS_OVERFLOW(mp))
2205 if (env->me_flags & MDB_WRITEMAP) {
2208 np = mdb_page_malloc(txn, num);
2212 memcpy(np, mp, num * env->me_psize);
2214 mdb_page_copy(np, mp, env->me_psize);
2217 /* If in current txn, this page is no longer spilled.
2218 * If it happens to be the last page, truncate the spill list.
2219 * Otherwise mark it as deleted by setting the LSB.
2221 if (x == txn->mt_spill_pgs[0])
2222 txn->mt_spill_pgs[0]--;
2224 txn->mt_spill_pgs[x] |= 1;
2225 } /* otherwise, if belonging to a parent txn, the
2226 * page remains spilled until child commits
2229 mdb_page_dirty(txn, np);
2230 np->mp_flags |= P_DIRTY;
2238 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2239 * @param[in] mc cursor pointing to the page to be touched
2240 * @return 0 on success, non-zero on failure.
2243 mdb_page_touch(MDB_cursor *mc)
2245 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2246 MDB_txn *txn = mc->mc_txn;
2247 MDB_cursor *m2, *m3;
2251 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2252 if (txn->mt_flags & MDB_TXN_SPILLS) {
2254 rc = mdb_page_unspill(txn, mp, &np);
2260 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2261 (rc = mdb_page_alloc(mc, 1, &np)))
2264 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2265 mp->mp_pgno, pgno));
2266 mdb_cassert(mc, mp->mp_pgno != pgno);
2267 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2268 /* Update the parent page, if any, to point to the new page */
2270 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2271 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2272 SETPGNO(node, pgno);
2274 mc->mc_db->md_root = pgno;
2276 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2277 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2279 /* If txn has a parent, make sure the page is in our
2283 unsigned x = mdb_mid2l_search(dl, pgno);
2284 if (x <= dl[0].mid && dl[x].mid == pgno) {
2285 if (mp != dl[x].mptr) { /* bad cursor? */
2286 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2287 txn->mt_flags |= MDB_TXN_ERROR;
2288 return MDB_CORRUPTED;
2293 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2295 np = mdb_page_malloc(txn, 1);
2300 rc = mdb_mid2l_insert(dl, &mid);
2301 mdb_cassert(mc, rc == 0);
2306 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2308 np->mp_flags |= P_DIRTY;
2311 /* Adjust cursors pointing to mp */
2312 mc->mc_pg[mc->mc_top] = np;
2313 m2 = txn->mt_cursors[mc->mc_dbi];
2314 if (mc->mc_flags & C_SUB) {
2315 for (; m2; m2=m2->mc_next) {
2316 m3 = &m2->mc_xcursor->mx_cursor;
2317 if (m3->mc_snum < mc->mc_snum) continue;
2318 if (m3->mc_pg[mc->mc_top] == mp)
2319 m3->mc_pg[mc->mc_top] = np;
2322 for (; m2; m2=m2->mc_next) {
2323 if (m2->mc_snum < mc->mc_snum) continue;
2324 if (m2->mc_pg[mc->mc_top] == mp) {
2325 m2->mc_pg[mc->mc_top] = np;
2326 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2328 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2330 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2331 if (!(leaf->mn_flags & F_SUBDATA))
2332 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2340 txn->mt_flags |= MDB_TXN_ERROR;
2345 mdb_env_sync(MDB_env *env, int force)
2348 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2349 if (env->me_flags & MDB_WRITEMAP) {
2350 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2351 ? MS_ASYNC : MS_SYNC;
2352 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2355 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2359 if (MDB_FDATASYNC(env->me_fd))
2366 /** Back up parent txn's cursors, then grab the originals for tracking */
2368 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2370 MDB_cursor *mc, *bk;
2375 for (i = src->mt_numdbs; --i >= 0; ) {
2376 if ((mc = src->mt_cursors[i]) != NULL) {
2377 size = sizeof(MDB_cursor);
2379 size += sizeof(MDB_xcursor);
2380 for (; mc; mc = bk->mc_next) {
2386 mc->mc_db = &dst->mt_dbs[i];
2387 /* Kill pointers into src - and dst to reduce abuse: The
2388 * user may not use mc until dst ends. Otherwise we'd...
2390 mc->mc_txn = NULL; /* ...set this to dst */
2391 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2392 if ((mx = mc->mc_xcursor) != NULL) {
2393 *(MDB_xcursor *)(bk+1) = *mx;
2394 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2396 mc->mc_next = dst->mt_cursors[i];
2397 dst->mt_cursors[i] = mc;
2404 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2405 * @param[in] txn the transaction handle.
2406 * @param[in] merge true to keep changes to parent cursors, false to revert.
2407 * @return 0 on success, non-zero on failure.
2410 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2412 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2416 for (i = txn->mt_numdbs; --i >= 0; ) {
2417 for (mc = cursors[i]; mc; mc = next) {
2419 if ((bk = mc->mc_backup) != NULL) {
2421 /* Commit changes to parent txn */
2422 mc->mc_next = bk->mc_next;
2423 mc->mc_backup = bk->mc_backup;
2424 mc->mc_txn = bk->mc_txn;
2425 mc->mc_db = bk->mc_db;
2426 mc->mc_dbflag = bk->mc_dbflag;
2427 if ((mx = mc->mc_xcursor) != NULL)
2428 mx->mx_cursor.mc_txn = bk->mc_txn;
2430 /* Abort nested txn */
2432 if ((mx = mc->mc_xcursor) != NULL)
2433 *mx = *(MDB_xcursor *)(bk+1);
2437 /* Only malloced cursors are permanently tracked. */
2445 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2448 mdb_txn_reset0(MDB_txn *txn, const char *act);
2450 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2456 Pidset = F_SETLK, Pidcheck = F_GETLK
2460 /** Set or check a pid lock. Set returns 0 on success.
2461 * Check returns 0 if the process is certainly dead, nonzero if it may
2462 * be alive (the lock exists or an error happened so we do not know).
2464 * On Windows Pidset is a no-op, we merely check for the existence
2465 * of the process with the given pid. On POSIX we use a single byte
2466 * lock on the lockfile, set at an offset equal to the pid.
2469 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2471 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2474 if (op == Pidcheck) {
2475 h = OpenProcess(env->me_pidquery, FALSE, pid);
2476 /* No documented "no such process" code, but other program use this: */
2478 return ErrCode() != ERROR_INVALID_PARAMETER;
2479 /* A process exists until all handles to it close. Has it exited? */
2480 ret = WaitForSingleObject(h, 0) != 0;
2487 struct flock lock_info;
2488 memset(&lock_info, 0, sizeof(lock_info));
2489 lock_info.l_type = F_WRLCK;
2490 lock_info.l_whence = SEEK_SET;
2491 lock_info.l_start = pid;
2492 lock_info.l_len = 1;
2493 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2494 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2496 } else if ((rc = ErrCode()) == EINTR) {
2504 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2505 * @param[in] txn the transaction handle to initialize
2506 * @return 0 on success, non-zero on failure.
2509 mdb_txn_renew0(MDB_txn *txn)
2511 MDB_env *env = txn->mt_env;
2512 MDB_txninfo *ti = env->me_txns;
2516 int rc, new_notls = 0;
2518 if (txn->mt_flags & MDB_TXN_RDONLY) {
2520 txn->mt_numdbs = env->me_numdbs;
2521 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2523 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2524 txn->mt_txnid = meta->mm_txnid;
2525 txn->mt_u.reader = NULL;
2527 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2528 pthread_getspecific(env->me_txkey);
2530 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2531 return MDB_BAD_RSLOT;
2533 MDB_PID_T pid = env->me_pid;
2534 MDB_THR_T tid = pthread_self();
2535 mdb_mutex_t *rmutex = MDB_MUTEX(env, r);
2537 if (!env->me_live_reader) {
2538 rc = mdb_reader_pid(env, Pidset, pid);
2541 env->me_live_reader = 1;
2544 if (LOCK_MUTEX(rc, env, rmutex))
2546 nr = ti->mti_numreaders;
2547 for (i=0; i<nr; i++)
2548 if (ti->mti_readers[i].mr_pid == 0)
2550 if (i == env->me_maxreaders) {
2551 UNLOCK_MUTEX(rmutex);
2552 return MDB_READERS_FULL;
2554 r = &ti->mti_readers[i];
2555 r->mr_txnid = (txnid_t)-1;
2557 r->mr_pid = pid; /* should be written last, see ITS#7971. */
2559 ti->mti_numreaders = ++nr;
2560 /* Save numreaders for un-mutexed mdb_env_close() */
2561 env->me_numreaders = nr;
2562 UNLOCK_MUTEX(rmutex);
2564 new_notls = (env->me_flags & MDB_NOTLS);
2565 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2570 do /* LY: Retry on a race, ITS#7970. */
2571 r->mr_txnid = ti->mti_txnid;
2572 while(r->mr_txnid != ti->mti_txnid);
2573 txn->mt_txnid = r->mr_txnid;
2574 txn->mt_u.reader = r;
2575 meta = env->me_metas[txn->mt_txnid & 1];
2579 if (LOCK_MUTEX(rc, env, MDB_MUTEX(env, w)))
2581 #ifdef MDB_USE_SYSV_SEM
2582 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2583 txn->mt_txnid = meta->mm_txnid;
2584 /* Update mti_txnid like mdb_mutex_failed() would,
2585 * in case last writer crashed before updating it.
2587 ti->mti_txnid = txn->mt_txnid;
2589 txn->mt_txnid = ti->mti_txnid;
2590 meta = env->me_metas[txn->mt_txnid & 1];
2593 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2594 txn->mt_txnid = meta->mm_txnid;
2597 txn->mt_numdbs = env->me_numdbs;
2600 if (txn->mt_txnid == mdb_debug_start)
2604 txn->mt_child = NULL;
2605 txn->mt_loose_pgs = NULL;
2606 txn->mt_loose_count = 0;
2607 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2608 txn->mt_u.dirty_list = env->me_dirty_list;
2609 txn->mt_u.dirty_list[0].mid = 0;
2610 txn->mt_free_pgs = env->me_free_pgs;
2611 txn->mt_free_pgs[0] = 0;
2612 txn->mt_spill_pgs = NULL;
2614 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2617 /* Copy the DB info and flags */
2618 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2620 /* Moved to here to avoid a data race in read TXNs */
2621 txn->mt_next_pgno = meta->mm_last_pg+1;
2623 for (i=2; i<txn->mt_numdbs; i++) {
2624 x = env->me_dbflags[i];
2625 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2626 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2628 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2630 if (env->me_maxpg < txn->mt_next_pgno) {
2631 mdb_txn_reset0(txn, "renew0-mapfail");
2633 txn->mt_u.reader->mr_pid = 0;
2634 txn->mt_u.reader = NULL;
2636 return MDB_MAP_RESIZED;
2643 mdb_txn_renew(MDB_txn *txn)
2647 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2650 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2651 DPUTS("environment had fatal error, must shutdown!");
2655 rc = mdb_txn_renew0(txn);
2656 if (rc == MDB_SUCCESS) {
2657 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2658 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2659 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2665 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2669 int rc, size, tsize = sizeof(MDB_txn);
2671 if (env->me_flags & MDB_FATAL_ERROR) {
2672 DPUTS("environment had fatal error, must shutdown!");
2675 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2678 /* Nested transactions: Max 1 child, write txns only, no writemap */
2679 if (parent->mt_child ||
2680 (flags & MDB_RDONLY) ||
2681 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2682 (env->me_flags & MDB_WRITEMAP))
2684 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2686 tsize = sizeof(MDB_ntxn);
2689 if (!(flags & MDB_RDONLY)) {
2691 txn = env->me_txn0; /* just reuse preallocated write txn */
2694 /* child txns use own copy of cursors */
2695 size += env->me_maxdbs * sizeof(MDB_cursor *);
2697 size += env->me_maxdbs * (sizeof(MDB_db)+1);
2699 if ((txn = calloc(1, size)) == NULL) {
2700 DPRINTF(("calloc: %s", strerror(errno)));
2703 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2704 if (flags & MDB_RDONLY) {
2705 txn->mt_flags |= MDB_TXN_RDONLY;
2706 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2707 txn->mt_dbiseqs = env->me_dbiseqs;
2709 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2711 txn->mt_dbiseqs = parent->mt_dbiseqs;
2712 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2714 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
2715 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
2723 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2724 if (!txn->mt_u.dirty_list ||
2725 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2727 free(txn->mt_u.dirty_list);
2731 txn->mt_txnid = parent->mt_txnid;
2732 txn->mt_dirty_room = parent->mt_dirty_room;
2733 txn->mt_u.dirty_list[0].mid = 0;
2734 txn->mt_spill_pgs = NULL;
2735 txn->mt_next_pgno = parent->mt_next_pgno;
2736 parent->mt_child = txn;
2737 txn->mt_parent = parent;
2738 txn->mt_numdbs = parent->mt_numdbs;
2739 txn->mt_flags = parent->mt_flags;
2740 txn->mt_dbxs = parent->mt_dbxs;
2741 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2742 /* Copy parent's mt_dbflags, but clear DB_NEW */
2743 for (i=0; i<txn->mt_numdbs; i++)
2744 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2746 ntxn = (MDB_ntxn *)txn;
2747 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2748 if (env->me_pghead) {
2749 size = MDB_IDL_SIZEOF(env->me_pghead);
2750 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2752 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2757 rc = mdb_cursor_shadow(parent, txn);
2759 mdb_txn_reset0(txn, "beginchild-fail");
2761 rc = mdb_txn_renew0(txn);
2764 if (txn != env->me_txn0)
2768 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2769 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2770 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2777 mdb_txn_env(MDB_txn *txn)
2779 if(!txn) return NULL;
2784 mdb_txn_id(MDB_txn *txn)
2787 return txn->mt_txnid;
2790 /** Export or close DBI handles opened in this txn. */
2792 mdb_dbis_update(MDB_txn *txn, int keep)
2795 MDB_dbi n = txn->mt_numdbs;
2796 MDB_env *env = txn->mt_env;
2797 unsigned char *tdbflags = txn->mt_dbflags;
2799 for (i = n; --i >= 2;) {
2800 if (tdbflags[i] & DB_NEW) {
2802 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2804 char *ptr = env->me_dbxs[i].md_name.mv_data;
2806 env->me_dbxs[i].md_name.mv_data = NULL;
2807 env->me_dbxs[i].md_name.mv_size = 0;
2808 env->me_dbflags[i] = 0;
2809 env->me_dbiseqs[i]++;
2815 if (keep && env->me_numdbs < n)
2819 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2820 * May be called twice for readonly txns: First reset it, then abort.
2821 * @param[in] txn the transaction handle to reset
2822 * @param[in] act why the transaction is being reset
2825 mdb_txn_reset0(MDB_txn *txn, const char *act)
2827 MDB_env *env = txn->mt_env;
2829 /* Close any DBI handles opened in this txn */
2830 mdb_dbis_update(txn, 0);
2832 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2833 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2834 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2836 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2837 if (txn->mt_u.reader) {
2838 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2839 if (!(env->me_flags & MDB_NOTLS))
2840 txn->mt_u.reader = NULL; /* txn does not own reader */
2842 txn->mt_numdbs = 0; /* close nothing if called again */
2843 txn->mt_dbxs = NULL; /* mark txn as reset */
2845 pgno_t *pghead = env->me_pghead;
2847 mdb_cursors_close(txn, 0);
2848 if (!(env->me_flags & MDB_WRITEMAP)) {
2849 mdb_dlist_free(txn);
2852 if (!txn->mt_parent) {
2853 if (mdb_midl_shrink(&txn->mt_free_pgs))
2854 env->me_free_pgs = txn->mt_free_pgs;
2856 env->me_pghead = NULL;
2860 /* The writer mutex was locked in mdb_txn_begin. */
2862 UNLOCK_MUTEX(MDB_MUTEX(env, w));
2864 txn->mt_parent->mt_child = NULL;
2865 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2866 mdb_midl_free(txn->mt_free_pgs);
2867 mdb_midl_free(txn->mt_spill_pgs);
2868 free(txn->mt_u.dirty_list);
2871 mdb_midl_free(pghead);
2876 mdb_txn_reset(MDB_txn *txn)
2881 /* This call is only valid for read-only txns */
2882 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2885 mdb_txn_reset0(txn, "reset");
2889 mdb_txn_abort(MDB_txn *txn)
2895 mdb_txn_abort(txn->mt_child);
2897 mdb_txn_reset0(txn, "abort");
2898 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2899 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2900 txn->mt_u.reader->mr_pid = 0;
2902 if (txn != txn->mt_env->me_txn0)
2906 /** Save the freelist as of this transaction to the freeDB.
2907 * This changes the freelist. Keep trying until it stabilizes.
2910 mdb_freelist_save(MDB_txn *txn)
2912 /* env->me_pghead[] can grow and shrink during this call.
2913 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2914 * Page numbers cannot disappear from txn->mt_free_pgs[].
2917 MDB_env *env = txn->mt_env;
2918 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2919 txnid_t pglast = 0, head_id = 0;
2920 pgno_t freecnt = 0, *free_pgs, *mop;
2921 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2923 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2925 if (env->me_pghead) {
2926 /* Make sure first page of freeDB is touched and on freelist */
2927 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2928 if (rc && rc != MDB_NOTFOUND)
2932 if (!env->me_pghead && txn->mt_loose_pgs) {
2933 /* Put loose page numbers in mt_free_pgs, since
2934 * we may be unable to return them to me_pghead.
2936 MDB_page *mp = txn->mt_loose_pgs;
2937 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
2939 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
2940 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2941 txn->mt_loose_pgs = NULL;
2942 txn->mt_loose_count = 0;
2945 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2946 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2947 ? SSIZE_MAX : maxfree_1pg;
2950 /* Come back here after each Put() in case freelist changed */
2955 /* If using records from freeDB which we have not yet
2956 * deleted, delete them and any we reserved for me_pghead.
2958 while (pglast < env->me_pglast) {
2959 rc = mdb_cursor_first(&mc, &key, NULL);
2962 pglast = head_id = *(txnid_t *)key.mv_data;
2963 total_room = head_room = 0;
2964 mdb_tassert(txn, pglast <= env->me_pglast);
2965 rc = mdb_cursor_del(&mc, 0);
2970 /* Save the IDL of pages freed by this txn, to a single record */
2971 if (freecnt < txn->mt_free_pgs[0]) {
2973 /* Make sure last page of freeDB is touched and on freelist */
2974 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2975 if (rc && rc != MDB_NOTFOUND)
2978 free_pgs = txn->mt_free_pgs;
2979 /* Write to last page of freeDB */
2980 key.mv_size = sizeof(txn->mt_txnid);
2981 key.mv_data = &txn->mt_txnid;
2983 freecnt = free_pgs[0];
2984 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2985 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2988 /* Retry if mt_free_pgs[] grew during the Put() */
2989 free_pgs = txn->mt_free_pgs;
2990 } while (freecnt < free_pgs[0]);
2991 mdb_midl_sort(free_pgs);
2992 memcpy(data.mv_data, free_pgs, data.mv_size);
2995 unsigned int i = free_pgs[0];
2996 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2997 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2999 DPRINTF(("IDL %"Z"u", free_pgs[i]));
3005 mop = env->me_pghead;
3006 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3008 /* Reserve records for me_pghead[]. Split it if multi-page,
3009 * to avoid searching freeDB for a page range. Use keys in
3010 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3012 if (total_room >= mop_len) {
3013 if (total_room == mop_len || --more < 0)
3015 } else if (head_room >= maxfree_1pg && head_id > 1) {
3016 /* Keep current record (overflow page), add a new one */
3020 /* (Re)write {key = head_id, IDL length = head_room} */
3021 total_room -= head_room;
3022 head_room = mop_len - total_room;
3023 if (head_room > maxfree_1pg && head_id > 1) {
3024 /* Overflow multi-page for part of me_pghead */
3025 head_room /= head_id; /* amortize page sizes */
3026 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3027 } else if (head_room < 0) {
3028 /* Rare case, not bothering to delete this record */
3031 key.mv_size = sizeof(head_id);
3032 key.mv_data = &head_id;
3033 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3034 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3037 /* IDL is initially empty, zero out at least the length */
3038 pgs = (pgno_t *)data.mv_data;
3039 j = head_room > clean_limit ? head_room : 0;
3043 total_room += head_room;
3046 /* Return loose page numbers to me_pghead, though usually none are
3047 * left at this point. The pages themselves remain in dirty_list.
3049 if (txn->mt_loose_pgs) {
3050 MDB_page *mp = txn->mt_loose_pgs;
3051 unsigned count = txn->mt_loose_count;
3053 /* Room for loose pages + temp IDL with same */
3054 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3056 mop = env->me_pghead;
3057 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3058 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3059 loose[ ++count ] = mp->mp_pgno;
3061 mdb_midl_sort(loose);
3062 mdb_midl_xmerge(mop, loose);
3063 txn->mt_loose_pgs = NULL;
3064 txn->mt_loose_count = 0;
3068 /* Fill in the reserved me_pghead records */
3074 rc = mdb_cursor_first(&mc, &key, &data);
3075 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3076 txnid_t id = *(txnid_t *)key.mv_data;
3077 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3080 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3082 if (len > mop_len) {
3084 data.mv_size = (len + 1) * sizeof(MDB_ID);
3086 data.mv_data = mop -= len;
3089 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3091 if (rc || !(mop_len -= len))
3098 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3099 * @param[in] txn the transaction that's being committed
3100 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3101 * @return 0 on success, non-zero on failure.
3104 mdb_page_flush(MDB_txn *txn, int keep)
3106 MDB_env *env = txn->mt_env;
3107 MDB_ID2L dl = txn->mt_u.dirty_list;
3108 unsigned psize = env->me_psize, j;
3109 int i, pagecount = dl[0].mid, rc;
3110 size_t size = 0, pos = 0;
3112 MDB_page *dp = NULL;
3116 struct iovec iov[MDB_COMMIT_PAGES];
3117 ssize_t wpos = 0, wsize = 0, wres;
3118 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3124 if (env->me_flags & MDB_WRITEMAP) {
3125 /* Clear dirty flags */
3126 while (++i <= pagecount) {
3128 /* Don't flush this page yet */
3129 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3130 dp->mp_flags &= ~P_KEEP;
3134 dp->mp_flags &= ~P_DIRTY;
3139 /* Write the pages */
3141 if (++i <= pagecount) {
3143 /* Don't flush this page yet */
3144 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3145 dp->mp_flags &= ~P_KEEP;
3150 /* clear dirty flag */
3151 dp->mp_flags &= ~P_DIRTY;
3154 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3159 /* Windows actually supports scatter/gather I/O, but only on
3160 * unbuffered file handles. Since we're relying on the OS page
3161 * cache for all our data, that's self-defeating. So we just
3162 * write pages one at a time. We use the ov structure to set
3163 * the write offset, to at least save the overhead of a Seek
3166 DPRINTF(("committing page %"Z"u", pgno));
3167 memset(&ov, 0, sizeof(ov));
3168 ov.Offset = pos & 0xffffffff;
3169 ov.OffsetHigh = pos >> 16 >> 16;
3170 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3172 DPRINTF(("WriteFile: %d", rc));
3176 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3177 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3179 /* Write previous page(s) */
3180 #ifdef MDB_USE_PWRITEV
3181 wres = pwritev(env->me_fd, iov, n, wpos);
3184 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3186 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3188 DPRINTF(("lseek: %s", strerror(rc)));
3191 wres = writev(env->me_fd, iov, n);
3194 if (wres != wsize) {
3197 DPRINTF(("Write error: %s", strerror(rc)));
3199 rc = EIO; /* TODO: Use which error code? */
3200 DPUTS("short write, filesystem full?");
3211 DPRINTF(("committing page %"Z"u", pgno));
3212 next_pos = pos + size;
3213 iov[n].iov_len = size;
3214 iov[n].iov_base = (char *)dp;
3220 /* MIPS has cache coherency issues, this is a no-op everywhere else
3221 * Note: for any size >= on-chip cache size, entire on-chip cache is
3224 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3226 for (i = keep; ++i <= pagecount; ) {
3228 /* This is a page we skipped above */
3231 dl[j].mid = dp->mp_pgno;
3234 mdb_dpage_free(env, dp);
3239 txn->mt_dirty_room += i - j;
3245 mdb_txn_commit(MDB_txn *txn)
3251 if (txn == NULL || txn->mt_env == NULL)
3254 if (txn->mt_child) {
3255 rc = mdb_txn_commit(txn->mt_child);
3256 txn->mt_child = NULL;
3263 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3264 mdb_dbis_update(txn, 1);
3265 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
3270 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
3271 DPUTS("error flag is set, can't commit");
3273 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3278 if (txn->mt_parent) {
3279 MDB_txn *parent = txn->mt_parent;
3283 unsigned x, y, len, ps_len;
3285 /* Append our free list to parent's */
3286 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3289 mdb_midl_free(txn->mt_free_pgs);
3290 /* Failures after this must either undo the changes
3291 * to the parent or set MDB_TXN_ERROR in the parent.
3294 parent->mt_next_pgno = txn->mt_next_pgno;
3295 parent->mt_flags = txn->mt_flags;
3297 /* Merge our cursors into parent's and close them */
3298 mdb_cursors_close(txn, 1);
3300 /* Update parent's DB table. */
3301 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3302 parent->mt_numdbs = txn->mt_numdbs;
3303 parent->mt_dbflags[0] = txn->mt_dbflags[0];
3304 parent->mt_dbflags[1] = txn->mt_dbflags[1];
3305 for (i=2; i<txn->mt_numdbs; i++) {
3306 /* preserve parent's DB_NEW status */
3307 x = parent->mt_dbflags[i] & DB_NEW;
3308 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3311 dst = parent->mt_u.dirty_list;
3312 src = txn->mt_u.dirty_list;
3313 /* Remove anything in our dirty list from parent's spill list */
3314 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3316 pspill[0] = (pgno_t)-1;
3317 /* Mark our dirty pages as deleted in parent spill list */
3318 for (i=0, len=src[0].mid; ++i <= len; ) {
3319 MDB_ID pn = src[i].mid << 1;
3320 while (pn > pspill[x])
3322 if (pn == pspill[x]) {
3327 /* Squash deleted pagenums if we deleted any */
3328 for (x=y; ++x <= ps_len; )
3329 if (!(pspill[x] & 1))
3330 pspill[++y] = pspill[x];
3334 /* Find len = length of merging our dirty list with parent's */
3336 dst[0].mid = 0; /* simplify loops */
3337 if (parent->mt_parent) {
3338 len = x + src[0].mid;
3339 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3340 for (i = x; y && i; y--) {
3341 pgno_t yp = src[y].mid;
3342 while (yp < dst[i].mid)
3344 if (yp == dst[i].mid) {
3349 } else { /* Simplify the above for single-ancestor case */
3350 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3352 /* Merge our dirty list with parent's */
3354 for (i = len; y; dst[i--] = src[y--]) {
3355 pgno_t yp = src[y].mid;
3356 while (yp < dst[x].mid)
3357 dst[i--] = dst[x--];
3358 if (yp == dst[x].mid)
3359 free(dst[x--].mptr);
3361 mdb_tassert(txn, i == x);
3363 free(txn->mt_u.dirty_list);
3364 parent->mt_dirty_room = txn->mt_dirty_room;
3365 if (txn->mt_spill_pgs) {
3366 if (parent->mt_spill_pgs) {
3367 /* TODO: Prevent failure here, so parent does not fail */
3368 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3370 parent->mt_flags |= MDB_TXN_ERROR;
3371 mdb_midl_free(txn->mt_spill_pgs);
3372 mdb_midl_sort(parent->mt_spill_pgs);
3374 parent->mt_spill_pgs = txn->mt_spill_pgs;
3378 /* Append our loose page list to parent's */
3379 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(lp))
3381 *lp = txn->mt_loose_pgs;
3382 parent->mt_loose_count += txn->mt_loose_count;
3384 parent->mt_child = NULL;
3385 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3390 if (txn != env->me_txn) {
3391 DPUTS("attempt to commit unknown transaction");
3396 mdb_cursors_close(txn, 0);
3398 if (!txn->mt_u.dirty_list[0].mid &&
3399 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3402 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3403 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3405 /* Update DB root pointers */
3406 if (txn->mt_numdbs > 2) {
3410 data.mv_size = sizeof(MDB_db);
3412 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3413 for (i = 2; i < txn->mt_numdbs; i++) {
3414 if (txn->mt_dbflags[i] & DB_DIRTY) {
3415 if (TXN_DBI_CHANGED(txn, i)) {
3419 data.mv_data = &txn->mt_dbs[i];
3420 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
3427 rc = mdb_freelist_save(txn);
3431 mdb_midl_free(env->me_pghead);
3432 env->me_pghead = NULL;
3433 if (mdb_midl_shrink(&txn->mt_free_pgs))
3434 env->me_free_pgs = txn->mt_free_pgs;
3440 if ((rc = mdb_page_flush(txn, 0)) ||
3441 (rc = mdb_env_sync(env, 0)) ||
3442 (rc = mdb_env_write_meta(txn)))
3445 /* Free P_LOOSE pages left behind in dirty_list */
3446 if (!(env->me_flags & MDB_WRITEMAP))
3447 mdb_dlist_free(txn);
3452 mdb_dbis_update(txn, 1);
3455 UNLOCK_MUTEX(MDB_MUTEX(env, w));
3456 if (txn != env->me_txn0)
3466 /** Read the environment parameters of a DB environment before
3467 * mapping it into memory.
3468 * @param[in] env the environment handle
3469 * @param[out] meta address of where to store the meta information
3470 * @return 0 on success, non-zero on failure.
3473 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3479 enum { Size = sizeof(pbuf) };
3481 /* We don't know the page size yet, so use a minimum value.
3482 * Read both meta pages so we can use the latest one.
3485 for (i=off=0; i<2; i++, off = meta->mm_psize) {
3489 memset(&ov, 0, sizeof(ov));
3491 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3492 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3495 rc = pread(env->me_fd, &pbuf, Size, off);
3498 if (rc == 0 && off == 0)
3500 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3501 DPRINTF(("read: %s", mdb_strerror(rc)));
3505 p = (MDB_page *)&pbuf;
3507 if (!F_ISSET(p->mp_flags, P_META)) {
3508 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3513 if (m->mm_magic != MDB_MAGIC) {
3514 DPUTS("meta has invalid magic");
3518 if (m->mm_version != MDB_DATA_VERSION) {
3519 DPRINTF(("database is version %u, expected version %u",
3520 m->mm_version, MDB_DATA_VERSION));
3521 return MDB_VERSION_MISMATCH;
3524 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3530 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3532 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3534 meta->mm_magic = MDB_MAGIC;
3535 meta->mm_version = MDB_DATA_VERSION;
3536 meta->mm_mapsize = env->me_mapsize;
3537 meta->mm_psize = env->me_psize;
3538 meta->mm_last_pg = 1;
3539 meta->mm_flags = env->me_flags & 0xffff;
3540 meta->mm_flags |= MDB_INTEGERKEY;
3541 meta->mm_dbs[0].md_root = P_INVALID;
3542 meta->mm_dbs[1].md_root = P_INVALID;
3545 /** Write the environment parameters of a freshly created DB environment.
3546 * @param[in] env the environment handle
3547 * @param[in] meta the #MDB_meta to write
3548 * @return 0 on success, non-zero on failure.
3551 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3559 memset(&ov, 0, sizeof(ov));
3560 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3562 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3565 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3566 len = pwrite(fd, ptr, size, pos); \
3567 rc = (len >= 0); } while(0)
3570 DPUTS("writing new meta page");
3572 psize = env->me_psize;
3574 p = calloc(2, psize);
3576 p->mp_flags = P_META;
3577 *(MDB_meta *)METADATA(p) = *meta;
3579 q = (MDB_page *)((char *)p + psize);
3581 q->mp_flags = P_META;
3582 *(MDB_meta *)METADATA(q) = *meta;
3584 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3587 else if ((unsigned) len == psize * 2)
3595 /** Update the environment info to commit a transaction.
3596 * @param[in] txn the transaction that's being committed
3597 * @return 0 on success, non-zero on failure.
3600 mdb_env_write_meta(MDB_txn *txn)
3603 MDB_meta meta, metab, *mp;
3606 int rc, len, toggle;
3615 toggle = txn->mt_txnid & 1;
3616 DPRINTF(("writing meta page %d for root page %"Z"u",
3617 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3620 mp = env->me_metas[toggle];
3621 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3622 /* Persist any increases of mapsize config */
3623 if (mapsize < env->me_mapsize)
3624 mapsize = env->me_mapsize;
3626 if (env->me_flags & MDB_WRITEMAP) {
3627 mp->mm_mapsize = mapsize;
3628 mp->mm_dbs[0] = txn->mt_dbs[0];
3629 mp->mm_dbs[1] = txn->mt_dbs[1];
3630 mp->mm_last_pg = txn->mt_next_pgno - 1;
3631 #if !(defined(_MSC_VER) || defined(__i386__) || defined(__x86_64__))
3632 /* LY: issue a memory barrier, if not x86. ITS#7969 */
3633 __sync_synchronize();
3635 mp->mm_txnid = txn->mt_txnid;
3636 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3637 unsigned meta_size = env->me_psize;
3638 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3641 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3642 if (meta_size < env->me_os_psize)
3643 meta_size += meta_size;
3648 if (MDB_MSYNC(ptr, meta_size, rc)) {
3655 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3656 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3658 meta.mm_mapsize = mapsize;
3659 meta.mm_dbs[0] = txn->mt_dbs[0];
3660 meta.mm_dbs[1] = txn->mt_dbs[1];
3661 meta.mm_last_pg = txn->mt_next_pgno - 1;
3662 meta.mm_txnid = txn->mt_txnid;
3664 off = offsetof(MDB_meta, mm_mapsize);
3665 ptr = (char *)&meta + off;
3666 len = sizeof(MDB_meta) - off;
3668 off += env->me_psize;
3671 /* Write to the SYNC fd */
3672 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3673 env->me_fd : env->me_mfd;
3676 memset(&ov, 0, sizeof(ov));
3678 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3682 rc = pwrite(mfd, ptr, len, off);
3685 rc = rc < 0 ? ErrCode() : EIO;
3686 DPUTS("write failed, disk error?");
3687 /* On a failure, the pagecache still contains the new data.
3688 * Write some old data back, to prevent it from being used.
3689 * Use the non-SYNC fd; we know it will fail anyway.
3691 meta.mm_last_pg = metab.mm_last_pg;
3692 meta.mm_txnid = metab.mm_txnid;
3694 memset(&ov, 0, sizeof(ov));
3696 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3698 r2 = pwrite(env->me_fd, ptr, len, off);
3699 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3702 env->me_flags |= MDB_FATAL_ERROR;
3705 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3706 CACHEFLUSH(env->me_map + off, len, DCACHE);
3708 /* Memory ordering issues are irrelevant; since the entire writer
3709 * is wrapped by wmutex, all of these changes will become visible
3710 * after the wmutex is unlocked. Since the DB is multi-version,
3711 * readers will get consistent data regardless of how fresh or
3712 * how stale their view of these values is.
3715 env->me_txns->mti_txnid = txn->mt_txnid;
3720 /** Check both meta pages to see which one is newer.
3721 * @param[in] env the environment handle
3722 * @return meta toggle (0 or 1).
3725 mdb_env_pick_meta(const MDB_env *env)
3727 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3731 mdb_env_create(MDB_env **env)
3735 e = calloc(1, sizeof(MDB_env));
3739 e->me_maxreaders = DEFAULT_READERS;
3740 e->me_maxdbs = e->me_numdbs = 2;
3741 e->me_fd = INVALID_HANDLE_VALUE;
3742 e->me_lfd = INVALID_HANDLE_VALUE;
3743 e->me_mfd = INVALID_HANDLE_VALUE;
3744 #ifdef MDB_USE_SYSV_SEM
3745 e->me_rmutex.semid = -1;
3746 e->me_wmutex.semid = -1;
3748 e->me_pid = getpid();
3749 GET_PAGESIZE(e->me_os_psize);
3750 VGMEMP_CREATE(e,0,0);
3756 mdb_env_map(MDB_env *env, void *addr)
3759 unsigned int flags = env->me_flags;
3763 LONG sizelo, sizehi;
3766 if (flags & MDB_RDONLY) {
3767 /* Don't set explicit map size, use whatever exists */
3772 msize = env->me_mapsize;
3773 sizelo = msize & 0xffffffff;
3774 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3776 /* Windows won't create mappings for zero length files.
3777 * and won't map more than the file size.
3778 * Just set the maxsize right now.
3780 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3781 || !SetEndOfFile(env->me_fd)
3782 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3786 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3787 PAGE_READWRITE : PAGE_READONLY,
3788 sizehi, sizelo, NULL);
3791 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3792 FILE_MAP_WRITE : FILE_MAP_READ,
3794 rc = env->me_map ? 0 : ErrCode();
3799 int prot = PROT_READ;
3800 if (flags & MDB_WRITEMAP) {
3802 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3805 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3807 if (env->me_map == MAP_FAILED) {
3812 if (flags & MDB_NORDAHEAD) {
3813 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3815 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3817 #ifdef POSIX_MADV_RANDOM
3818 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3819 #endif /* POSIX_MADV_RANDOM */
3820 #endif /* MADV_RANDOM */
3824 /* Can happen because the address argument to mmap() is just a
3825 * hint. mmap() can pick another, e.g. if the range is in use.
3826 * The MAP_FIXED flag would prevent that, but then mmap could
3827 * instead unmap existing pages to make room for the new map.
3829 if (addr && env->me_map != addr)
3830 return EBUSY; /* TODO: Make a new MDB_* error code? */
3832 p = (MDB_page *)env->me_map;
3833 env->me_metas[0] = METADATA(p);
3834 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3840 mdb_env_set_mapsize(MDB_env *env, size_t size)
3842 /* If env is already open, caller is responsible for making
3843 * sure there are no active txns.
3851 meta = env->me_metas[mdb_env_pick_meta(env)];
3853 size = meta->mm_mapsize;
3855 /* Silently round up to minimum if the size is too small */
3856 size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
3860 munmap(env->me_map, env->me_mapsize);
3861 env->me_mapsize = size;
3862 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3863 rc = mdb_env_map(env, old);
3867 env->me_mapsize = size;
3869 env->me_maxpg = env->me_mapsize / env->me_psize;
3874 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3878 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3883 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3885 if (env->me_map || readers < 1)
3887 env->me_maxreaders = readers;
3892 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3894 if (!env || !readers)
3896 *readers = env->me_maxreaders;
3901 mdb_fsize(HANDLE fd, size_t *size)
3904 LARGE_INTEGER fsize;
3906 if (!GetFileSizeEx(fd, &fsize))
3909 *size = fsize.QuadPart;
3921 /** Further setup required for opening an LMDB environment
3924 mdb_env_open2(MDB_env *env)
3926 unsigned int flags = env->me_flags;
3927 int i, newenv = 0, rc;
3931 /* See if we should use QueryLimited */
3933 if ((rc & 0xff) > 5)
3934 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3936 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3939 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3942 DPUTS("new mdbenv");
3944 env->me_psize = env->me_os_psize;
3945 if (env->me_psize > MAX_PAGESIZE)
3946 env->me_psize = MAX_PAGESIZE;
3947 memset(&meta, 0, sizeof(meta));
3948 mdb_env_init_meta0(env, &meta);
3949 meta.mm_mapsize = DEFAULT_MAPSIZE;
3951 env->me_psize = meta.mm_psize;
3954 /* Was a mapsize configured? */
3955 if (!env->me_mapsize) {
3956 env->me_mapsize = meta.mm_mapsize;
3959 /* Make sure mapsize >= committed data size. Even when using
3960 * mm_mapsize, which could be broken in old files (ITS#7789).
3962 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3963 if (env->me_mapsize < minsize)
3964 env->me_mapsize = minsize;
3966 meta.mm_mapsize = env->me_mapsize;
3968 if (newenv && !(flags & MDB_FIXEDMAP)) {
3969 /* mdb_env_map() may grow the datafile. Write the metapages
3970 * first, so the file will be valid if initialization fails.
3971 * Except with FIXEDMAP, since we do not yet know mm_address.
3972 * We could fill in mm_address later, but then a different
3973 * program might end up doing that - one with a memory layout
3974 * and map address which does not suit the main program.
3976 rc = mdb_env_init_meta(env, &meta);
3982 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
3987 if (flags & MDB_FIXEDMAP)
3988 meta.mm_address = env->me_map;
3989 i = mdb_env_init_meta(env, &meta);
3990 if (i != MDB_SUCCESS) {
3995 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3996 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
3998 #if !(MDB_MAXKEYSIZE)
3999 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4001 env->me_maxpg = env->me_mapsize / env->me_psize;
4005 int toggle = mdb_env_pick_meta(env);
4006 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
4008 DPRINTF(("opened database version %u, pagesize %u",
4009 env->me_metas[0]->mm_version, env->me_psize));
4010 DPRINTF(("using meta page %d", toggle));
4011 DPRINTF(("depth: %u", db->md_depth));
4012 DPRINTF(("entries: %"Z"u", db->md_entries));
4013 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
4014 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
4015 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
4016 DPRINTF(("root: %"Z"u", db->md_root));
4024 /** Release a reader thread's slot in the reader lock table.
4025 * This function is called automatically when a thread exits.
4026 * @param[in] ptr This points to the slot in the reader lock table.
4029 mdb_env_reader_dest(void *ptr)
4031 MDB_reader *reader = ptr;
4037 /** Junk for arranging thread-specific callbacks on Windows. This is
4038 * necessarily platform and compiler-specific. Windows supports up
4039 * to 1088 keys. Let's assume nobody opens more than 64 environments
4040 * in a single process, for now. They can override this if needed.
4042 #ifndef MAX_TLS_KEYS
4043 #define MAX_TLS_KEYS 64
4045 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4046 static int mdb_tls_nkeys;
4048 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4052 case DLL_PROCESS_ATTACH: break;
4053 case DLL_THREAD_ATTACH: break;
4054 case DLL_THREAD_DETACH:
4055 for (i=0; i<mdb_tls_nkeys; i++) {
4056 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4058 mdb_env_reader_dest(r);
4062 case DLL_PROCESS_DETACH: break;
4067 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4069 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4073 /* Force some symbol references.
4074 * _tls_used forces the linker to create the TLS directory if not already done
4075 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4077 #pragma comment(linker, "/INCLUDE:_tls_used")
4078 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4079 #pragma const_seg(".CRT$XLB")
4080 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4081 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4084 #pragma comment(linker, "/INCLUDE:__tls_used")
4085 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4086 #pragma data_seg(".CRT$XLB")
4087 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4089 #endif /* WIN 32/64 */
4090 #endif /* !__GNUC__ */
4093 /** Downgrade the exclusive lock on the region back to shared */
4095 mdb_env_share_locks(MDB_env *env, int *excl)
4097 int rc = 0, toggle = mdb_env_pick_meta(env);
4099 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
4104 /* First acquire a shared lock. The Unlock will
4105 * then release the existing exclusive lock.
4107 memset(&ov, 0, sizeof(ov));
4108 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4111 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4117 struct flock lock_info;
4118 /* The shared lock replaces the existing lock */
4119 memset((void *)&lock_info, 0, sizeof(lock_info));
4120 lock_info.l_type = F_RDLCK;
4121 lock_info.l_whence = SEEK_SET;
4122 lock_info.l_start = 0;
4123 lock_info.l_len = 1;
4124 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4125 (rc = ErrCode()) == EINTR) ;
4126 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4133 /** Try to get exclusive lock, otherwise shared.
4134 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4137 mdb_env_excl_lock(MDB_env *env, int *excl)
4141 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4145 memset(&ov, 0, sizeof(ov));
4146 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4153 struct flock lock_info;
4154 memset((void *)&lock_info, 0, sizeof(lock_info));
4155 lock_info.l_type = F_WRLCK;
4156 lock_info.l_whence = SEEK_SET;
4157 lock_info.l_start = 0;
4158 lock_info.l_len = 1;
4159 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4160 (rc = ErrCode()) == EINTR) ;
4164 # ifdef MDB_USE_SYSV_SEM
4165 if (*excl < 0) /* always true when !MDB_USE_SYSV_SEM */
4168 lock_info.l_type = F_RDLCK;
4169 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4170 (rc = ErrCode()) == EINTR) ;
4180 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4182 * @(#) $Revision: 5.1 $
4183 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4184 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4186 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4190 * Please do not copyright this code. This code is in the public domain.
4192 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4193 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4194 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4195 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4196 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4197 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4198 * PERFORMANCE OF THIS SOFTWARE.
4201 * chongo <Landon Curt Noll> /\oo/\
4202 * http://www.isthe.com/chongo/
4204 * Share and Enjoy! :-)
4207 typedef unsigned long long mdb_hash_t;
4208 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4210 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4211 * @param[in] val value to hash
4212 * @param[in] hval initial value for hash
4213 * @return 64 bit hash
4215 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4216 * hval arg on the first call.
4219 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4221 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4222 unsigned char *end = s + val->mv_size;
4224 * FNV-1a hash each octet of the string
4227 /* xor the bottom with the current octet */
4228 hval ^= (mdb_hash_t)*s++;
4230 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4231 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4232 (hval << 7) + (hval << 8) + (hval << 40);
4234 /* return our new hash value */
4238 /** Hash the string and output the encoded hash.
4239 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4240 * very short name limits. We don't care about the encoding being reversible,
4241 * we just want to preserve as many bits of the input as possible in a
4242 * small printable string.
4243 * @param[in] str string to hash
4244 * @param[out] encbuf an array of 11 chars to hold the hash
4246 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4249 mdb_pack85(unsigned long l, char *out)
4253 for (i=0; i<5; i++) {
4254 *out++ = mdb_a85[l % 85];
4260 mdb_hash_enc(MDB_val *val, char *encbuf)
4262 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4264 mdb_pack85(h, encbuf);
4265 mdb_pack85(h>>32, encbuf+5);
4270 /** Open and/or initialize the lock region for the environment.
4271 * @param[in] env The LMDB environment.
4272 * @param[in] lpath The pathname of the file used for the lock region.
4273 * @param[in] mode The Unix permissions for the file, if we create it.
4274 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4275 * @return 0 on success, non-zero on failure.
4278 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4281 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4283 # define MDB_ERRCODE_ROFS EROFS
4284 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4285 # define MDB_CLOEXEC O_CLOEXEC
4288 # define MDB_CLOEXEC 0
4295 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
4296 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4297 FILE_ATTRIBUTE_NORMAL, NULL);
4299 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4301 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4303 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4308 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4309 /* Lose record locks when exec*() */
4310 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4311 fcntl(env->me_lfd, F_SETFD, fdflags);
4314 if (!(env->me_flags & MDB_NOTLS)) {
4315 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4318 env->me_flags |= MDB_ENV_TXKEY;
4320 /* Windows TLS callbacks need help finding their TLS info. */
4321 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4325 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4329 /* Try to get exclusive lock. If we succeed, then
4330 * nobody is using the lock region and we should initialize it.
4332 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4335 size = GetFileSize(env->me_lfd, NULL);
4337 size = lseek(env->me_lfd, 0, SEEK_END);
4338 if (size == -1) goto fail_errno;
4340 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4341 if (size < rsize && *excl > 0) {
4343 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4344 || !SetEndOfFile(env->me_lfd))
4347 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4351 size = rsize - sizeof(MDB_txninfo);
4352 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4357 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4359 if (!mh) goto fail_errno;
4360 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4362 if (!env->me_txns) goto fail_errno;
4364 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4366 if (m == MAP_FAILED) goto fail_errno;
4372 BY_HANDLE_FILE_INFORMATION stbuf;
4381 if (!mdb_sec_inited) {
4382 InitializeSecurityDescriptor(&mdb_null_sd,
4383 SECURITY_DESCRIPTOR_REVISION);
4384 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4385 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4386 mdb_all_sa.bInheritHandle = FALSE;
4387 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4390 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4391 idbuf.volume = stbuf.dwVolumeSerialNumber;
4392 idbuf.nhigh = stbuf.nFileIndexHigh;
4393 idbuf.nlow = stbuf.nFileIndexLow;
4394 val.mv_data = &idbuf;
4395 val.mv_size = sizeof(idbuf);
4396 mdb_hash_enc(&val, encbuf);
4397 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4398 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4399 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4400 if (!env->me_rmutex) goto fail_errno;
4401 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4402 if (!env->me_wmutex) goto fail_errno;
4403 #elif defined(MDB_USE_SYSV_SEM)
4405 unsigned short vals[2] = {1, 1};
4406 int semid = semget(IPC_PRIVATE, 2, mode);
4410 env->me_rmutex.semid = semid;
4411 env->me_wmutex.semid = semid;
4412 env->me_rmutex.semnum = 0;
4413 env->me_wmutex.semnum = 1;
4416 if (semctl(semid, 0, SETALL, semu) < 0)
4418 env->me_txns->mti_semid = semid;
4419 #else /* MDB_USE_SYSV_SEM */
4420 pthread_mutexattr_t mattr;
4422 if ((rc = pthread_mutexattr_init(&mattr))
4423 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4424 #ifdef MDB_ROBUST_SUPPORTED
4425 || (rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST))
4427 || (rc = pthread_mutex_init(&env->me_txns->mti_rmutex, &mattr))
4428 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
4430 pthread_mutexattr_destroy(&mattr);
4431 #endif /* _WIN32 || MDB_USE_SYSV_SEM */
4433 env->me_txns->mti_magic = MDB_MAGIC;
4434 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4435 env->me_txns->mti_txnid = 0;
4436 env->me_txns->mti_numreaders = 0;
4439 #ifdef MDB_USE_SYSV_SEM
4440 struct semid_ds buf;
4444 if (env->me_txns->mti_magic != MDB_MAGIC) {
4445 DPUTS("lock region has invalid magic");
4449 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4450 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4451 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4452 rc = MDB_VERSION_MISMATCH;
4456 if (rc && rc != EACCES && rc != EAGAIN) {
4460 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4461 if (!env->me_rmutex) goto fail_errno;
4462 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4463 if (!env->me_wmutex) goto fail_errno;
4464 #elif defined(MDB_USE_SYSV_SEM)
4465 semid = env->me_txns->mti_semid;
4468 /* check for read access */
4469 if (semctl(semid, 0, IPC_STAT, semu) < 0)
4471 /* check for write access */
4472 if (semctl(semid, 0, IPC_SET, semu) < 0)
4475 env->me_rmutex.semid = semid;
4476 env->me_wmutex.semid = semid;
4477 env->me_rmutex.semnum = 0;
4478 env->me_wmutex.semnum = 1;
4489 /** The name of the lock file in the DB environment */
4490 #define LOCKNAME "/lock.mdb"
4491 /** The name of the data file in the DB environment */
4492 #define DATANAME "/data.mdb"
4493 /** The suffix of the lock file when no subdir is used */
4494 #define LOCKSUFF "-lock"
4495 /** Only a subset of the @ref mdb_env flags can be changed
4496 * at runtime. Changing other flags requires closing the
4497 * environment and re-opening it with the new flags.
4499 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4500 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
4501 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4503 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4504 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4508 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4510 int oflags, rc, len, excl = -1;
4511 char *lpath, *dpath;
4513 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4517 if (flags & MDB_NOSUBDIR) {
4518 rc = len + sizeof(LOCKSUFF) + len + 1;
4520 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4525 if (flags & MDB_NOSUBDIR) {
4526 dpath = lpath + len + sizeof(LOCKSUFF);
4527 sprintf(lpath, "%s" LOCKSUFF, path);
4528 strcpy(dpath, path);
4530 dpath = lpath + len + sizeof(LOCKNAME);
4531 sprintf(lpath, "%s" LOCKNAME, path);
4532 sprintf(dpath, "%s" DATANAME, path);
4536 flags |= env->me_flags;
4537 if (flags & MDB_RDONLY) {
4538 /* silently ignore WRITEMAP when we're only getting read access */
4539 flags &= ~MDB_WRITEMAP;
4541 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4542 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4545 env->me_flags = flags |= MDB_ENV_ACTIVE;
4549 env->me_path = strdup(path);
4550 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4551 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4552 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4553 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4558 /* For RDONLY, get lockfile after we know datafile exists */
4559 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4560 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4566 if (F_ISSET(flags, MDB_RDONLY)) {
4567 oflags = GENERIC_READ;
4568 len = OPEN_EXISTING;
4570 oflags = GENERIC_READ|GENERIC_WRITE;
4573 mode = FILE_ATTRIBUTE_NORMAL;
4574 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4575 NULL, len, mode, NULL);
4577 if (F_ISSET(flags, MDB_RDONLY))
4580 oflags = O_RDWR | O_CREAT;
4582 env->me_fd = open(dpath, oflags, mode);
4584 if (env->me_fd == INVALID_HANDLE_VALUE) {
4589 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4590 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4595 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4596 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4597 env->me_mfd = env->me_fd;
4599 /* Synchronous fd for meta writes. Needed even with
4600 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4603 len = OPEN_EXISTING;
4604 env->me_mfd = CreateFile(dpath, oflags,
4605 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4606 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4609 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4611 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4616 DPRINTF(("opened dbenv %p", (void *) env));
4618 rc = mdb_env_share_locks(env, &excl);
4622 if (!((flags & MDB_RDONLY) ||
4623 (env->me_pbuf = calloc(1, env->me_psize))))
4625 if (!(flags & MDB_RDONLY)) {
4627 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
4628 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
4629 txn = calloc(1, size);
4631 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
4632 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
4633 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
4634 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
4636 txn->mt_dbxs = env->me_dbxs;
4646 mdb_env_close0(env, excl);
4652 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4654 mdb_env_close0(MDB_env *env, int excl)
4658 if (!(env->me_flags & MDB_ENV_ACTIVE))
4661 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4662 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4663 free(env->me_dbxs[i].md_name.mv_data);
4666 free(env->me_dbiseqs);
4667 free(env->me_dbflags);
4670 free(env->me_dirty_list);
4672 mdb_midl_free(env->me_free_pgs);
4674 if (env->me_flags & MDB_ENV_TXKEY) {
4675 pthread_key_delete(env->me_txkey);
4677 /* Delete our key from the global list */
4678 for (i=0; i<mdb_tls_nkeys; i++)
4679 if (mdb_tls_keys[i] == env->me_txkey) {
4680 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4688 munmap(env->me_map, env->me_mapsize);
4690 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4691 (void) close(env->me_mfd);
4692 if (env->me_fd != INVALID_HANDLE_VALUE)
4693 (void) close(env->me_fd);
4695 MDB_PID_T pid = env->me_pid;
4696 /* Clearing readers is done in this function because
4697 * me_txkey with its destructor must be disabled first.
4699 for (i = env->me_numreaders; --i >= 0; )
4700 if (env->me_txns->mti_readers[i].mr_pid == pid)
4701 env->me_txns->mti_readers[i].mr_pid = 0;
4703 if (env->me_rmutex) {
4704 CloseHandle(env->me_rmutex);
4705 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4707 /* Windows automatically destroys the mutexes when
4708 * the last handle closes.
4710 #elif defined(MDB_USE_SYSV_SEM)
4711 if (env->me_rmutex.semid != -1) {
4712 /* If we have the filelock: If we are the
4713 * only remaining user, clean up semaphores.
4716 mdb_env_excl_lock(env, &excl);
4718 semctl(env->me_rmutex.semid, 0, IPC_RMID);
4721 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4723 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4726 /* Unlock the lockfile. Windows would have unlocked it
4727 * after closing anyway, but not necessarily at once.
4729 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4732 (void) close(env->me_lfd);
4735 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4739 mdb_env_close(MDB_env *env)
4746 VGMEMP_DESTROY(env);
4747 while ((dp = env->me_dpages) != NULL) {
4748 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4749 env->me_dpages = dp->mp_next;
4753 mdb_env_close0(env, 0);
4757 /** Compare two items pointing at aligned size_t's */
4759 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4761 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4762 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4765 /** Compare two items pointing at aligned unsigned int's */
4767 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4769 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4770 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4773 /** Compare two items pointing at unsigned ints of unknown alignment.
4774 * Nodes and keys are guaranteed to be 2-byte aligned.
4777 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4779 #if BYTE_ORDER == LITTLE_ENDIAN
4780 unsigned short *u, *c;
4783 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4784 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4787 } while(!x && u > (unsigned short *)a->mv_data);
4790 unsigned short *u, *c, *end;
4793 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4794 u = (unsigned short *)a->mv_data;
4795 c = (unsigned short *)b->mv_data;
4798 } while(!x && u < end);
4803 /** Compare two items pointing at size_t's of unknown alignment. */
4804 #ifdef MISALIGNED_OK
4805 # define mdb_cmp_clong mdb_cmp_long
4807 # define mdb_cmp_clong mdb_cmp_cint
4810 /** Compare two items lexically */
4812 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4819 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4825 diff = memcmp(a->mv_data, b->mv_data, len);
4826 return diff ? diff : len_diff<0 ? -1 : len_diff;
4829 /** Compare two items in reverse byte order */
4831 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4833 const unsigned char *p1, *p2, *p1_lim;
4837 p1_lim = (const unsigned char *)a->mv_data;
4838 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4839 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4841 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4847 while (p1 > p1_lim) {
4848 diff = *--p1 - *--p2;
4852 return len_diff<0 ? -1 : len_diff;
4855 /** Search for key within a page, using binary search.
4856 * Returns the smallest entry larger or equal to the key.
4857 * If exactp is non-null, stores whether the found entry was an exact match
4858 * in *exactp (1 or 0).
4859 * Updates the cursor index with the index of the found entry.
4860 * If no entry larger or equal to the key is found, returns NULL.
4863 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4865 unsigned int i = 0, nkeys;
4868 MDB_page *mp = mc->mc_pg[mc->mc_top];
4869 MDB_node *node = NULL;
4874 nkeys = NUMKEYS(mp);
4876 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4877 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4880 low = IS_LEAF(mp) ? 0 : 1;
4882 cmp = mc->mc_dbx->md_cmp;
4884 /* Branch pages have no data, so if using integer keys,
4885 * alignment is guaranteed. Use faster mdb_cmp_int.
4887 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4888 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4895 nodekey.mv_size = mc->mc_db->md_pad;
4896 node = NODEPTR(mp, 0); /* fake */
4897 while (low <= high) {
4898 i = (low + high) >> 1;
4899 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4900 rc = cmp(key, &nodekey);
4901 DPRINTF(("found leaf index %u [%s], rc = %i",
4902 i, DKEY(&nodekey), rc));
4911 while (low <= high) {
4912 i = (low + high) >> 1;
4914 node = NODEPTR(mp, i);
4915 nodekey.mv_size = NODEKSZ(node);
4916 nodekey.mv_data = NODEKEY(node);
4918 rc = cmp(key, &nodekey);
4921 DPRINTF(("found leaf index %u [%s], rc = %i",
4922 i, DKEY(&nodekey), rc));
4924 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4925 i, DKEY(&nodekey), NODEPGNO(node), rc));
4936 if (rc > 0) { /* Found entry is less than the key. */
4937 i++; /* Skip to get the smallest entry larger than key. */
4939 node = NODEPTR(mp, i);
4942 *exactp = (rc == 0 && nkeys > 0);
4943 /* store the key index */
4944 mc->mc_ki[mc->mc_top] = i;
4946 /* There is no entry larger or equal to the key. */
4949 /* nodeptr is fake for LEAF2 */
4955 mdb_cursor_adjust(MDB_cursor *mc, func)
4959 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4960 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4967 /** Pop a page off the top of the cursor's stack. */
4969 mdb_cursor_pop(MDB_cursor *mc)
4973 MDB_page *top = mc->mc_pg[mc->mc_top];
4979 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4980 DDBI(mc), (void *) mc));
4984 /** Push a page onto the top of the cursor's stack. */
4986 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4988 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4989 DDBI(mc), (void *) mc));
4991 if (mc->mc_snum >= CURSOR_STACK) {
4992 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4993 return MDB_CURSOR_FULL;
4996 mc->mc_top = mc->mc_snum++;
4997 mc->mc_pg[mc->mc_top] = mp;
4998 mc->mc_ki[mc->mc_top] = 0;
5003 /** Find the address of the page corresponding to a given page number.
5004 * @param[in] txn the transaction for this access.
5005 * @param[in] pgno the page number for the page to retrieve.
5006 * @param[out] ret address of a pointer where the page's address will be stored.
5007 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5008 * @return 0 on success, non-zero on failure.
5011 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
5013 MDB_env *env = txn->mt_env;
5017 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
5021 MDB_ID2L dl = tx2->mt_u.dirty_list;
5023 /* Spilled pages were dirtied in this txn and flushed
5024 * because the dirty list got full. Bring this page
5025 * back in from the map (but don't unspill it here,
5026 * leave that unless page_touch happens again).
5028 if (tx2->mt_spill_pgs) {
5029 MDB_ID pn = pgno << 1;
5030 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5031 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5032 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5037 unsigned x = mdb_mid2l_search(dl, pgno);
5038 if (x <= dl[0].mid && dl[x].mid == pgno) {
5044 } while ((tx2 = tx2->mt_parent) != NULL);
5047 if (pgno < txn->mt_next_pgno) {
5049 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5051 DPRINTF(("page %"Z"u not found", pgno));
5052 txn->mt_flags |= MDB_TXN_ERROR;
5053 return MDB_PAGE_NOTFOUND;
5063 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
5064 * The cursor is at the root page, set up the rest of it.
5067 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
5069 MDB_page *mp = mc->mc_pg[mc->mc_top];
5073 while (IS_BRANCH(mp)) {
5077 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
5078 mdb_cassert(mc, NUMKEYS(mp) > 1);
5079 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
5081 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
5083 if (flags & MDB_PS_LAST)
5084 i = NUMKEYS(mp) - 1;
5087 node = mdb_node_search(mc, key, &exact);
5089 i = NUMKEYS(mp) - 1;
5091 i = mc->mc_ki[mc->mc_top];
5093 mdb_cassert(mc, i > 0);
5097 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
5100 mdb_cassert(mc, i < NUMKEYS(mp));
5101 node = NODEPTR(mp, i);
5103 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5106 mc->mc_ki[mc->mc_top] = i;
5107 if ((rc = mdb_cursor_push(mc, mp)))
5110 if (flags & MDB_PS_MODIFY) {
5111 if ((rc = mdb_page_touch(mc)) != 0)
5113 mp = mc->mc_pg[mc->mc_top];
5118 DPRINTF(("internal error, index points to a %02X page!?",
5120 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5121 return MDB_CORRUPTED;
5124 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
5125 key ? DKEY(key) : "null"));
5126 mc->mc_flags |= C_INITIALIZED;
5127 mc->mc_flags &= ~C_EOF;
5132 /** Search for the lowest key under the current branch page.
5133 * This just bypasses a NUMKEYS check in the current page
5134 * before calling mdb_page_search_root(), because the callers
5135 * are all in situations where the current page is known to
5139 mdb_page_search_lowest(MDB_cursor *mc)
5141 MDB_page *mp = mc->mc_pg[mc->mc_top];
5142 MDB_node *node = NODEPTR(mp, 0);
5145 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5148 mc->mc_ki[mc->mc_top] = 0;
5149 if ((rc = mdb_cursor_push(mc, mp)))
5151 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5154 /** Search for the page a given key should be in.
5155 * Push it and its parent pages on the cursor stack.
5156 * @param[in,out] mc the cursor for this operation.
5157 * @param[in] key the key to search for, or NULL for first/last page.
5158 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5159 * are touched (updated with new page numbers).
5160 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5161 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5162 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5163 * @return 0 on success, non-zero on failure.
5166 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5171 /* Make sure the txn is still viable, then find the root from
5172 * the txn's db table and set it as the root of the cursor's stack.
5174 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
5175 DPUTS("transaction has failed, must abort");
5178 /* Make sure we're using an up-to-date root */
5179 if (*mc->mc_dbflag & DB_STALE) {
5181 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5183 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5184 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5191 MDB_node *leaf = mdb_node_search(&mc2,
5192 &mc->mc_dbx->md_name, &exact);
5194 return MDB_NOTFOUND;
5195 rc = mdb_node_read(mc->mc_txn, leaf, &data);
5198 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5200 /* The txn may not know this DBI, or another process may
5201 * have dropped and recreated the DB with other flags.
5203 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5204 return MDB_INCOMPATIBLE;
5205 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5207 *mc->mc_dbflag &= ~DB_STALE;
5209 root = mc->mc_db->md_root;
5211 if (root == P_INVALID) { /* Tree is empty. */
5212 DPUTS("tree is empty");
5213 return MDB_NOTFOUND;
5217 mdb_cassert(mc, root > 1);
5218 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5219 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
5225 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5226 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5228 if (flags & MDB_PS_MODIFY) {
5229 if ((rc = mdb_page_touch(mc)))
5233 if (flags & MDB_PS_ROOTONLY)
5236 return mdb_page_search_root(mc, key, flags);
5240 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5242 MDB_txn *txn = mc->mc_txn;
5243 pgno_t pg = mp->mp_pgno;
5244 unsigned x = 0, ovpages = mp->mp_pages;
5245 MDB_env *env = txn->mt_env;
5246 MDB_IDL sl = txn->mt_spill_pgs;
5247 MDB_ID pn = pg << 1;
5250 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5251 /* If the page is dirty or on the spill list we just acquired it,
5252 * so we should give it back to our current free list, if any.
5253 * Otherwise put it onto the list of pages we freed in this txn.
5255 * Won't create me_pghead: me_pglast must be inited along with it.
5256 * Unsupported in nested txns: They would need to hide the page
5257 * range in ancestor txns' dirty and spilled lists.
5259 if (env->me_pghead &&
5261 ((mp->mp_flags & P_DIRTY) ||
5262 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5266 MDB_ID2 *dl, ix, iy;
5267 rc = mdb_midl_need(&env->me_pghead, ovpages);
5270 if (!(mp->mp_flags & P_DIRTY)) {
5271 /* This page is no longer spilled */
5278 /* Remove from dirty list */
5279 dl = txn->mt_u.dirty_list;
5281 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5287 mdb_cassert(mc, x > 1);
5289 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5290 txn->mt_flags |= MDB_TXN_ERROR;
5291 return MDB_CORRUPTED;
5294 if (!(env->me_flags & MDB_WRITEMAP))
5295 mdb_dpage_free(env, mp);
5297 /* Insert in me_pghead */
5298 mop = env->me_pghead;
5299 j = mop[0] + ovpages;
5300 for (i = mop[0]; i && mop[i] < pg; i--)
5306 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5310 mc->mc_db->md_overflow_pages -= ovpages;
5314 /** Return the data associated with a given node.
5315 * @param[in] txn The transaction for this operation.
5316 * @param[in] leaf The node being read.
5317 * @param[out] data Updated to point to the node's data.
5318 * @return 0 on success, non-zero on failure.
5321 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5323 MDB_page *omp; /* overflow page */
5327 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5328 data->mv_size = NODEDSZ(leaf);
5329 data->mv_data = NODEDATA(leaf);
5333 /* Read overflow data.
5335 data->mv_size = NODEDSZ(leaf);
5336 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5337 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5338 DPRINTF(("read overflow page %"Z"u failed", pgno));
5341 data->mv_data = METADATA(omp);
5347 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5348 MDB_val *key, MDB_val *data)
5355 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5357 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
5360 if (txn->mt_flags & MDB_TXN_ERROR)
5363 mdb_cursor_init(&mc, txn, dbi, &mx);
5364 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5367 /** Find a sibling for a page.
5368 * Replaces the page at the top of the cursor's stack with the
5369 * specified sibling, if one exists.
5370 * @param[in] mc The cursor for this operation.
5371 * @param[in] move_right Non-zero if the right sibling is requested,
5372 * otherwise the left sibling.
5373 * @return 0 on success, non-zero on failure.
5376 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5382 if (mc->mc_snum < 2) {
5383 return MDB_NOTFOUND; /* root has no siblings */
5387 DPRINTF(("parent page is page %"Z"u, index %u",
5388 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5390 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5391 : (mc->mc_ki[mc->mc_top] == 0)) {
5392 DPRINTF(("no more keys left, moving to %s sibling",
5393 move_right ? "right" : "left"));
5394 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5395 /* undo cursor_pop before returning */
5402 mc->mc_ki[mc->mc_top]++;
5404 mc->mc_ki[mc->mc_top]--;
5405 DPRINTF(("just moving to %s index key %u",
5406 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5408 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5410 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5411 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5412 /* mc will be inconsistent if caller does mc_snum++ as above */
5413 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5417 mdb_cursor_push(mc, mp);
5419 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5424 /** Move the cursor to the next data item. */
5426 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5432 if (mc->mc_flags & C_EOF) {
5433 return MDB_NOTFOUND;
5436 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5438 mp = mc->mc_pg[mc->mc_top];
5440 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5441 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5442 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5443 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5444 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5445 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5446 if (rc == MDB_SUCCESS)
5447 MDB_GET_KEY(leaf, key);
5452 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5453 if (op == MDB_NEXT_DUP)
5454 return MDB_NOTFOUND;
5458 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5459 mdb_dbg_pgno(mp), (void *) mc));
5460 if (mc->mc_flags & C_DEL)
5463 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5464 DPUTS("=====> move to next sibling page");
5465 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5466 mc->mc_flags |= C_EOF;
5469 mp = mc->mc_pg[mc->mc_top];
5470 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5472 mc->mc_ki[mc->mc_top]++;
5475 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5476 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5479 key->mv_size = mc->mc_db->md_pad;
5480 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5484 mdb_cassert(mc, IS_LEAF(mp));
5485 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5487 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5488 mdb_xcursor_init1(mc, leaf);
5491 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5494 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5495 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5496 if (rc != MDB_SUCCESS)
5501 MDB_GET_KEY(leaf, key);
5505 /** Move the cursor to the previous data item. */
5507 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5513 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5515 mp = mc->mc_pg[mc->mc_top];
5517 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5518 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5519 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5520 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5521 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5522 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5523 if (rc == MDB_SUCCESS) {
5524 MDB_GET_KEY(leaf, key);
5525 mc->mc_flags &= ~C_EOF;
5531 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5532 if (op == MDB_PREV_DUP)
5533 return MDB_NOTFOUND;
5537 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5538 mdb_dbg_pgno(mp), (void *) mc));
5540 if (mc->mc_ki[mc->mc_top] == 0) {
5541 DPUTS("=====> move to prev sibling page");
5542 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5545 mp = mc->mc_pg[mc->mc_top];
5546 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5547 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5549 mc->mc_ki[mc->mc_top]--;
5551 mc->mc_flags &= ~C_EOF;
5553 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5554 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5557 key->mv_size = mc->mc_db->md_pad;
5558 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5562 mdb_cassert(mc, IS_LEAF(mp));
5563 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5565 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5566 mdb_xcursor_init1(mc, leaf);
5569 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5572 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5573 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5574 if (rc != MDB_SUCCESS)
5579 MDB_GET_KEY(leaf, key);
5583 /** Set the cursor on a specific data item. */
5585 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5586 MDB_cursor_op op, int *exactp)
5590 MDB_node *leaf = NULL;
5593 if (key->mv_size == 0)
5594 return MDB_BAD_VALSIZE;
5597 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5599 /* See if we're already on the right page */
5600 if (mc->mc_flags & C_INITIALIZED) {
5603 mp = mc->mc_pg[mc->mc_top];
5605 mc->mc_ki[mc->mc_top] = 0;
5606 return MDB_NOTFOUND;
5608 if (mp->mp_flags & P_LEAF2) {
5609 nodekey.mv_size = mc->mc_db->md_pad;
5610 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5612 leaf = NODEPTR(mp, 0);
5613 MDB_GET_KEY2(leaf, nodekey);
5615 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5617 /* Probably happens rarely, but first node on the page
5618 * was the one we wanted.
5620 mc->mc_ki[mc->mc_top] = 0;
5627 unsigned int nkeys = NUMKEYS(mp);
5629 if (mp->mp_flags & P_LEAF2) {
5630 nodekey.mv_data = LEAF2KEY(mp,
5631 nkeys-1, nodekey.mv_size);
5633 leaf = NODEPTR(mp, nkeys-1);
5634 MDB_GET_KEY2(leaf, nodekey);
5636 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5638 /* last node was the one we wanted */
5639 mc->mc_ki[mc->mc_top] = nkeys-1;
5645 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5646 /* This is definitely the right page, skip search_page */
5647 if (mp->mp_flags & P_LEAF2) {
5648 nodekey.mv_data = LEAF2KEY(mp,
5649 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5651 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5652 MDB_GET_KEY2(leaf, nodekey);
5654 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5656 /* current node was the one we wanted */
5666 /* If any parents have right-sibs, search.
5667 * Otherwise, there's nothing further.
5669 for (i=0; i<mc->mc_top; i++)
5671 NUMKEYS(mc->mc_pg[i])-1)
5673 if (i == mc->mc_top) {
5674 /* There are no other pages */
5675 mc->mc_ki[mc->mc_top] = nkeys;
5676 return MDB_NOTFOUND;
5680 /* There are no other pages */
5681 mc->mc_ki[mc->mc_top] = 0;
5682 if (op == MDB_SET_RANGE && !exactp) {
5686 return MDB_NOTFOUND;
5690 rc = mdb_page_search(mc, key, 0);
5691 if (rc != MDB_SUCCESS)
5694 mp = mc->mc_pg[mc->mc_top];
5695 mdb_cassert(mc, IS_LEAF(mp));
5698 leaf = mdb_node_search(mc, key, exactp);
5699 if (exactp != NULL && !*exactp) {
5700 /* MDB_SET specified and not an exact match. */
5701 return MDB_NOTFOUND;
5705 DPUTS("===> inexact leaf not found, goto sibling");
5706 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5707 return rc; /* no entries matched */
5708 mp = mc->mc_pg[mc->mc_top];
5709 mdb_cassert(mc, IS_LEAF(mp));
5710 leaf = NODEPTR(mp, 0);
5714 mc->mc_flags |= C_INITIALIZED;
5715 mc->mc_flags &= ~C_EOF;
5718 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5719 key->mv_size = mc->mc_db->md_pad;
5720 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5725 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5726 mdb_xcursor_init1(mc, leaf);
5729 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5730 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5731 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5734 if (op == MDB_GET_BOTH) {
5740 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5741 if (rc != MDB_SUCCESS)
5744 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5746 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5748 rc = mc->mc_dbx->md_dcmp(data, &d2);
5750 if (op == MDB_GET_BOTH || rc > 0)
5751 return MDB_NOTFOUND;
5758 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5759 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5764 /* The key already matches in all other cases */
5765 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5766 MDB_GET_KEY(leaf, key);
5767 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5772 /** Move the cursor to the first item in the database. */
5774 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5780 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5782 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5783 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5784 if (rc != MDB_SUCCESS)
5787 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5789 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5790 mc->mc_flags |= C_INITIALIZED;
5791 mc->mc_flags &= ~C_EOF;
5793 mc->mc_ki[mc->mc_top] = 0;
5795 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5796 key->mv_size = mc->mc_db->md_pad;
5797 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5802 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5803 mdb_xcursor_init1(mc, leaf);
5804 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5808 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5812 MDB_GET_KEY(leaf, key);
5816 /** Move the cursor to the last item in the database. */
5818 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5824 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5826 if (!(mc->mc_flags & C_EOF)) {
5828 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5829 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5830 if (rc != MDB_SUCCESS)
5833 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5836 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5837 mc->mc_flags |= C_INITIALIZED|C_EOF;
5838 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5840 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5841 key->mv_size = mc->mc_db->md_pad;
5842 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5847 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5848 mdb_xcursor_init1(mc, leaf);
5849 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5853 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5858 MDB_GET_KEY(leaf, key);
5863 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5868 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5873 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5877 case MDB_GET_CURRENT:
5878 if (!(mc->mc_flags & C_INITIALIZED)) {
5881 MDB_page *mp = mc->mc_pg[mc->mc_top];
5882 int nkeys = NUMKEYS(mp);
5883 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5884 mc->mc_ki[mc->mc_top] = nkeys;
5890 key->mv_size = mc->mc_db->md_pad;
5891 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5893 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5894 MDB_GET_KEY(leaf, key);
5896 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5897 if (mc->mc_flags & C_DEL)
5898 mdb_xcursor_init1(mc, leaf);
5899 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5901 rc = mdb_node_read(mc->mc_txn, leaf, data);
5908 case MDB_GET_BOTH_RANGE:
5913 if (mc->mc_xcursor == NULL) {
5914 rc = MDB_INCOMPATIBLE;
5924 rc = mdb_cursor_set(mc, key, data, op,
5925 op == MDB_SET_RANGE ? NULL : &exact);
5928 case MDB_GET_MULTIPLE:
5929 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5933 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5934 rc = MDB_INCOMPATIBLE;
5938 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5939 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5942 case MDB_NEXT_MULTIPLE:
5947 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5948 rc = MDB_INCOMPATIBLE;
5951 if (!(mc->mc_flags & C_INITIALIZED))
5952 rc = mdb_cursor_first(mc, key, data);
5954 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5955 if (rc == MDB_SUCCESS) {
5956 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5959 mx = &mc->mc_xcursor->mx_cursor;
5960 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5962 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5963 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5971 case MDB_NEXT_NODUP:
5972 if (!(mc->mc_flags & C_INITIALIZED))
5973 rc = mdb_cursor_first(mc, key, data);
5975 rc = mdb_cursor_next(mc, key, data, op);
5979 case MDB_PREV_NODUP:
5980 if (!(mc->mc_flags & C_INITIALIZED)) {
5981 rc = mdb_cursor_last(mc, key, data);
5984 mc->mc_flags |= C_INITIALIZED;
5985 mc->mc_ki[mc->mc_top]++;
5987 rc = mdb_cursor_prev(mc, key, data, op);
5990 rc = mdb_cursor_first(mc, key, data);
5993 mfunc = mdb_cursor_first;
5995 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5999 if (mc->mc_xcursor == NULL) {
6000 rc = MDB_INCOMPATIBLE;
6004 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6005 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6006 MDB_GET_KEY(leaf, key);
6007 rc = mdb_node_read(mc->mc_txn, leaf, data);
6011 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6015 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
6018 rc = mdb_cursor_last(mc, key, data);
6021 mfunc = mdb_cursor_last;
6024 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
6029 if (mc->mc_flags & C_DEL)
6030 mc->mc_flags ^= C_DEL;
6035 /** Touch all the pages in the cursor stack. Set mc_top.
6036 * Makes sure all the pages are writable, before attempting a write operation.
6037 * @param[in] mc The cursor to operate on.
6040 mdb_cursor_touch(MDB_cursor *mc)
6042 int rc = MDB_SUCCESS;
6044 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
6047 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6049 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
6050 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
6053 *mc->mc_dbflag |= DB_DIRTY;
6058 rc = mdb_page_touch(mc);
6059 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
6060 mc->mc_top = mc->mc_snum-1;
6065 /** Do not spill pages to disk if txn is getting full, may fail instead */
6066 #define MDB_NOSPILL 0x8000
6069 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6072 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
6074 MDB_node *leaf = NULL;
6077 MDB_val xdata, *rdata, dkey, olddata;
6079 int do_sub = 0, insert_key, insert_data;
6080 unsigned int mcount = 0, dcount = 0, nospill;
6083 unsigned int nflags;
6086 if (mc == NULL || key == NULL)
6089 env = mc->mc_txn->mt_env;
6091 /* Check this first so counter will always be zero on any
6094 if (flags & MDB_MULTIPLE) {
6095 dcount = data[1].mv_size;
6096 data[1].mv_size = 0;
6097 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
6098 return MDB_INCOMPATIBLE;
6101 nospill = flags & MDB_NOSPILL;
6102 flags &= ~MDB_NOSPILL;
6104 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6105 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6107 if (key->mv_size-1 >= ENV_MAXKEY(env))
6108 return MDB_BAD_VALSIZE;
6110 #if SIZE_MAX > MAXDATASIZE
6111 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
6112 return MDB_BAD_VALSIZE;
6114 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
6115 return MDB_BAD_VALSIZE;
6118 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
6119 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
6123 if (flags == MDB_CURRENT) {
6124 if (!(mc->mc_flags & C_INITIALIZED))
6127 } else if (mc->mc_db->md_root == P_INVALID) {
6128 /* new database, cursor has nothing to point to */
6131 mc->mc_flags &= ~C_INITIALIZED;
6136 if (flags & MDB_APPEND) {
6138 rc = mdb_cursor_last(mc, &k2, &d2);
6140 rc = mc->mc_dbx->md_cmp(key, &k2);
6143 mc->mc_ki[mc->mc_top]++;
6145 /* new key is <= last key */
6150 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6152 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6153 DPRINTF(("duplicate key [%s]", DKEY(key)));
6155 return MDB_KEYEXIST;
6157 if (rc && rc != MDB_NOTFOUND)
6161 if (mc->mc_flags & C_DEL)
6162 mc->mc_flags ^= C_DEL;
6164 /* Cursor is positioned, check for room in the dirty list */
6166 if (flags & MDB_MULTIPLE) {
6168 xdata.mv_size = data->mv_size * dcount;
6172 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6176 if (rc == MDB_NO_ROOT) {
6178 /* new database, write a root leaf page */
6179 DPUTS("allocating new root leaf page");
6180 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6183 mdb_cursor_push(mc, np);
6184 mc->mc_db->md_root = np->mp_pgno;
6185 mc->mc_db->md_depth++;
6186 *mc->mc_dbflag |= DB_DIRTY;
6187 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6189 np->mp_flags |= P_LEAF2;
6190 mc->mc_flags |= C_INITIALIZED;
6192 /* make sure all cursor pages are writable */
6193 rc2 = mdb_cursor_touch(mc);
6198 insert_key = insert_data = rc;
6200 /* The key does not exist */
6201 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6202 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6203 LEAFSIZE(key, data) > env->me_nodemax)
6205 /* Too big for a node, insert in sub-DB. Set up an empty
6206 * "old sub-page" for prep_subDB to expand to a full page.
6208 fp_flags = P_LEAF|P_DIRTY;
6210 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6211 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6212 olddata.mv_size = PAGEHDRSZ;
6216 /* there's only a key anyway, so this is a no-op */
6217 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6219 unsigned int ksize = mc->mc_db->md_pad;
6220 if (key->mv_size != ksize)
6221 return MDB_BAD_VALSIZE;
6222 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6223 memcpy(ptr, key->mv_data, ksize);
6225 /* if overwriting slot 0 of leaf, need to
6226 * update branch key if there is a parent page
6228 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6229 unsigned short top = mc->mc_top;
6231 /* slot 0 is always an empty key, find real slot */
6232 while (mc->mc_top && !mc->mc_ki[mc->mc_top])
6234 if (mc->mc_ki[mc->mc_top])
6235 rc2 = mdb_update_key(mc, key);
6246 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6247 olddata.mv_size = NODEDSZ(leaf);
6248 olddata.mv_data = NODEDATA(leaf);
6251 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6252 /* Prepare (sub-)page/sub-DB to accept the new item,
6253 * if needed. fp: old sub-page or a header faking
6254 * it. mp: new (sub-)page. offset: growth in page
6255 * size. xdata: node data with new page or DB.
6257 unsigned i, offset = 0;
6258 mp = fp = xdata.mv_data = env->me_pbuf;
6259 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6261 /* Was a single item before, must convert now */
6262 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6263 /* Just overwrite the current item */
6264 if (flags == MDB_CURRENT)
6267 #if UINT_MAX < SIZE_MAX
6268 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6269 mc->mc_dbx->md_dcmp = mdb_cmp_clong;
6271 /* does data match? */
6272 if (!mc->mc_dbx->md_dcmp(data, &olddata)) {
6273 if (flags & MDB_NODUPDATA)
6274 return MDB_KEYEXIST;
6279 /* Back up original data item */
6280 dkey.mv_size = olddata.mv_size;
6281 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6283 /* Make sub-page header for the dup items, with dummy body */
6284 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6285 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6286 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6287 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6288 fp->mp_flags |= P_LEAF2;
6289 fp->mp_pad = data->mv_size;
6290 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6292 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6293 (dkey.mv_size & 1) + (data->mv_size & 1);
6295 fp->mp_upper = xdata.mv_size - PAGEBASE;
6296 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6297 } else if (leaf->mn_flags & F_SUBDATA) {
6298 /* Data is on sub-DB, just store it */
6299 flags |= F_DUPDATA|F_SUBDATA;
6302 /* Data is on sub-page */
6303 fp = olddata.mv_data;
6306 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6307 offset = EVEN(NODESIZE + sizeof(indx_t) +
6311 offset = fp->mp_pad;
6312 if (SIZELEFT(fp) < offset) {
6313 offset *= 4; /* space for 4 more */
6316 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6318 fp->mp_flags |= P_DIRTY;
6319 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6320 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6324 xdata.mv_size = olddata.mv_size + offset;
6327 fp_flags = fp->mp_flags;
6328 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6329 /* Too big for a sub-page, convert to sub-DB */
6330 fp_flags &= ~P_SUBP;
6332 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6333 fp_flags |= P_LEAF2;
6334 dummy.md_pad = fp->mp_pad;
6335 dummy.md_flags = MDB_DUPFIXED;
6336 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6337 dummy.md_flags |= MDB_INTEGERKEY;
6343 dummy.md_branch_pages = 0;
6344 dummy.md_leaf_pages = 1;
6345 dummy.md_overflow_pages = 0;
6346 dummy.md_entries = NUMKEYS(fp);
6347 xdata.mv_size = sizeof(MDB_db);
6348 xdata.mv_data = &dummy;
6349 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6351 offset = env->me_psize - olddata.mv_size;
6352 flags |= F_DUPDATA|F_SUBDATA;
6353 dummy.md_root = mp->mp_pgno;
6356 mp->mp_flags = fp_flags | P_DIRTY;
6357 mp->mp_pad = fp->mp_pad;
6358 mp->mp_lower = fp->mp_lower;
6359 mp->mp_upper = fp->mp_upper + offset;
6360 if (fp_flags & P_LEAF2) {
6361 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6363 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6364 olddata.mv_size - fp->mp_upper - PAGEBASE);
6365 for (i=0; i<NUMKEYS(fp); i++)
6366 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6374 mdb_node_del(mc, 0);
6378 /* overflow page overwrites need special handling */
6379 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6382 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6384 memcpy(&pg, olddata.mv_data, sizeof(pg));
6385 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6387 ovpages = omp->mp_pages;
6389 /* Is the ov page large enough? */
6390 if (ovpages >= dpages) {
6391 if (!(omp->mp_flags & P_DIRTY) &&
6392 (level || (env->me_flags & MDB_WRITEMAP)))
6394 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6397 level = 0; /* dirty in this txn or clean */
6400 if (omp->mp_flags & P_DIRTY) {
6401 /* yes, overwrite it. Note in this case we don't
6402 * bother to try shrinking the page if the new data
6403 * is smaller than the overflow threshold.
6406 /* It is writable only in a parent txn */
6407 size_t sz = (size_t) env->me_psize * ovpages, off;
6408 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6414 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6415 mdb_cassert(mc, rc2 == 0);
6416 if (!(flags & MDB_RESERVE)) {
6417 /* Copy end of page, adjusting alignment so
6418 * compiler may copy words instead of bytes.
6420 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6421 memcpy((size_t *)((char *)np + off),
6422 (size_t *)((char *)omp + off), sz - off);
6425 memcpy(np, omp, sz); /* Copy beginning of page */
6428 SETDSZ(leaf, data->mv_size);
6429 if (F_ISSET(flags, MDB_RESERVE))
6430 data->mv_data = METADATA(omp);
6432 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6436 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6438 } else if (data->mv_size == olddata.mv_size) {
6439 /* same size, just replace it. Note that we could
6440 * also reuse this node if the new data is smaller,
6441 * but instead we opt to shrink the node in that case.
6443 if (F_ISSET(flags, MDB_RESERVE))
6444 data->mv_data = olddata.mv_data;
6445 else if (!(mc->mc_flags & C_SUB))
6446 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6448 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6453 mdb_node_del(mc, 0);
6459 nflags = flags & NODE_ADD_FLAGS;
6460 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6461 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6462 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6463 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6465 nflags |= MDB_SPLIT_REPLACE;
6466 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6468 /* There is room already in this leaf page. */
6469 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6470 if (rc == 0 && insert_key) {
6471 /* Adjust other cursors pointing to mp */
6472 MDB_cursor *m2, *m3;
6473 MDB_dbi dbi = mc->mc_dbi;
6474 unsigned i = mc->mc_top;
6475 MDB_page *mp = mc->mc_pg[i];
6477 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6478 if (mc->mc_flags & C_SUB)
6479 m3 = &m2->mc_xcursor->mx_cursor;
6482 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6483 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6490 if (rc == MDB_SUCCESS) {
6491 /* Now store the actual data in the child DB. Note that we're
6492 * storing the user data in the keys field, so there are strict
6493 * size limits on dupdata. The actual data fields of the child
6494 * DB are all zero size.
6502 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6503 if (flags & MDB_CURRENT) {
6504 xflags = MDB_CURRENT|MDB_NOSPILL;
6506 mdb_xcursor_init1(mc, leaf);
6507 xflags = (flags & MDB_NODUPDATA) ?
6508 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6510 /* converted, write the original data first */
6512 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6516 /* Adjust other cursors pointing to mp */
6518 unsigned i = mc->mc_top;
6519 MDB_page *mp = mc->mc_pg[i];
6521 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6522 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6523 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6524 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6525 mdb_xcursor_init1(m2, leaf);
6529 /* we've done our job */
6532 ecount = mc->mc_xcursor->mx_db.md_entries;
6533 if (flags & MDB_APPENDDUP)
6534 xflags |= MDB_APPEND;
6535 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6536 if (flags & F_SUBDATA) {
6537 void *db = NODEDATA(leaf);
6538 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6540 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6542 /* Increment count unless we just replaced an existing item. */
6544 mc->mc_db->md_entries++;
6546 /* Invalidate txn if we created an empty sub-DB */
6549 /* If we succeeded and the key didn't exist before,
6550 * make sure the cursor is marked valid.
6552 mc->mc_flags |= C_INITIALIZED;
6554 if (flags & MDB_MULTIPLE) {
6557 /* let caller know how many succeeded, if any */
6558 data[1].mv_size = mcount;
6559 if (mcount < dcount) {
6560 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6561 insert_key = insert_data = 0;
6568 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6571 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6576 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6582 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6583 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6585 if (!(mc->mc_flags & C_INITIALIZED))
6588 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6589 return MDB_NOTFOUND;
6591 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6594 rc = mdb_cursor_touch(mc);
6598 mp = mc->mc_pg[mc->mc_top];
6601 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6603 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6604 if (flags & MDB_NODUPDATA) {
6605 /* mdb_cursor_del0() will subtract the final entry */
6606 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6608 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6609 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6611 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6614 /* If sub-DB still has entries, we're done */
6615 if (mc->mc_xcursor->mx_db.md_entries) {
6616 if (leaf->mn_flags & F_SUBDATA) {
6617 /* update subDB info */
6618 void *db = NODEDATA(leaf);
6619 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6622 /* shrink fake page */
6623 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6624 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6625 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6626 /* fix other sub-DB cursors pointed at this fake page */
6627 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6628 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6629 if (m2->mc_pg[mc->mc_top] == mp &&
6630 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6631 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6634 mc->mc_db->md_entries--;
6635 mc->mc_flags |= C_DEL;
6638 /* otherwise fall thru and delete the sub-DB */
6641 if (leaf->mn_flags & F_SUBDATA) {
6642 /* add all the child DB's pages to the free list */
6643 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6649 /* add overflow pages to free list */
6650 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6654 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6655 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6656 (rc = mdb_ovpage_free(mc, omp)))
6661 return mdb_cursor_del0(mc);
6664 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6668 /** Allocate and initialize new pages for a database.
6669 * @param[in] mc a cursor on the database being added to.
6670 * @param[in] flags flags defining what type of page is being allocated.
6671 * @param[in] num the number of pages to allocate. This is usually 1,
6672 * unless allocating overflow pages for a large record.
6673 * @param[out] mp Address of a page, or NULL on failure.
6674 * @return 0 on success, non-zero on failure.
6677 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6682 if ((rc = mdb_page_alloc(mc, num, &np)))
6684 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6685 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6686 np->mp_flags = flags | P_DIRTY;
6687 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
6688 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
6691 mc->mc_db->md_branch_pages++;
6692 else if (IS_LEAF(np))
6693 mc->mc_db->md_leaf_pages++;
6694 else if (IS_OVERFLOW(np)) {
6695 mc->mc_db->md_overflow_pages += num;
6703 /** Calculate the size of a leaf node.
6704 * The size depends on the environment's page size; if a data item
6705 * is too large it will be put onto an overflow page and the node
6706 * size will only include the key and not the data. Sizes are always
6707 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6708 * of the #MDB_node headers.
6709 * @param[in] env The environment handle.
6710 * @param[in] key The key for the node.
6711 * @param[in] data The data for the node.
6712 * @return The number of bytes needed to store the node.
6715 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6719 sz = LEAFSIZE(key, data);
6720 if (sz > env->me_nodemax) {
6721 /* put on overflow page */
6722 sz -= data->mv_size - sizeof(pgno_t);
6725 return EVEN(sz + sizeof(indx_t));
6728 /** Calculate the size of a branch node.
6729 * The size should depend on the environment's page size but since
6730 * we currently don't support spilling large keys onto overflow
6731 * pages, it's simply the size of the #MDB_node header plus the
6732 * size of the key. Sizes are always rounded up to an even number
6733 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6734 * @param[in] env The environment handle.
6735 * @param[in] key The key for the node.
6736 * @return The number of bytes needed to store the node.
6739 mdb_branch_size(MDB_env *env, MDB_val *key)
6744 if (sz > env->me_nodemax) {
6745 /* put on overflow page */
6746 /* not implemented */
6747 /* sz -= key->size - sizeof(pgno_t); */
6750 return sz + sizeof(indx_t);
6753 /** Add a node to the page pointed to by the cursor.
6754 * @param[in] mc The cursor for this operation.
6755 * @param[in] indx The index on the page where the new node should be added.
6756 * @param[in] key The key for the new node.
6757 * @param[in] data The data for the new node, if any.
6758 * @param[in] pgno The page number, if adding a branch node.
6759 * @param[in] flags Flags for the node.
6760 * @return 0 on success, non-zero on failure. Possible errors are:
6762 * <li>ENOMEM - failed to allocate overflow pages for the node.
6763 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6764 * should never happen since all callers already calculate the
6765 * page's free space before calling this function.
6769 mdb_node_add(MDB_cursor *mc, indx_t indx,
6770 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6773 size_t node_size = NODESIZE;
6777 MDB_page *mp = mc->mc_pg[mc->mc_top];
6778 MDB_page *ofp = NULL; /* overflow page */
6781 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
6783 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6784 IS_LEAF(mp) ? "leaf" : "branch",
6785 IS_SUBP(mp) ? "sub-" : "",
6786 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
6787 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6790 /* Move higher keys up one slot. */
6791 int ksize = mc->mc_db->md_pad, dif;
6792 char *ptr = LEAF2KEY(mp, indx, ksize);
6793 dif = NUMKEYS(mp) - indx;
6795 memmove(ptr+ksize, ptr, dif*ksize);
6796 /* insert new key */
6797 memcpy(ptr, key->mv_data, ksize);
6799 /* Just using these for counting */
6800 mp->mp_lower += sizeof(indx_t);
6801 mp->mp_upper -= ksize - sizeof(indx_t);
6805 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6807 node_size += key->mv_size;
6809 mdb_cassert(mc, data);
6810 if (F_ISSET(flags, F_BIGDATA)) {
6811 /* Data already on overflow page. */
6812 node_size += sizeof(pgno_t);
6813 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
6814 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6816 /* Put data on overflow page. */
6817 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6818 data->mv_size, node_size+data->mv_size));
6819 node_size = EVEN(node_size + sizeof(pgno_t));
6820 if ((ssize_t)node_size > room)
6822 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6824 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6828 node_size += data->mv_size;
6831 node_size = EVEN(node_size);
6832 if ((ssize_t)node_size > room)
6836 /* Move higher pointers up one slot. */
6837 for (i = NUMKEYS(mp); i > indx; i--)
6838 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6840 /* Adjust free space offsets. */
6841 ofs = mp->mp_upper - node_size;
6842 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
6843 mp->mp_ptrs[indx] = ofs;
6845 mp->mp_lower += sizeof(indx_t);
6847 /* Write the node data. */
6848 node = NODEPTR(mp, indx);
6849 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6850 node->mn_flags = flags;
6852 SETDSZ(node,data->mv_size);
6857 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6860 mdb_cassert(mc, key);
6862 if (F_ISSET(flags, F_BIGDATA))
6863 memcpy(node->mn_data + key->mv_size, data->mv_data,
6865 else if (F_ISSET(flags, MDB_RESERVE))
6866 data->mv_data = node->mn_data + key->mv_size;
6868 memcpy(node->mn_data + key->mv_size, data->mv_data,
6871 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6873 if (F_ISSET(flags, MDB_RESERVE))
6874 data->mv_data = METADATA(ofp);
6876 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6883 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6884 mdb_dbg_pgno(mp), NUMKEYS(mp)));
6885 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6886 DPRINTF(("node size = %"Z"u", node_size));
6887 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6888 return MDB_PAGE_FULL;
6891 /** Delete the specified node from a page.
6892 * @param[in] mc Cursor pointing to the node to delete.
6893 * @param[in] ksize The size of a node. Only used if the page is
6894 * part of a #MDB_DUPFIXED database.
6897 mdb_node_del(MDB_cursor *mc, int ksize)
6899 MDB_page *mp = mc->mc_pg[mc->mc_top];
6900 indx_t indx = mc->mc_ki[mc->mc_top];
6902 indx_t i, j, numkeys, ptr;
6906 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6907 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
6908 numkeys = NUMKEYS(mp);
6909 mdb_cassert(mc, indx < numkeys);
6912 int x = numkeys - 1 - indx;
6913 base = LEAF2KEY(mp, indx, ksize);
6915 memmove(base, base + ksize, x * ksize);
6916 mp->mp_lower -= sizeof(indx_t);
6917 mp->mp_upper += ksize - sizeof(indx_t);
6921 node = NODEPTR(mp, indx);
6922 sz = NODESIZE + node->mn_ksize;
6924 if (F_ISSET(node->mn_flags, F_BIGDATA))
6925 sz += sizeof(pgno_t);
6927 sz += NODEDSZ(node);
6931 ptr = mp->mp_ptrs[indx];
6932 for (i = j = 0; i < numkeys; i++) {
6934 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6935 if (mp->mp_ptrs[i] < ptr)
6936 mp->mp_ptrs[j] += sz;
6941 base = (char *)mp + mp->mp_upper + PAGEBASE;
6942 memmove(base + sz, base, ptr - mp->mp_upper);
6944 mp->mp_lower -= sizeof(indx_t);
6948 /** Compact the main page after deleting a node on a subpage.
6949 * @param[in] mp The main page to operate on.
6950 * @param[in] indx The index of the subpage on the main page.
6953 mdb_node_shrink(MDB_page *mp, indx_t indx)
6959 indx_t i, numkeys, ptr;
6961 node = NODEPTR(mp, indx);
6962 sp = (MDB_page *)NODEDATA(node);
6963 delta = SIZELEFT(sp);
6964 xp = (MDB_page *)((char *)sp + delta);
6966 /* shift subpage upward */
6968 nsize = NUMKEYS(sp) * sp->mp_pad;
6970 return; /* do not make the node uneven-sized */
6971 memmove(METADATA(xp), METADATA(sp), nsize);
6974 numkeys = NUMKEYS(sp);
6975 for (i=numkeys-1; i>=0; i--)
6976 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6978 xp->mp_upper = sp->mp_lower;
6979 xp->mp_lower = sp->mp_lower;
6980 xp->mp_flags = sp->mp_flags;
6981 xp->mp_pad = sp->mp_pad;
6982 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6984 nsize = NODEDSZ(node) - delta;
6985 SETDSZ(node, nsize);
6987 /* shift lower nodes upward */
6988 ptr = mp->mp_ptrs[indx];
6989 numkeys = NUMKEYS(mp);
6990 for (i = 0; i < numkeys; i++) {
6991 if (mp->mp_ptrs[i] <= ptr)
6992 mp->mp_ptrs[i] += delta;
6995 base = (char *)mp + mp->mp_upper + PAGEBASE;
6996 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6997 mp->mp_upper += delta;
7000 /** Initial setup of a sorted-dups cursor.
7001 * Sorted duplicates are implemented as a sub-database for the given key.
7002 * The duplicate data items are actually keys of the sub-database.
7003 * Operations on the duplicate data items are performed using a sub-cursor
7004 * initialized when the sub-database is first accessed. This function does
7005 * the preliminary setup of the sub-cursor, filling in the fields that
7006 * depend only on the parent DB.
7007 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7010 mdb_xcursor_init0(MDB_cursor *mc)
7012 MDB_xcursor *mx = mc->mc_xcursor;
7014 mx->mx_cursor.mc_xcursor = NULL;
7015 mx->mx_cursor.mc_txn = mc->mc_txn;
7016 mx->mx_cursor.mc_db = &mx->mx_db;
7017 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
7018 mx->mx_cursor.mc_dbi = mc->mc_dbi;
7019 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
7020 mx->mx_cursor.mc_snum = 0;
7021 mx->mx_cursor.mc_top = 0;
7022 mx->mx_cursor.mc_flags = C_SUB;
7023 mx->mx_dbx.md_name.mv_size = 0;
7024 mx->mx_dbx.md_name.mv_data = NULL;
7025 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
7026 mx->mx_dbx.md_dcmp = NULL;
7027 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
7030 /** Final setup of a sorted-dups cursor.
7031 * Sets up the fields that depend on the data from the main cursor.
7032 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7033 * @param[in] node The data containing the #MDB_db record for the
7034 * sorted-dup database.
7037 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
7039 MDB_xcursor *mx = mc->mc_xcursor;
7041 if (node->mn_flags & F_SUBDATA) {
7042 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
7043 mx->mx_cursor.mc_pg[0] = 0;
7044 mx->mx_cursor.mc_snum = 0;
7045 mx->mx_cursor.mc_top = 0;
7046 mx->mx_cursor.mc_flags = C_SUB;
7048 MDB_page *fp = NODEDATA(node);
7049 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
7050 mx->mx_db.md_flags = 0;
7051 mx->mx_db.md_depth = 1;
7052 mx->mx_db.md_branch_pages = 0;
7053 mx->mx_db.md_leaf_pages = 1;
7054 mx->mx_db.md_overflow_pages = 0;
7055 mx->mx_db.md_entries = NUMKEYS(fp);
7056 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
7057 mx->mx_cursor.mc_snum = 1;
7058 mx->mx_cursor.mc_top = 0;
7059 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
7060 mx->mx_cursor.mc_pg[0] = fp;
7061 mx->mx_cursor.mc_ki[0] = 0;
7062 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7063 mx->mx_db.md_flags = MDB_DUPFIXED;
7064 mx->mx_db.md_pad = fp->mp_pad;
7065 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7066 mx->mx_db.md_flags |= MDB_INTEGERKEY;
7069 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7070 mx->mx_db.md_root));
7071 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
7072 #if UINT_MAX < SIZE_MAX
7073 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
7074 mx->mx_dbx.md_cmp = mdb_cmp_clong;
7078 /** Initialize a cursor for a given transaction and database. */
7080 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
7083 mc->mc_backup = NULL;
7086 mc->mc_db = &txn->mt_dbs[dbi];
7087 mc->mc_dbx = &txn->mt_dbxs[dbi];
7088 mc->mc_dbflag = &txn->mt_dbflags[dbi];
7093 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
7094 mdb_tassert(txn, mx != NULL);
7095 mc->mc_xcursor = mx;
7096 mdb_xcursor_init0(mc);
7098 mc->mc_xcursor = NULL;
7100 if (*mc->mc_dbflag & DB_STALE) {
7101 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
7106 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
7109 size_t size = sizeof(MDB_cursor);
7111 if (!ret || !TXN_DBI_EXIST(txn, dbi))
7114 if (txn->mt_flags & MDB_TXN_ERROR)
7117 /* Allow read access to the freelist */
7118 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7121 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
7122 size += sizeof(MDB_xcursor);
7124 if ((mc = malloc(size)) != NULL) {
7125 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
7126 if (txn->mt_cursors) {
7127 mc->mc_next = txn->mt_cursors[dbi];
7128 txn->mt_cursors[dbi] = mc;
7129 mc->mc_flags |= C_UNTRACK;
7141 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
7143 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi))
7146 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
7149 if (txn->mt_flags & MDB_TXN_ERROR)
7152 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
7156 /* Return the count of duplicate data items for the current key */
7158 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7162 if (mc == NULL || countp == NULL)
7165 if (mc->mc_xcursor == NULL)
7166 return MDB_INCOMPATIBLE;
7168 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
7171 if (!(mc->mc_flags & C_INITIALIZED))
7174 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
7175 return MDB_NOTFOUND;
7177 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7178 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7181 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7184 *countp = mc->mc_xcursor->mx_db.md_entries;
7190 mdb_cursor_close(MDB_cursor *mc)
7192 if (mc && !mc->mc_backup) {
7193 /* remove from txn, if tracked */
7194 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7195 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7196 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7198 *prev = mc->mc_next;
7205 mdb_cursor_txn(MDB_cursor *mc)
7207 if (!mc) return NULL;
7212 mdb_cursor_dbi(MDB_cursor *mc)
7217 /** Replace the key for a branch node with a new key.
7218 * @param[in] mc Cursor pointing to the node to operate on.
7219 * @param[in] key The new key to use.
7220 * @return 0 on success, non-zero on failure.
7223 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7229 int delta, ksize, oksize;
7230 indx_t ptr, i, numkeys, indx;
7233 indx = mc->mc_ki[mc->mc_top];
7234 mp = mc->mc_pg[mc->mc_top];
7235 node = NODEPTR(mp, indx);
7236 ptr = mp->mp_ptrs[indx];
7240 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7241 k2.mv_data = NODEKEY(node);
7242 k2.mv_size = node->mn_ksize;
7243 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7245 mdb_dkey(&k2, kbuf2),
7251 /* Sizes must be 2-byte aligned. */
7252 ksize = EVEN(key->mv_size);
7253 oksize = EVEN(node->mn_ksize);
7254 delta = ksize - oksize;
7256 /* Shift node contents if EVEN(key length) changed. */
7258 if (delta > 0 && SIZELEFT(mp) < delta) {
7260 /* not enough space left, do a delete and split */
7261 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7262 pgno = NODEPGNO(node);
7263 mdb_node_del(mc, 0);
7264 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7267 numkeys = NUMKEYS(mp);
7268 for (i = 0; i < numkeys; i++) {
7269 if (mp->mp_ptrs[i] <= ptr)
7270 mp->mp_ptrs[i] -= delta;
7273 base = (char *)mp + mp->mp_upper + PAGEBASE;
7274 len = ptr - mp->mp_upper + NODESIZE;
7275 memmove(base - delta, base, len);
7276 mp->mp_upper -= delta;
7278 node = NODEPTR(mp, indx);
7281 /* But even if no shift was needed, update ksize */
7282 if (node->mn_ksize != key->mv_size)
7283 node->mn_ksize = key->mv_size;
7286 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7292 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7294 /** Move a node from csrc to cdst.
7297 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
7304 unsigned short flags;
7308 /* Mark src and dst as dirty. */
7309 if ((rc = mdb_page_touch(csrc)) ||
7310 (rc = mdb_page_touch(cdst)))
7313 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7314 key.mv_size = csrc->mc_db->md_pad;
7315 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7317 data.mv_data = NULL;
7321 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7322 mdb_cassert(csrc, !((size_t)srcnode & 1));
7323 srcpg = NODEPGNO(srcnode);
7324 flags = srcnode->mn_flags;
7325 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7326 unsigned int snum = csrc->mc_snum;
7328 /* must find the lowest key below src */
7329 rc = mdb_page_search_lowest(csrc);
7332 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7333 key.mv_size = csrc->mc_db->md_pad;
7334 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7336 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7337 key.mv_size = NODEKSZ(s2);
7338 key.mv_data = NODEKEY(s2);
7340 csrc->mc_snum = snum--;
7341 csrc->mc_top = snum;
7343 key.mv_size = NODEKSZ(srcnode);
7344 key.mv_data = NODEKEY(srcnode);
7346 data.mv_size = NODEDSZ(srcnode);
7347 data.mv_data = NODEDATA(srcnode);
7349 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7350 unsigned int snum = cdst->mc_snum;
7353 /* must find the lowest key below dst */
7354 mdb_cursor_copy(cdst, &mn);
7355 rc = mdb_page_search_lowest(&mn);
7358 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7359 bkey.mv_size = mn.mc_db->md_pad;
7360 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7362 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7363 bkey.mv_size = NODEKSZ(s2);
7364 bkey.mv_data = NODEKEY(s2);
7366 mn.mc_snum = snum--;
7369 rc = mdb_update_key(&mn, &bkey);
7374 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7375 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7376 csrc->mc_ki[csrc->mc_top],
7378 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7379 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7381 /* Add the node to the destination page.
7383 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7384 if (rc != MDB_SUCCESS)
7387 /* Delete the node from the source page.
7389 mdb_node_del(csrc, key.mv_size);
7392 /* Adjust other cursors pointing to mp */
7393 MDB_cursor *m2, *m3;
7394 MDB_dbi dbi = csrc->mc_dbi;
7395 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
7397 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7398 if (csrc->mc_flags & C_SUB)
7399 m3 = &m2->mc_xcursor->mx_cursor;
7402 if (m3 == csrc) continue;
7403 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
7404 csrc->mc_ki[csrc->mc_top]) {
7405 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7406 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7411 /* Update the parent separators.
7413 if (csrc->mc_ki[csrc->mc_top] == 0) {
7414 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7415 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7416 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7418 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7419 key.mv_size = NODEKSZ(srcnode);
7420 key.mv_data = NODEKEY(srcnode);
7422 DPRINTF(("update separator for source page %"Z"u to [%s]",
7423 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7424 mdb_cursor_copy(csrc, &mn);
7427 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7430 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7432 indx_t ix = csrc->mc_ki[csrc->mc_top];
7433 nullkey.mv_size = 0;
7434 csrc->mc_ki[csrc->mc_top] = 0;
7435 rc = mdb_update_key(csrc, &nullkey);
7436 csrc->mc_ki[csrc->mc_top] = ix;
7437 mdb_cassert(csrc, rc == MDB_SUCCESS);
7441 if (cdst->mc_ki[cdst->mc_top] == 0) {
7442 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7443 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7444 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7446 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7447 key.mv_size = NODEKSZ(srcnode);
7448 key.mv_data = NODEKEY(srcnode);
7450 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7451 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7452 mdb_cursor_copy(cdst, &mn);
7455 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7458 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7460 indx_t ix = cdst->mc_ki[cdst->mc_top];
7461 nullkey.mv_size = 0;
7462 cdst->mc_ki[cdst->mc_top] = 0;
7463 rc = mdb_update_key(cdst, &nullkey);
7464 cdst->mc_ki[cdst->mc_top] = ix;
7465 mdb_cassert(csrc, rc == MDB_SUCCESS);
7472 /** Merge one page into another.
7473 * The nodes from the page pointed to by \b csrc will
7474 * be copied to the page pointed to by \b cdst and then
7475 * the \b csrc page will be freed.
7476 * @param[in] csrc Cursor pointing to the source page.
7477 * @param[in] cdst Cursor pointing to the destination page.
7478 * @return 0 on success, non-zero on failure.
7481 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7483 MDB_page *psrc, *pdst;
7490 psrc = csrc->mc_pg[csrc->mc_top];
7491 pdst = cdst->mc_pg[cdst->mc_top];
7493 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7495 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7496 mdb_cassert(csrc, cdst->mc_snum > 1);
7498 /* Mark dst as dirty. */
7499 if ((rc = mdb_page_touch(cdst)))
7502 /* Move all nodes from src to dst.
7504 j = nkeys = NUMKEYS(pdst);
7505 if (IS_LEAF2(psrc)) {
7506 key.mv_size = csrc->mc_db->md_pad;
7507 key.mv_data = METADATA(psrc);
7508 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7509 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7510 if (rc != MDB_SUCCESS)
7512 key.mv_data = (char *)key.mv_data + key.mv_size;
7515 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7516 srcnode = NODEPTR(psrc, i);
7517 if (i == 0 && IS_BRANCH(psrc)) {
7520 mdb_cursor_copy(csrc, &mn);
7521 /* must find the lowest key below src */
7522 rc = mdb_page_search_lowest(&mn);
7525 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7526 key.mv_size = mn.mc_db->md_pad;
7527 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7529 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7530 key.mv_size = NODEKSZ(s2);
7531 key.mv_data = NODEKEY(s2);
7534 key.mv_size = srcnode->mn_ksize;
7535 key.mv_data = NODEKEY(srcnode);
7538 data.mv_size = NODEDSZ(srcnode);
7539 data.mv_data = NODEDATA(srcnode);
7540 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7541 if (rc != MDB_SUCCESS)
7546 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7547 pdst->mp_pgno, NUMKEYS(pdst),
7548 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7550 /* Unlink the src page from parent and add to free list.
7553 mdb_node_del(csrc, 0);
7554 if (csrc->mc_ki[csrc->mc_top] == 0) {
7556 rc = mdb_update_key(csrc, &key);
7564 psrc = csrc->mc_pg[csrc->mc_top];
7565 /* If not operating on FreeDB, allow this page to be reused
7566 * in this txn. Otherwise just add to free list.
7568 rc = mdb_page_loose(csrc, psrc);
7572 csrc->mc_db->md_leaf_pages--;
7574 csrc->mc_db->md_branch_pages--;
7576 /* Adjust other cursors pointing to mp */
7577 MDB_cursor *m2, *m3;
7578 MDB_dbi dbi = csrc->mc_dbi;
7580 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7581 if (csrc->mc_flags & C_SUB)
7582 m3 = &m2->mc_xcursor->mx_cursor;
7585 if (m3 == csrc) continue;
7586 if (m3->mc_snum < csrc->mc_snum) continue;
7587 if (m3->mc_pg[csrc->mc_top] == psrc) {
7588 m3->mc_pg[csrc->mc_top] = pdst;
7589 m3->mc_ki[csrc->mc_top] += nkeys;
7594 unsigned int snum = cdst->mc_snum;
7595 uint16_t depth = cdst->mc_db->md_depth;
7596 mdb_cursor_pop(cdst);
7597 rc = mdb_rebalance(cdst);
7598 /* Did the tree shrink? */
7599 if (depth > cdst->mc_db->md_depth)
7601 cdst->mc_snum = snum;
7602 cdst->mc_top = snum-1;
7607 /** Copy the contents of a cursor.
7608 * @param[in] csrc The cursor to copy from.
7609 * @param[out] cdst The cursor to copy to.
7612 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7616 cdst->mc_txn = csrc->mc_txn;
7617 cdst->mc_dbi = csrc->mc_dbi;
7618 cdst->mc_db = csrc->mc_db;
7619 cdst->mc_dbx = csrc->mc_dbx;
7620 cdst->mc_snum = csrc->mc_snum;
7621 cdst->mc_top = csrc->mc_top;
7622 cdst->mc_flags = csrc->mc_flags;
7624 for (i=0; i<csrc->mc_snum; i++) {
7625 cdst->mc_pg[i] = csrc->mc_pg[i];
7626 cdst->mc_ki[i] = csrc->mc_ki[i];
7630 /** Rebalance the tree after a delete operation.
7631 * @param[in] mc Cursor pointing to the page where rebalancing
7633 * @return 0 on success, non-zero on failure.
7636 mdb_rebalance(MDB_cursor *mc)
7640 unsigned int ptop, minkeys;
7644 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7645 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7646 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7647 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7648 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7650 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7651 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7652 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7653 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7657 if (mc->mc_snum < 2) {
7658 MDB_page *mp = mc->mc_pg[0];
7660 DPUTS("Can't rebalance a subpage, ignoring");
7663 if (NUMKEYS(mp) == 0) {
7664 DPUTS("tree is completely empty");
7665 mc->mc_db->md_root = P_INVALID;
7666 mc->mc_db->md_depth = 0;
7667 mc->mc_db->md_leaf_pages = 0;
7668 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7671 /* Adjust cursors pointing to mp */
7674 mc->mc_flags &= ~C_INITIALIZED;
7676 MDB_cursor *m2, *m3;
7677 MDB_dbi dbi = mc->mc_dbi;
7679 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7680 if (mc->mc_flags & C_SUB)
7681 m3 = &m2->mc_xcursor->mx_cursor;
7684 if (m3->mc_snum < mc->mc_snum) continue;
7685 if (m3->mc_pg[0] == mp) {
7688 m3->mc_flags &= ~C_INITIALIZED;
7692 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7694 DPUTS("collapsing root page!");
7695 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7698 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7699 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7702 mc->mc_db->md_depth--;
7703 mc->mc_db->md_branch_pages--;
7704 mc->mc_ki[0] = mc->mc_ki[1];
7705 for (i = 1; i<mc->mc_db->md_depth; i++) {
7706 mc->mc_pg[i] = mc->mc_pg[i+1];
7707 mc->mc_ki[i] = mc->mc_ki[i+1];
7710 /* Adjust other cursors pointing to mp */
7711 MDB_cursor *m2, *m3;
7712 MDB_dbi dbi = mc->mc_dbi;
7714 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7715 if (mc->mc_flags & C_SUB)
7716 m3 = &m2->mc_xcursor->mx_cursor;
7719 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7720 if (m3->mc_pg[0] == mp) {
7723 for (i=0; i<m3->mc_snum; i++) {
7724 m3->mc_pg[i] = m3->mc_pg[i+1];
7725 m3->mc_ki[i] = m3->mc_ki[i+1];
7731 DPUTS("root page doesn't need rebalancing");
7735 /* The parent (branch page) must have at least 2 pointers,
7736 * otherwise the tree is invalid.
7738 ptop = mc->mc_top-1;
7739 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
7741 /* Leaf page fill factor is below the threshold.
7742 * Try to move keys from left or right neighbor, or
7743 * merge with a neighbor page.
7748 mdb_cursor_copy(mc, &mn);
7749 mn.mc_xcursor = NULL;
7751 oldki = mc->mc_ki[mc->mc_top];
7752 if (mc->mc_ki[ptop] == 0) {
7753 /* We're the leftmost leaf in our parent.
7755 DPUTS("reading right neighbor");
7757 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7758 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7761 mn.mc_ki[mn.mc_top] = 0;
7762 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7764 /* There is at least one neighbor to the left.
7766 DPUTS("reading left neighbor");
7768 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7769 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7772 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7773 mc->mc_ki[mc->mc_top] = 0;
7776 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7777 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7778 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7780 /* If the neighbor page is above threshold and has enough keys,
7781 * move one key from it. Otherwise we should try to merge them.
7782 * (A branch page must never have less than 2 keys.)
7784 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7785 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
7786 rc = mdb_node_move(&mn, mc);
7787 if (mc->mc_ki[ptop]) {
7791 if (mc->mc_ki[ptop] == 0) {
7792 rc = mdb_page_merge(&mn, mc);
7794 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
7795 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7796 rc = mdb_page_merge(mc, &mn);
7797 mdb_cursor_copy(&mn, mc);
7799 mc->mc_flags &= ~C_EOF;
7801 mc->mc_ki[mc->mc_top] = oldki;
7805 /** Complete a delete operation started by #mdb_cursor_del(). */
7807 mdb_cursor_del0(MDB_cursor *mc)
7814 ki = mc->mc_ki[mc->mc_top];
7815 mdb_node_del(mc, mc->mc_db->md_pad);
7816 mc->mc_db->md_entries--;
7817 rc = mdb_rebalance(mc);
7819 if (rc == MDB_SUCCESS) {
7820 MDB_cursor *m2, *m3;
7821 MDB_dbi dbi = mc->mc_dbi;
7823 mp = mc->mc_pg[mc->mc_top];
7824 nkeys = NUMKEYS(mp);
7826 /* if mc points past last node in page, find next sibling */
7827 if (mc->mc_ki[mc->mc_top] >= nkeys) {
7828 rc = mdb_cursor_sibling(mc, 1);
7829 if (rc == MDB_NOTFOUND) {
7830 mc->mc_flags |= C_EOF;
7835 /* Adjust other cursors pointing to mp */
7836 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
7837 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
7838 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7840 if (m3 == mc || m3->mc_snum < mc->mc_snum)
7842 if (m3->mc_pg[mc->mc_top] == mp) {
7843 if (m3->mc_ki[mc->mc_top] >= ki) {
7844 m3->mc_flags |= C_DEL;
7845 if (m3->mc_ki[mc->mc_top] > ki)
7846 m3->mc_ki[mc->mc_top]--;
7847 else if (mc->mc_db->md_flags & MDB_DUPSORT)
7848 m3->mc_xcursor->mx_cursor.mc_flags |= C_EOF;
7850 if (m3->mc_ki[mc->mc_top] >= nkeys) {
7851 rc = mdb_cursor_sibling(m3, 1);
7852 if (rc == MDB_NOTFOUND) {
7853 m3->mc_flags |= C_EOF;
7859 mc->mc_flags |= C_DEL;
7863 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7868 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7869 MDB_val *key, MDB_val *data)
7871 if (!key || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
7874 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7875 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7877 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7878 /* must ignore any data */
7882 return mdb_del0(txn, dbi, key, data, 0);
7886 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
7887 MDB_val *key, MDB_val *data, unsigned flags)
7892 MDB_val rdata, *xdata;
7896 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7898 mdb_cursor_init(&mc, txn, dbi, &mx);
7907 flags |= MDB_NODUPDATA;
7909 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7911 /* let mdb_page_split know about this cursor if needed:
7912 * delete will trigger a rebalance; if it needs to move
7913 * a node from one page to another, it will have to
7914 * update the parent's separator key(s). If the new sepkey
7915 * is larger than the current one, the parent page may
7916 * run out of space, triggering a split. We need this
7917 * cursor to be consistent until the end of the rebalance.
7919 mc.mc_flags |= C_UNTRACK;
7920 mc.mc_next = txn->mt_cursors[dbi];
7921 txn->mt_cursors[dbi] = &mc;
7922 rc = mdb_cursor_del(&mc, flags);
7923 txn->mt_cursors[dbi] = mc.mc_next;
7928 /** Split a page and insert a new node.
7929 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7930 * The cursor will be updated to point to the actual page and index where
7931 * the node got inserted after the split.
7932 * @param[in] newkey The key for the newly inserted node.
7933 * @param[in] newdata The data for the newly inserted node.
7934 * @param[in] newpgno The page number, if the new node is a branch node.
7935 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7936 * @return 0 on success, non-zero on failure.
7939 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7940 unsigned int nflags)
7943 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7946 int i, j, split_indx, nkeys, pmax;
7947 MDB_env *env = mc->mc_txn->mt_env;
7949 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7950 MDB_page *copy = NULL;
7951 MDB_page *mp, *rp, *pp;
7956 mp = mc->mc_pg[mc->mc_top];
7957 newindx = mc->mc_ki[mc->mc_top];
7958 nkeys = NUMKEYS(mp);
7960 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
7961 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7962 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
7964 /* Create a right sibling. */
7965 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7967 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7969 if (mc->mc_snum < 2) {
7970 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7972 /* shift current top to make room for new parent */
7973 mc->mc_pg[1] = mc->mc_pg[0];
7974 mc->mc_ki[1] = mc->mc_ki[0];
7977 mc->mc_db->md_root = pp->mp_pgno;
7978 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7979 mc->mc_db->md_depth++;
7982 /* Add left (implicit) pointer. */
7983 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7984 /* undo the pre-push */
7985 mc->mc_pg[0] = mc->mc_pg[1];
7986 mc->mc_ki[0] = mc->mc_ki[1];
7987 mc->mc_db->md_root = mp->mp_pgno;
7988 mc->mc_db->md_depth--;
7995 ptop = mc->mc_top-1;
7996 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7999 mc->mc_flags |= C_SPLITTING;
8000 mdb_cursor_copy(mc, &mn);
8001 mn.mc_pg[mn.mc_top] = rp;
8002 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
8004 if (nflags & MDB_APPEND) {
8005 mn.mc_ki[mn.mc_top] = 0;
8007 split_indx = newindx;
8011 split_indx = (nkeys+1) / 2;
8016 unsigned int lsize, rsize, ksize;
8017 /* Move half of the keys to the right sibling */
8018 x = mc->mc_ki[mc->mc_top] - split_indx;
8019 ksize = mc->mc_db->md_pad;
8020 split = LEAF2KEY(mp, split_indx, ksize);
8021 rsize = (nkeys - split_indx) * ksize;
8022 lsize = (nkeys - split_indx) * sizeof(indx_t);
8023 mp->mp_lower -= lsize;
8024 rp->mp_lower += lsize;
8025 mp->mp_upper += rsize - lsize;
8026 rp->mp_upper -= rsize - lsize;
8027 sepkey.mv_size = ksize;
8028 if (newindx == split_indx) {
8029 sepkey.mv_data = newkey->mv_data;
8031 sepkey.mv_data = split;
8034 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
8035 memcpy(rp->mp_ptrs, split, rsize);
8036 sepkey.mv_data = rp->mp_ptrs;
8037 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
8038 memcpy(ins, newkey->mv_data, ksize);
8039 mp->mp_lower += sizeof(indx_t);
8040 mp->mp_upper -= ksize - sizeof(indx_t);
8043 memcpy(rp->mp_ptrs, split, x * ksize);
8044 ins = LEAF2KEY(rp, x, ksize);
8045 memcpy(ins, newkey->mv_data, ksize);
8046 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
8047 rp->mp_lower += sizeof(indx_t);
8048 rp->mp_upper -= ksize - sizeof(indx_t);
8049 mc->mc_ki[mc->mc_top] = x;
8050 mc->mc_pg[mc->mc_top] = rp;
8053 int psize, nsize, k;
8054 /* Maximum free space in an empty page */
8055 pmax = env->me_psize - PAGEHDRSZ;
8057 nsize = mdb_leaf_size(env, newkey, newdata);
8059 nsize = mdb_branch_size(env, newkey);
8060 nsize = EVEN(nsize);
8062 /* grab a page to hold a temporary copy */
8063 copy = mdb_page_malloc(mc->mc_txn, 1);
8068 copy->mp_pgno = mp->mp_pgno;
8069 copy->mp_flags = mp->mp_flags;
8070 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
8071 copy->mp_upper = env->me_psize - PAGEBASE;
8073 /* prepare to insert */
8074 for (i=0, j=0; i<nkeys; i++) {
8076 copy->mp_ptrs[j++] = 0;
8078 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
8081 /* When items are relatively large the split point needs
8082 * to be checked, because being off-by-one will make the
8083 * difference between success or failure in mdb_node_add.
8085 * It's also relevant if a page happens to be laid out
8086 * such that one half of its nodes are all "small" and
8087 * the other half of its nodes are "large." If the new
8088 * item is also "large" and falls on the half with
8089 * "large" nodes, it also may not fit.
8091 * As a final tweak, if the new item goes on the last
8092 * spot on the page (and thus, onto the new page), bias
8093 * the split so the new page is emptier than the old page.
8094 * This yields better packing during sequential inserts.
8096 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
8097 /* Find split point */
8099 if (newindx <= split_indx || newindx >= nkeys) {
8101 k = newindx >= nkeys ? nkeys : split_indx+2;
8106 for (; i!=k; i+=j) {
8111 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8112 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
8114 if (F_ISSET(node->mn_flags, F_BIGDATA))
8115 psize += sizeof(pgno_t);
8117 psize += NODEDSZ(node);
8119 psize = EVEN(psize);
8121 if (psize > pmax || i == k-j) {
8122 split_indx = i + (j<0);
8127 if (split_indx == newindx) {
8128 sepkey.mv_size = newkey->mv_size;
8129 sepkey.mv_data = newkey->mv_data;
8131 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
8132 sepkey.mv_size = node->mn_ksize;
8133 sepkey.mv_data = NODEKEY(node);
8138 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
8140 /* Copy separator key to the parent.
8142 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
8146 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
8151 if (mn.mc_snum == mc->mc_snum) {
8152 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
8153 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
8154 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
8155 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
8160 /* Right page might now have changed parent.
8161 * Check if left page also changed parent.
8163 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8164 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8165 for (i=0; i<ptop; i++) {
8166 mc->mc_pg[i] = mn.mc_pg[i];
8167 mc->mc_ki[i] = mn.mc_ki[i];
8169 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8170 if (mn.mc_ki[ptop]) {
8171 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8173 /* find right page's left sibling */
8174 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8175 mdb_cursor_sibling(mc, 0);
8180 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8183 mc->mc_flags ^= C_SPLITTING;
8184 if (rc != MDB_SUCCESS) {
8187 if (nflags & MDB_APPEND) {
8188 mc->mc_pg[mc->mc_top] = rp;
8189 mc->mc_ki[mc->mc_top] = 0;
8190 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8193 for (i=0; i<mc->mc_top; i++)
8194 mc->mc_ki[i] = mn.mc_ki[i];
8195 } else if (!IS_LEAF2(mp)) {
8197 mc->mc_pg[mc->mc_top] = rp;
8202 rkey.mv_data = newkey->mv_data;
8203 rkey.mv_size = newkey->mv_size;
8209 /* Update index for the new key. */
8210 mc->mc_ki[mc->mc_top] = j;
8212 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8213 rkey.mv_data = NODEKEY(node);
8214 rkey.mv_size = node->mn_ksize;
8216 xdata.mv_data = NODEDATA(node);
8217 xdata.mv_size = NODEDSZ(node);
8220 pgno = NODEPGNO(node);
8221 flags = node->mn_flags;
8224 if (!IS_LEAF(mp) && j == 0) {
8225 /* First branch index doesn't need key data. */
8229 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8235 mc->mc_pg[mc->mc_top] = copy;
8240 } while (i != split_indx);
8242 nkeys = NUMKEYS(copy);
8243 for (i=0; i<nkeys; i++)
8244 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8245 mp->mp_lower = copy->mp_lower;
8246 mp->mp_upper = copy->mp_upper;
8247 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8248 env->me_psize - copy->mp_upper - PAGEBASE);
8250 /* reset back to original page */
8251 if (newindx < split_indx) {
8252 mc->mc_pg[mc->mc_top] = mp;
8253 if (nflags & MDB_RESERVE) {
8254 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
8255 if (!(node->mn_flags & F_BIGDATA))
8256 newdata->mv_data = NODEDATA(node);
8259 mc->mc_pg[mc->mc_top] = rp;
8261 /* Make sure mc_ki is still valid.
8263 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8264 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8265 for (i=0; i<=ptop; i++) {
8266 mc->mc_pg[i] = mn.mc_pg[i];
8267 mc->mc_ki[i] = mn.mc_ki[i];
8274 /* Adjust other cursors pointing to mp */
8275 MDB_cursor *m2, *m3;
8276 MDB_dbi dbi = mc->mc_dbi;
8277 int fixup = NUMKEYS(mp);
8279 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8280 if (mc->mc_flags & C_SUB)
8281 m3 = &m2->mc_xcursor->mx_cursor;
8286 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8288 if (m3->mc_flags & C_SPLITTING)
8293 for (k=m3->mc_top; k>=0; k--) {
8294 m3->mc_ki[k+1] = m3->mc_ki[k];
8295 m3->mc_pg[k+1] = m3->mc_pg[k];
8297 if (m3->mc_ki[0] >= split_indx) {
8302 m3->mc_pg[0] = mc->mc_pg[0];
8306 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8307 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8308 m3->mc_ki[mc->mc_top]++;
8309 if (m3->mc_ki[mc->mc_top] >= fixup) {
8310 m3->mc_pg[mc->mc_top] = rp;
8311 m3->mc_ki[mc->mc_top] -= fixup;
8312 m3->mc_ki[ptop] = mn.mc_ki[ptop];
8314 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8315 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8320 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8323 if (copy) /* tmp page */
8324 mdb_page_free(env, copy);
8326 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8331 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8332 MDB_val *key, MDB_val *data, unsigned int flags)
8337 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8340 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
8343 mdb_cursor_init(&mc, txn, dbi, &mx);
8344 return mdb_cursor_put(&mc, key, data, flags);
8348 #define MDB_WBUF (1024*1024)
8351 /** State needed for a compacting copy. */
8352 typedef struct mdb_copy {
8353 pthread_mutex_t mc_mutex;
8354 pthread_cond_t mc_cond;
8361 pgno_t mc_next_pgno;
8364 volatile int mc_new;
8369 /** Dedicated writer thread for compacting copy. */
8370 static THREAD_RET ESECT
8371 mdb_env_copythr(void *arg)
8375 int toggle = 0, wsize, rc;
8378 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8381 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8384 pthread_mutex_lock(&my->mc_mutex);
8386 pthread_cond_signal(&my->mc_cond);
8389 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8390 if (my->mc_new < 0) {
8395 wsize = my->mc_wlen[toggle];
8396 ptr = my->mc_wbuf[toggle];
8399 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8403 } else if (len > 0) {
8417 /* If there's an overflow page tail, write it too */
8418 if (my->mc_olen[toggle]) {
8419 wsize = my->mc_olen[toggle];
8420 ptr = my->mc_over[toggle];
8421 my->mc_olen[toggle] = 0;
8424 my->mc_wlen[toggle] = 0;
8426 pthread_cond_signal(&my->mc_cond);
8428 pthread_cond_signal(&my->mc_cond);
8429 pthread_mutex_unlock(&my->mc_mutex);
8430 return (THREAD_RET)0;
8434 /** Tell the writer thread there's a buffer ready to write */
8436 mdb_env_cthr_toggle(mdb_copy *my, int st)
8438 int toggle = my->mc_toggle ^ 1;
8439 pthread_mutex_lock(&my->mc_mutex);
8440 if (my->mc_status) {
8441 pthread_mutex_unlock(&my->mc_mutex);
8442 return my->mc_status;
8444 while (my->mc_new == 1)
8445 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8447 my->mc_toggle = toggle;
8448 pthread_cond_signal(&my->mc_cond);
8449 pthread_mutex_unlock(&my->mc_mutex);
8453 /** Depth-first tree traversal for compacting copy. */
8455 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8458 MDB_txn *txn = my->mc_txn;
8460 MDB_page *mo, *mp, *leaf;
8465 /* Empty DB, nothing to do */
8466 if (*pg == P_INVALID)
8473 rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
8476 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8480 /* Make cursor pages writable */
8481 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8485 for (i=0; i<mc.mc_top; i++) {
8486 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8487 mc.mc_pg[i] = (MDB_page *)ptr;
8488 ptr += my->mc_env->me_psize;
8491 /* This is writable space for a leaf page. Usually not needed. */
8492 leaf = (MDB_page *)ptr;
8494 toggle = my->mc_toggle;
8495 while (mc.mc_snum > 0) {
8497 mp = mc.mc_pg[mc.mc_top];
8501 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8502 for (i=0; i<n; i++) {
8503 ni = NODEPTR(mp, i);
8504 if (ni->mn_flags & F_BIGDATA) {
8508 /* Need writable leaf */
8510 mc.mc_pg[mc.mc_top] = leaf;
8511 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8513 ni = NODEPTR(mp, i);
8516 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8517 rc = mdb_page_get(txn, pg, &omp, NULL);
8520 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8521 rc = mdb_env_cthr_toggle(my, 1);
8524 toggle = my->mc_toggle;
8526 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8527 memcpy(mo, omp, my->mc_env->me_psize);
8528 mo->mp_pgno = my->mc_next_pgno;
8529 my->mc_next_pgno += omp->mp_pages;
8530 my->mc_wlen[toggle] += my->mc_env->me_psize;
8531 if (omp->mp_pages > 1) {
8532 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
8533 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
8534 rc = mdb_env_cthr_toggle(my, 1);
8537 toggle = my->mc_toggle;
8539 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
8540 } else if (ni->mn_flags & F_SUBDATA) {
8543 /* Need writable leaf */
8545 mc.mc_pg[mc.mc_top] = leaf;
8546 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8548 ni = NODEPTR(mp, i);
8551 memcpy(&db, NODEDATA(ni), sizeof(db));
8552 my->mc_toggle = toggle;
8553 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
8556 toggle = my->mc_toggle;
8557 memcpy(NODEDATA(ni), &db, sizeof(db));
8562 mc.mc_ki[mc.mc_top]++;
8563 if (mc.mc_ki[mc.mc_top] < n) {
8566 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
8568 rc = mdb_page_get(txn, pg, &mp, NULL);
8573 mc.mc_ki[mc.mc_top] = 0;
8574 if (IS_BRANCH(mp)) {
8575 /* Whenever we advance to a sibling branch page,
8576 * we must proceed all the way down to its first leaf.
8578 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
8581 mc.mc_pg[mc.mc_top] = mp;
8585 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8586 rc = mdb_env_cthr_toggle(my, 1);
8589 toggle = my->mc_toggle;
8591 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8592 mdb_page_copy(mo, mp, my->mc_env->me_psize);
8593 mo->mp_pgno = my->mc_next_pgno++;
8594 my->mc_wlen[toggle] += my->mc_env->me_psize;
8596 /* Update parent if there is one */
8597 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
8598 SETPGNO(ni, mo->mp_pgno);
8599 mdb_cursor_pop(&mc);
8601 /* Otherwise we're done */
8611 /** Copy environment with compaction. */
8613 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
8618 MDB_txn *txn = NULL;
8623 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
8624 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
8625 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
8626 if (my.mc_wbuf[0] == NULL)
8629 pthread_mutex_init(&my.mc_mutex, NULL);
8630 pthread_cond_init(&my.mc_cond, NULL);
8631 #ifdef HAVE_MEMALIGN
8632 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
8633 if (my.mc_wbuf[0] == NULL)
8636 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_os_psize, MDB_WBUF*2);
8641 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
8642 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
8647 my.mc_next_pgno = 2;
8653 THREAD_CREATE(thr, mdb_env_copythr, &my);
8655 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8659 mp = (MDB_page *)my.mc_wbuf[0];
8660 memset(mp, 0, 2*env->me_psize);
8662 mp->mp_flags = P_META;
8663 mm = (MDB_meta *)METADATA(mp);
8664 mdb_env_init_meta0(env, mm);
8665 mm->mm_address = env->me_metas[0]->mm_address;
8667 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
8669 mp->mp_flags = P_META;
8670 *(MDB_meta *)METADATA(mp) = *mm;
8671 mm = (MDB_meta *)METADATA(mp);
8673 /* Count the number of free pages, subtract from lastpg to find
8674 * number of active pages
8677 MDB_ID freecount = 0;
8680 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
8681 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
8682 freecount += *(MDB_ID *)data.mv_data;
8683 freecount += txn->mt_dbs[0].md_branch_pages +
8684 txn->mt_dbs[0].md_leaf_pages +
8685 txn->mt_dbs[0].md_overflow_pages;
8687 /* Set metapage 1 */
8688 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
8689 mm->mm_dbs[1] = txn->mt_dbs[1];
8690 if (mm->mm_last_pg > 1) {
8691 mm->mm_dbs[1].md_root = mm->mm_last_pg;
8694 mm->mm_dbs[1].md_root = P_INVALID;
8697 my.mc_wlen[0] = env->me_psize * 2;
8699 pthread_mutex_lock(&my.mc_mutex);
8701 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8702 pthread_mutex_unlock(&my.mc_mutex);
8703 rc = mdb_env_cwalk(&my, &txn->mt_dbs[1].md_root, 0);
8704 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
8705 rc = mdb_env_cthr_toggle(&my, 1);
8706 mdb_env_cthr_toggle(&my, -1);
8707 pthread_mutex_lock(&my.mc_mutex);
8709 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8710 pthread_mutex_unlock(&my.mc_mutex);
8715 CloseHandle(my.mc_cond);
8716 CloseHandle(my.mc_mutex);
8717 _aligned_free(my.mc_wbuf[0]);
8719 pthread_cond_destroy(&my.mc_cond);
8720 pthread_mutex_destroy(&my.mc_mutex);
8721 free(my.mc_wbuf[0]);
8726 /** Copy environment as-is. */
8728 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
8730 MDB_txn *txn = NULL;
8731 mdb_mutex_t *wmutex = NULL;
8737 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8741 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8744 /* Do the lock/unlock of the reader mutex before starting the
8745 * write txn. Otherwise other read txns could block writers.
8747 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8752 /* We must start the actual read txn after blocking writers */
8753 mdb_txn_reset0(txn, "reset-stage1");
8755 /* Temporarily block writers until we snapshot the meta pages */
8756 wmutex = MDB_MUTEX(env, w);
8757 if (LOCK_MUTEX(rc, env, wmutex))
8760 rc = mdb_txn_renew0(txn);
8762 UNLOCK_MUTEX(wmutex);
8767 wsize = env->me_psize * 2;
8771 DO_WRITE(rc, fd, ptr, w2, len);
8775 } else if (len > 0) {
8781 /* Non-blocking or async handles are not supported */
8787 UNLOCK_MUTEX(wmutex);
8792 w2 = txn->mt_next_pgno * env->me_psize;
8795 if ((rc = mdb_fsize(env->me_fd, &fsize)))
8802 if (wsize > MAX_WRITE)
8806 DO_WRITE(rc, fd, ptr, w2, len);
8810 } else if (len > 0) {
8827 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
8829 if (flags & MDB_CP_COMPACT)
8830 return mdb_env_copyfd1(env, fd);
8832 return mdb_env_copyfd0(env, fd);
8836 mdb_env_copyfd(MDB_env *env, HANDLE fd)
8838 return mdb_env_copyfd2(env, fd, 0);
8842 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
8846 HANDLE newfd = INVALID_HANDLE_VALUE;
8848 if (env->me_flags & MDB_NOSUBDIR) {
8849 lpath = (char *)path;
8852 len += sizeof(DATANAME);
8853 lpath = malloc(len);
8856 sprintf(lpath, "%s" DATANAME, path);
8859 /* The destination path must exist, but the destination file must not.
8860 * We don't want the OS to cache the writes, since the source data is
8861 * already in the OS cache.
8864 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
8865 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
8867 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
8869 if (newfd == INVALID_HANDLE_VALUE) {
8874 if (env->me_psize >= env->me_os_psize) {
8876 /* Set O_DIRECT if the file system supports it */
8877 if ((rc = fcntl(newfd, F_GETFL)) != -1)
8878 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
8880 #ifdef F_NOCACHE /* __APPLE__ */
8881 rc = fcntl(newfd, F_NOCACHE, 1);
8889 rc = mdb_env_copyfd2(env, newfd, flags);
8892 if (!(env->me_flags & MDB_NOSUBDIR))
8894 if (newfd != INVALID_HANDLE_VALUE)
8895 if (close(newfd) < 0 && rc == MDB_SUCCESS)
8902 mdb_env_copy(MDB_env *env, const char *path)
8904 return mdb_env_copy2(env, path, 0);
8908 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
8910 if (flag & (env->me_map ? ~CHANGEABLE : ~(CHANGEABLE|CHANGELESS)))
8913 env->me_flags |= flag;
8915 env->me_flags &= ~flag;
8920 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
8925 *arg = env->me_flags;
8930 mdb_env_set_userctx(MDB_env *env, void *ctx)
8934 env->me_userctx = ctx;
8939 mdb_env_get_userctx(MDB_env *env)
8941 return env ? env->me_userctx : NULL;
8945 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
8950 env->me_assert_func = func;
8956 mdb_env_get_path(MDB_env *env, const char **arg)
8961 *arg = env->me_path;
8966 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
8975 /** Common code for #mdb_stat() and #mdb_env_stat().
8976 * @param[in] env the environment to operate in.
8977 * @param[in] db the #MDB_db record containing the stats to return.
8978 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
8979 * @return 0, this function always succeeds.
8982 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
8984 arg->ms_psize = env->me_psize;
8985 arg->ms_depth = db->md_depth;
8986 arg->ms_branch_pages = db->md_branch_pages;
8987 arg->ms_leaf_pages = db->md_leaf_pages;
8988 arg->ms_overflow_pages = db->md_overflow_pages;
8989 arg->ms_entries = db->md_entries;
8995 mdb_env_stat(MDB_env *env, MDB_stat *arg)
8999 if (env == NULL || arg == NULL)
9002 toggle = mdb_env_pick_meta(env);
9004 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
9008 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
9012 if (env == NULL || arg == NULL)
9015 toggle = mdb_env_pick_meta(env);
9016 arg->me_mapaddr = env->me_metas[toggle]->mm_address;
9017 arg->me_mapsize = env->me_mapsize;
9018 arg->me_maxreaders = env->me_maxreaders;
9020 /* me_numreaders may be zero if this process never used any readers. Use
9021 * the shared numreader count if it exists.
9023 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
9025 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
9026 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
9030 /** Set the default comparison functions for a database.
9031 * Called immediately after a database is opened to set the defaults.
9032 * The user can then override them with #mdb_set_compare() or
9033 * #mdb_set_dupsort().
9034 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
9035 * @param[in] dbi A database handle returned by #mdb_dbi_open()
9038 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
9040 uint16_t f = txn->mt_dbs[dbi].md_flags;
9042 txn->mt_dbxs[dbi].md_cmp =
9043 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
9044 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
9046 txn->mt_dbxs[dbi].md_dcmp =
9047 !(f & MDB_DUPSORT) ? 0 :
9048 ((f & MDB_INTEGERDUP)
9049 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
9050 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
9053 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
9059 int rc, dbflag, exact;
9060 unsigned int unused = 0, seq;
9063 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
9064 mdb_default_cmp(txn, FREE_DBI);
9067 if ((flags & VALID_FLAGS) != flags)
9069 if (txn->mt_flags & MDB_TXN_ERROR)
9075 if (flags & PERSISTENT_FLAGS) {
9076 uint16_t f2 = flags & PERSISTENT_FLAGS;
9077 /* make sure flag changes get committed */
9078 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
9079 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
9080 txn->mt_flags |= MDB_TXN_DIRTY;
9083 mdb_default_cmp(txn, MAIN_DBI);
9087 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
9088 mdb_default_cmp(txn, MAIN_DBI);
9091 /* Is the DB already open? */
9093 for (i=2; i<txn->mt_numdbs; i++) {
9094 if (!txn->mt_dbxs[i].md_name.mv_size) {
9095 /* Remember this free slot */
9096 if (!unused) unused = i;
9099 if (len == txn->mt_dbxs[i].md_name.mv_size &&
9100 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
9106 /* If no free slot and max hit, fail */
9107 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
9108 return MDB_DBS_FULL;
9110 /* Cannot mix named databases with some mainDB flags */
9111 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
9112 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
9114 /* Find the DB info */
9115 dbflag = DB_NEW|DB_VALID;
9118 key.mv_data = (void *)name;
9119 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
9120 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
9121 if (rc == MDB_SUCCESS) {
9122 /* make sure this is actually a DB */
9123 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
9124 if (!(node->mn_flags & F_SUBDATA))
9125 return MDB_INCOMPATIBLE;
9126 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
9127 /* Create if requested */
9128 data.mv_size = sizeof(MDB_db);
9129 data.mv_data = &dummy;
9130 memset(&dummy, 0, sizeof(dummy));
9131 dummy.md_root = P_INVALID;
9132 dummy.md_flags = flags & PERSISTENT_FLAGS;
9133 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
9137 /* OK, got info, add to table */
9138 if (rc == MDB_SUCCESS) {
9139 unsigned int slot = unused ? unused : txn->mt_numdbs;
9140 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
9141 txn->mt_dbxs[slot].md_name.mv_size = len;
9142 txn->mt_dbxs[slot].md_rel = NULL;
9143 txn->mt_dbflags[slot] = dbflag;
9144 /* txn-> and env-> are the same in read txns, use
9145 * tmp variable to avoid undefined assignment
9147 seq = ++txn->mt_env->me_dbiseqs[slot];
9148 txn->mt_dbiseqs[slot] = seq;
9150 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
9152 mdb_default_cmp(txn, slot);
9161 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9163 if (!arg || !TXN_DBI_EXIST(txn, dbi))
9166 if (txn->mt_flags & MDB_TXN_ERROR)
9169 if (txn->mt_dbflags[dbi] & DB_STALE) {
9172 /* Stale, must read the DB's root. cursor_init does it for us. */
9173 mdb_cursor_init(&mc, txn, dbi, &mx);
9175 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9178 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9181 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
9183 ptr = env->me_dbxs[dbi].md_name.mv_data;
9184 /* If there was no name, this was already closed */
9186 env->me_dbxs[dbi].md_name.mv_data = NULL;
9187 env->me_dbxs[dbi].md_name.mv_size = 0;
9188 env->me_dbflags[dbi] = 0;
9189 env->me_dbiseqs[dbi]++;
9194 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9196 /* We could return the flags for the FREE_DBI too but what's the point? */
9197 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9199 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9203 /** Add all the DB's pages to the free list.
9204 * @param[in] mc Cursor on the DB to free.
9205 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9206 * @return 0 on success, non-zero on failure.
9209 mdb_drop0(MDB_cursor *mc, int subs)
9213 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9214 if (rc == MDB_SUCCESS) {
9215 MDB_txn *txn = mc->mc_txn;
9220 /* LEAF2 pages have no nodes, cannot have sub-DBs */
9221 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
9224 mdb_cursor_copy(mc, &mx);
9225 while (mc->mc_snum > 0) {
9226 MDB_page *mp = mc->mc_pg[mc->mc_top];
9227 unsigned n = NUMKEYS(mp);
9229 for (i=0; i<n; i++) {
9230 ni = NODEPTR(mp, i);
9231 if (ni->mn_flags & F_BIGDATA) {
9234 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9235 rc = mdb_page_get(txn, pg, &omp, NULL);
9238 mdb_cassert(mc, IS_OVERFLOW(omp));
9239 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9243 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9244 mdb_xcursor_init1(mc, ni);
9245 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9251 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9253 for (i=0; i<n; i++) {
9255 ni = NODEPTR(mp, i);
9258 mdb_midl_xappend(txn->mt_free_pgs, pg);
9263 mc->mc_ki[mc->mc_top] = i;
9264 rc = mdb_cursor_sibling(mc, 1);
9266 if (rc != MDB_NOTFOUND)
9268 /* no more siblings, go back to beginning
9269 * of previous level.
9273 for (i=1; i<mc->mc_snum; i++) {
9275 mc->mc_pg[i] = mx.mc_pg[i];
9280 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9283 txn->mt_flags |= MDB_TXN_ERROR;
9284 } else if (rc == MDB_NOTFOUND) {
9290 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9292 MDB_cursor *mc, *m2;
9295 if ((unsigned)del > 1 || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9298 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9301 if (dbi > MAIN_DBI && TXN_DBI_CHANGED(txn, dbi))
9304 rc = mdb_cursor_open(txn, dbi, &mc);
9308 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9309 /* Invalidate the dropped DB's cursors */
9310 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9311 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9315 /* Can't delete the main DB */
9316 if (del && dbi > MAIN_DBI) {
9317 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, 0);
9319 txn->mt_dbflags[dbi] = DB_STALE;
9320 mdb_dbi_close(txn->mt_env, dbi);
9322 txn->mt_flags |= MDB_TXN_ERROR;
9325 /* reset the DB record, mark it dirty */
9326 txn->mt_dbflags[dbi] |= DB_DIRTY;
9327 txn->mt_dbs[dbi].md_depth = 0;
9328 txn->mt_dbs[dbi].md_branch_pages = 0;
9329 txn->mt_dbs[dbi].md_leaf_pages = 0;
9330 txn->mt_dbs[dbi].md_overflow_pages = 0;
9331 txn->mt_dbs[dbi].md_entries = 0;
9332 txn->mt_dbs[dbi].md_root = P_INVALID;
9334 txn->mt_flags |= MDB_TXN_DIRTY;
9337 mdb_cursor_close(mc);
9341 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9343 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9346 txn->mt_dbxs[dbi].md_cmp = cmp;
9350 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9352 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9355 txn->mt_dbxs[dbi].md_dcmp = cmp;
9359 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9361 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9364 txn->mt_dbxs[dbi].md_rel = rel;
9368 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9370 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9373 txn->mt_dbxs[dbi].md_relctx = ctx;
9378 mdb_env_get_maxkeysize(MDB_env *env)
9380 return ENV_MAXKEY(env);
9384 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9386 unsigned int i, rdrs;
9389 int rc = 0, first = 1;
9393 if (!env->me_txns) {
9394 return func("(no reader locks)\n", ctx);
9396 rdrs = env->me_txns->mti_numreaders;
9397 mr = env->me_txns->mti_readers;
9398 for (i=0; i<rdrs; i++) {
9400 txnid_t txnid = mr[i].mr_txnid;
9401 sprintf(buf, txnid == (txnid_t)-1 ?
9402 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9403 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9406 rc = func(" pid thread txnid\n", ctx);
9410 rc = func(buf, ctx);
9416 rc = func("(no active readers)\n", ctx);
9421 /** Insert pid into list if not already present.
9422 * return -1 if already present.
9425 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9427 /* binary search of pid in list */
9429 unsigned cursor = 1;
9431 unsigned n = ids[0];
9434 unsigned pivot = n >> 1;
9435 cursor = base + pivot + 1;
9436 val = pid - ids[cursor];
9441 } else if ( val > 0 ) {
9446 /* found, so it's a duplicate */
9455 for (n = ids[0]; n > cursor; n--)
9462 mdb_reader_check(MDB_env *env, int *dead)
9468 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
9471 /** As #mdb_reader_check(). rlocked = <caller locked the reader mutex>. */
9472 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
9474 mdb_mutex_t *rmutex = rlocked ? NULL : MDB_MUTEX(env, r);
9475 unsigned int i, j, rdrs;
9477 MDB_PID_T *pids, pid;
9478 int rc = MDB_SUCCESS, count = 0;
9480 rdrs = env->me_txns->mti_numreaders;
9481 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
9485 mr = env->me_txns->mti_readers;
9486 for (i=0; i<rdrs; i++) {
9488 if (pid && pid != env->me_pid) {
9489 if (mdb_pid_insert(pids, pid) == 0) {
9490 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9491 /* Stale reader found */
9494 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
9495 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
9497 rdrs = 0; /* the above checked all readers */
9499 /* Recheck, a new process may have reused pid */
9500 if (mdb_reader_pid(env, Pidcheck, pid))
9505 if (mr[j].mr_pid == pid) {
9506 DPRINTF(("clear stale reader pid %u txn %"Z"d",
9507 (unsigned) pid, mr[j].mr_txnid));
9512 UNLOCK_MUTEX(rmutex);
9523 #ifdef MDB_ROBUST_SUPPORTED
9524 /** Handle #LOCK_MUTEX0() failure.
9525 * With #MDB_ROBUST, try to repair the lock file if the mutex owner died.
9526 * @param[in] env the environment handle
9527 * @param[in] mutex LOCK_MUTEX0() mutex
9528 * @param[in] rc LOCK_MUTEX0() error (nonzero)
9529 * @return 0 on success with the mutex locked, or an error code on failure.
9531 static int mdb_mutex_failed(MDB_env *env, mdb_mutex_t *mutex, int rc)
9533 int toggle, rlocked, rc2;
9535 enum { WAIT_ABANDONED = EOWNERDEAD };
9538 if (rc == (int) WAIT_ABANDONED) {
9539 /* We own the mutex. Clean up after dead previous owner. */
9541 rlocked = (mutex == MDB_MUTEX(env, r));
9543 /* Keep mti_txnid updated, otherwise next writer can
9544 * overwrite data which latest meta page refers to.
9546 toggle = mdb_env_pick_meta(env);
9547 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
9548 /* env is hosed if the dead thread was ours */
9550 env->me_flags |= MDB_FATAL_ERROR;
9555 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
9556 (rc ? "this process' env is hosed" : "recovering")));
9557 rc2 = mdb_reader_check0(env, rlocked, NULL);
9559 rc2 = pthread_mutex_consistent(mutex);
9560 if (rc || (rc = rc2)) {
9561 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
9562 UNLOCK_MUTEX(mutex);
9568 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
9573 #endif /* MDB_ROBUST_SUPPORTED */