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)
82 #if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
83 /** fdatasync is broken on ext3/ext4fs on older kernels, see
84 * description in #mdb_env_open2 comments
86 #define BROKEN_FDATASYNC
99 #if defined(__sun) || defined(ANDROID)
100 /* Most platforms have posix_memalign, older may only have memalign */
101 #define HAVE_MEMALIGN 1
105 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
106 #include <netinet/in.h>
107 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
110 #if defined(__APPLE__) || defined (BSD)
111 # define MDB_USE_SYSV_SEM 1
112 # define MDB_FDATASYNC fsync
113 #elif defined(ANDROID)
114 # define MDB_FDATASYNC fsync
119 #ifdef MDB_USE_SYSV_SEM
122 #ifdef _SEM_SEMUN_UNDEFINED
125 struct semid_ds *buf;
126 unsigned short *array;
128 #endif /* _SEM_SEMUN_UNDEFINED */
129 #endif /* MDB_USE_SYSV_SEM */
133 #include <valgrind/memcheck.h>
134 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
135 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
136 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
137 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
138 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
140 #define VGMEMP_CREATE(h,r,z)
141 #define VGMEMP_ALLOC(h,a,s)
142 #define VGMEMP_FREE(h,a)
143 #define VGMEMP_DESTROY(h)
144 #define VGMEMP_DEFINED(a,s)
148 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
149 /* Solaris just defines one or the other */
150 # define LITTLE_ENDIAN 1234
151 # define BIG_ENDIAN 4321
152 # ifdef _LITTLE_ENDIAN
153 # define BYTE_ORDER LITTLE_ENDIAN
155 # define BYTE_ORDER BIG_ENDIAN
158 # define BYTE_ORDER __BYTE_ORDER
162 #ifndef LITTLE_ENDIAN
163 #define LITTLE_ENDIAN __LITTLE_ENDIAN
166 #define BIG_ENDIAN __BIG_ENDIAN
169 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
170 #define MISALIGNED_OK 1
176 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
177 # error "Unknown or unsupported endianness (BYTE_ORDER)"
178 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
179 # error "Two's complement, reasonably sized integer types, please"
183 /** Put infrequently used env functions in separate section */
185 # define ESECT __attribute__ ((section("__TEXT,text_env")))
187 # define ESECT __attribute__ ((section("text_env")))
193 /** @defgroup internal LMDB Internals
196 /** @defgroup compat Compatibility Macros
197 * A bunch of macros to minimize the amount of platform-specific ifdefs
198 * needed throughout the rest of the code. When the features this library
199 * needs are similar enough to POSIX to be hidden in a one-or-two line
200 * replacement, this macro approach is used.
204 /** Features under development */
209 #if defined(_WIN32) || (defined(EOWNERDEAD) && !defined(MDB_USE_SYSV_SEM))
210 #define MDB_ROBUST_SUPPORTED 1
213 /** Wrapper around __func__, which is a C99 feature */
214 #if __STDC_VERSION__ >= 199901L
215 # define mdb_func_ __func__
216 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
217 # define mdb_func_ __FUNCTION__
219 /* If a debug message says <mdb_unknown>(), update the #if statements above */
220 # define mdb_func_ "<mdb_unknown>"
224 #define MDB_USE_HASH 1
225 #define MDB_PIDLOCK 0
226 #define THREAD_RET DWORD
227 #define pthread_t HANDLE
228 #define pthread_mutex_t HANDLE
229 #define pthread_cond_t HANDLE
230 typedef HANDLE mdb_mutex_t;
231 #define pthread_key_t DWORD
232 #define pthread_self() GetCurrentThreadId()
233 #define pthread_key_create(x,y) \
234 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
235 #define pthread_key_delete(x) TlsFree(x)
236 #define pthread_getspecific(x) TlsGetValue(x)
237 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
238 #define pthread_mutex_consistent(mutex) 0
239 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
240 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
241 #define pthread_cond_signal(x) SetEvent(*x)
242 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
243 #define THREAD_CREATE(thr,start,arg) thr=CreateThread(NULL,0,start,arg,0,NULL)
244 #define THREAD_FINISH(thr) WaitForSingleObject(thr, INFINITE)
245 #define MDB_MUTEX(env, rw) ((env)->me_##rw##mutex)
246 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
247 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
248 #define getpid() GetCurrentProcessId()
249 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
250 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
251 #define ErrCode() GetLastError()
252 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
253 #define close(fd) (CloseHandle(fd) ? 0 : -1)
254 #define munmap(ptr,len) UnmapViewOfFile(ptr)
255 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
256 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
258 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
262 #define THREAD_RET void *
263 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
264 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
265 #define Z "z" /**< printf format modifier for size_t */
267 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
268 #define MDB_PIDLOCK 1
270 #ifdef MDB_USE_SYSV_SEM
272 typedef struct mdb_mutex {
277 #define MDB_MUTEX(env, rw) (&(env)->me_##rw##mutex)
278 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
279 #define UNLOCK_MUTEX(mutex) do { \
280 struct sembuf sb = { 0, 1, SEM_UNDO }; \
281 sb.sem_num = (mutex)->semnum; \
282 semop((mutex)->semid, &sb, 1); \
286 mdb_sem_wait(mdb_mutex_t *sem)
289 struct sembuf sb = { 0, -1, SEM_UNDO };
290 sb.sem_num = sem->semnum;
291 while ((rc = semop(sem->semid, &sb, 1)) && (rc = errno) == EINTR) ;
296 /** Pointer/HANDLE type of shared mutex/semaphore.
298 typedef pthread_mutex_t mdb_mutex_t;
299 /** Mutex for the reader table (rw = r) or write transaction (rw = w).
301 #define MDB_MUTEX(env, rw) (&(env)->me_txns->mti_##rw##mutex)
302 /** Lock the reader or writer mutex.
303 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
305 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
306 /** Unlock the reader or writer mutex.
308 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
309 #endif /* MDB_USE_SYSV_SEM */
311 /** Get the error code for the last failed system function.
313 #define ErrCode() errno
315 /** An abstraction for a file handle.
316 * On POSIX systems file handles are small integers. On Windows
317 * they're opaque pointers.
321 /** A value for an invalid file handle.
322 * Mainly used to initialize file variables and signify that they are
325 #define INVALID_HANDLE_VALUE (-1)
327 /** Get the size of a memory page for the system.
328 * This is the basic size that the platform's memory manager uses, and is
329 * fundamental to the use of memory-mapped files.
331 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
336 #elif defined(MDB_USE_SYSV_SEM)
339 #define MNAME_LEN (sizeof(pthread_mutex_t))
344 #ifdef MDB_ROBUST_SUPPORTED
345 /** Lock mutex, handle any error, set rc = result.
346 * Return 0 on success, nonzero (not rc) on error.
348 #define LOCK_MUTEX(rc, env, mutex) \
349 (((rc) = LOCK_MUTEX0(mutex)) && \
350 ((rc) = mdb_mutex_failed(env, mutex, rc)))
351 static int mdb_mutex_failed(MDB_env *env, mdb_mutex_t *mutex, int rc);
353 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
354 #define mdb_mutex_failed(env, mutex, rc) (rc)
358 /** A flag for opening a file and requesting synchronous data writes.
359 * This is only used when writing a meta page. It's not strictly needed;
360 * we could just do a normal write and then immediately perform a flush.
361 * But if this flag is available it saves us an extra system call.
363 * @note If O_DSYNC is undefined but exists in /usr/include,
364 * preferably set some compiler flag to get the definition.
365 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
368 # define MDB_DSYNC O_DSYNC
372 /** Function for flushing the data of a file. Define this to fsync
373 * if fdatasync() is not supported.
375 #ifndef MDB_FDATASYNC
376 # define MDB_FDATASYNC fdatasync
380 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
391 /** A page number in the database.
392 * Note that 64 bit page numbers are overkill, since pages themselves
393 * already represent 12-13 bits of addressable memory, and the OS will
394 * always limit applications to a maximum of 63 bits of address space.
396 * @note In the #MDB_node structure, we only store 48 bits of this value,
397 * which thus limits us to only 60 bits of addressable data.
399 typedef MDB_ID pgno_t;
401 /** A transaction ID.
402 * See struct MDB_txn.mt_txnid for details.
404 typedef MDB_ID txnid_t;
406 /** @defgroup debug Debug Macros
410 /** Enable debug output. Needs variable argument macros (a C99 feature).
411 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
412 * read from and written to the database (used for free space management).
418 static int mdb_debug;
419 static txnid_t mdb_debug_start;
421 /** Print a debug message with printf formatting.
422 * Requires double parenthesis around 2 or more args.
424 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
425 # define DPRINTF0(fmt, ...) \
426 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
428 # define DPRINTF(args) ((void) 0)
430 /** Print a debug string.
431 * The string is printed literally, with no format processing.
433 #define DPUTS(arg) DPRINTF(("%s", arg))
434 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
436 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
439 /** @brief The maximum size of a database page.
441 * It is 32k or 64k, since value-PAGEBASE must fit in
442 * #MDB_page.%mp_upper.
444 * LMDB will use database pages < OS pages if needed.
445 * That causes more I/O in write transactions: The OS must
446 * know (read) the whole page before writing a partial page.
448 * Note that we don't currently support Huge pages. On Linux,
449 * regular data files cannot use Huge pages, and in general
450 * Huge pages aren't actually pageable. We rely on the OS
451 * demand-pager to read our data and page it out when memory
452 * pressure from other processes is high. So until OSs have
453 * actual paging support for Huge pages, they're not viable.
455 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
457 /** The minimum number of keys required in a database page.
458 * Setting this to a larger value will place a smaller bound on the
459 * maximum size of a data item. Data items larger than this size will
460 * be pushed into overflow pages instead of being stored directly in
461 * the B-tree node. This value used to default to 4. With a page size
462 * of 4096 bytes that meant that any item larger than 1024 bytes would
463 * go into an overflow page. That also meant that on average 2-3KB of
464 * each overflow page was wasted space. The value cannot be lower than
465 * 2 because then there would no longer be a tree structure. With this
466 * value, items larger than 2KB will go into overflow pages, and on
467 * average only 1KB will be wasted.
469 #define MDB_MINKEYS 2
471 /** A stamp that identifies a file as an LMDB file.
472 * There's nothing special about this value other than that it is easily
473 * recognizable, and it will reflect any byte order mismatches.
475 #define MDB_MAGIC 0xBEEFC0DE
477 /** The version number for a database's datafile format. */
478 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
479 /** The version number for a database's lockfile format. */
480 #define MDB_LOCK_VERSION ((MDB_DEVEL) ? 999 : 1)
482 /** @brief The max size of a key we can write, or 0 for dynamic max.
484 * Define this as 0 to compute the max from the page size. 511
485 * is default for backwards compat: liblmdb <= 0.9.10 can break
486 * when modifying a DB with keys/dupsort data bigger than its max.
487 * #MDB_DEVEL sets the default to 0.
489 * Data items in an #MDB_DUPSORT database are also limited to
490 * this size, since they're actually keys of a sub-DB. Keys and
491 * #MDB_DUPSORT data items must fit on a node in a regular page.
493 #ifndef MDB_MAXKEYSIZE
494 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
497 /** The maximum size of a key we can write to the environment. */
499 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
501 #define ENV_MAXKEY(env) ((env)->me_maxkey)
504 /** @brief The maximum size of a data item.
506 * We only store a 32 bit value for node sizes.
508 #define MAXDATASIZE 0xffffffffUL
511 /** Key size which fits in a #DKBUF.
514 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
517 * This is used for printing a hex dump of a key's contents.
519 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
520 /** Display a key in hex.
522 * Invoke a function to display a key in hex.
524 #define DKEY(x) mdb_dkey(x, kbuf)
530 /** An invalid page number.
531 * Mainly used to denote an empty tree.
533 #define P_INVALID (~(pgno_t)0)
535 /** Test if the flags \b f are set in a flag word \b w. */
536 #define F_ISSET(w, f) (((w) & (f)) == (f))
538 /** Round \b n up to an even number. */
539 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
541 /** Used for offsets within a single page.
542 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
545 typedef uint16_t indx_t;
547 /** Default size of memory map.
548 * This is certainly too small for any actual applications. Apps should always set
549 * the size explicitly using #mdb_env_set_mapsize().
551 #define DEFAULT_MAPSIZE 1048576
553 /** @defgroup readers Reader Lock Table
554 * Readers don't acquire any locks for their data access. Instead, they
555 * simply record their transaction ID in the reader table. The reader
556 * mutex is needed just to find an empty slot in the reader table. The
557 * slot's address is saved in thread-specific data so that subsequent read
558 * transactions started by the same thread need no further locking to proceed.
560 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
562 * No reader table is used if the database is on a read-only filesystem, or
563 * if #MDB_NOLOCK is set.
565 * Since the database uses multi-version concurrency control, readers don't
566 * actually need any locking. This table is used to keep track of which
567 * readers are using data from which old transactions, so that we'll know
568 * when a particular old transaction is no longer in use. Old transactions
569 * that have discarded any data pages can then have those pages reclaimed
570 * for use by a later write transaction.
572 * The lock table is constructed such that reader slots are aligned with the
573 * processor's cache line size. Any slot is only ever used by one thread.
574 * This alignment guarantees that there will be no contention or cache
575 * thrashing as threads update their own slot info, and also eliminates
576 * any need for locking when accessing a slot.
578 * A writer thread will scan every slot in the table to determine the oldest
579 * outstanding reader transaction. Any freed pages older than this will be
580 * reclaimed by the writer. The writer doesn't use any locks when scanning
581 * this table. This means that there's no guarantee that the writer will
582 * see the most up-to-date reader info, but that's not required for correct
583 * operation - all we need is to know the upper bound on the oldest reader,
584 * we don't care at all about the newest reader. So the only consequence of
585 * reading stale information here is that old pages might hang around a
586 * while longer before being reclaimed. That's actually good anyway, because
587 * the longer we delay reclaiming old pages, the more likely it is that a
588 * string of contiguous pages can be found after coalescing old pages from
589 * many old transactions together.
592 /** Number of slots in the reader table.
593 * This value was chosen somewhat arbitrarily. 126 readers plus a
594 * couple mutexes fit exactly into 8KB on my development machine.
595 * Applications should set the table size using #mdb_env_set_maxreaders().
597 #define DEFAULT_READERS 126
599 /** The size of a CPU cache line in bytes. We want our lock structures
600 * aligned to this size to avoid false cache line sharing in the
602 * This value works for most CPUs. For Itanium this should be 128.
608 /** The information we store in a single slot of the reader table.
609 * In addition to a transaction ID, we also record the process and
610 * thread ID that owns a slot, so that we can detect stale information,
611 * e.g. threads or processes that went away without cleaning up.
612 * @note We currently don't check for stale records. We simply re-init
613 * the table when we know that we're the only process opening the
616 typedef struct MDB_rxbody {
617 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
618 * Multiple readers that start at the same time will probably have the
619 * same ID here. Again, it's not important to exclude them from
620 * anything; all we need to know is which version of the DB they
621 * started from so we can avoid overwriting any data used in that
622 * particular version.
624 volatile txnid_t mrb_txnid;
625 /** The process ID of the process owning this reader txn. */
626 volatile MDB_PID_T mrb_pid;
627 /** The thread ID of the thread owning this txn. */
628 volatile MDB_THR_T mrb_tid;
631 /** The actual reader record, with cacheline padding. */
632 typedef struct MDB_reader {
635 /** shorthand for mrb_txnid */
636 #define mr_txnid mru.mrx.mrb_txnid
637 #define mr_pid mru.mrx.mrb_pid
638 #define mr_tid mru.mrx.mrb_tid
639 /** cache line alignment */
640 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
644 /** The header for the reader table.
645 * The table resides in a memory-mapped file. (This is a different file
646 * than is used for the main database.)
648 * For POSIX the actual mutexes reside in the shared memory of this
649 * mapped file. On Windows, mutexes are named objects allocated by the
650 * kernel; we store the mutex names in this mapped file so that other
651 * processes can grab them. This same approach is also used on
652 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
653 * process-shared POSIX mutexes. For these cases where a named object
654 * is used, the object name is derived from a 64 bit FNV hash of the
655 * environment pathname. As such, naming collisions are extremely
656 * unlikely. If a collision occurs, the results are unpredictable.
658 typedef struct MDB_txbody {
659 /** Stamp identifying this as an LMDB file. It must be set
662 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
665 char mtb_rmname[MNAME_LEN];
666 #elif defined(MDB_USE_SYSV_SEM)
669 /** Mutex protecting access to this table.
670 * This is the #MDB_MUTEX(env,r) reader table lock.
672 pthread_mutex_t mtb_rmutex;
674 /** The ID of the last transaction committed to the database.
675 * This is recorded here only for convenience; the value can always
676 * be determined by reading the main database meta pages.
678 volatile txnid_t mtb_txnid;
679 /** The number of slots that have been used in the reader table.
680 * This always records the maximum count, it is not decremented
681 * when readers release their slots.
683 volatile unsigned mtb_numreaders;
686 /** The actual reader table definition. */
687 typedef struct MDB_txninfo {
690 #define mti_magic mt1.mtb.mtb_magic
691 #define mti_format mt1.mtb.mtb_format
692 #define mti_rmutex mt1.mtb.mtb_rmutex
693 #define mti_rmname mt1.mtb.mtb_rmname
694 #define mti_txnid mt1.mtb.mtb_txnid
695 #define mti_numreaders mt1.mtb.mtb_numreaders
696 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
698 #ifdef MDB_USE_SYSV_SEM
699 #define mti_semid mt1.mtb.mtb_semid
703 char mt2_wmname[MNAME_LEN];
704 #define mti_wmname mt2.mt2_wmname
706 pthread_mutex_t mt2_wmutex;
707 #define mti_wmutex mt2.mt2_wmutex
709 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
712 MDB_reader mti_readers[1];
715 /** Lockfile format signature: version, features and field layout */
716 #define MDB_LOCK_FORMAT \
718 ((MDB_LOCK_VERSION) \
719 /* Flags which describe functionality */ \
720 + (((MNAME_LEN) == 0) << 18) /* MDB_USE_SYSV_SEM */ \
721 + (((MDB_PIDLOCK) != 0) << 16)))
724 /** Common header for all page types.
725 * Overflow records occupy a number of contiguous pages with no
726 * headers on any page after the first.
728 typedef struct MDB_page {
729 #define mp_pgno mp_p.p_pgno
730 #define mp_next mp_p.p_next
732 pgno_t p_pgno; /**< page number */
733 struct MDB_page *p_next; /**< for in-memory list of freed pages */
736 /** @defgroup mdb_page Page Flags
738 * Flags for the page headers.
741 #define P_BRANCH 0x01 /**< branch page */
742 #define P_LEAF 0x02 /**< leaf page */
743 #define P_OVERFLOW 0x04 /**< overflow page */
744 #define P_META 0x08 /**< meta page */
745 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
746 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
747 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
748 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
749 #define P_KEEP 0x8000 /**< leave this page alone during spill */
751 uint16_t mp_flags; /**< @ref mdb_page */
752 #define mp_lower mp_pb.pb.pb_lower
753 #define mp_upper mp_pb.pb.pb_upper
754 #define mp_pages mp_pb.pb_pages
757 indx_t pb_lower; /**< lower bound of free space */
758 indx_t pb_upper; /**< upper bound of free space */
760 uint32_t pb_pages; /**< number of overflow pages */
762 indx_t mp_ptrs[1]; /**< dynamic size */
765 /** Size of the page header, excluding dynamic data at the end */
766 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
768 /** Address of first usable data byte in a page, after the header */
769 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
771 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
772 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
774 /** Number of nodes on a page */
775 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
777 /** The amount of space remaining in the page */
778 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
780 /** The percentage of space used in the page, in tenths of a percent. */
781 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
782 ((env)->me_psize - PAGEHDRSZ))
783 /** The minimum page fill factor, in tenths of a percent.
784 * Pages emptier than this are candidates for merging.
786 #define FILL_THRESHOLD 250
788 /** Test if a page is a leaf page */
789 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
790 /** Test if a page is a LEAF2 page */
791 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
792 /** Test if a page is a branch page */
793 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
794 /** Test if a page is an overflow page */
795 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
796 /** Test if a page is a sub page */
797 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
799 /** The number of overflow pages needed to store the given size. */
800 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
802 /** Link in #MDB_txn.%mt_loose_pgs list */
803 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
805 /** Header for a single key/data pair within a page.
806 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
807 * We guarantee 2-byte alignment for 'MDB_node's.
809 typedef struct MDB_node {
810 /** lo and hi are used for data size on leaf nodes and for
811 * child pgno on branch nodes. On 64 bit platforms, flags
812 * is also used for pgno. (Branch nodes have no flags).
813 * They are in host byte order in case that lets some
814 * accesses be optimized into a 32-bit word access.
816 #if BYTE_ORDER == LITTLE_ENDIAN
817 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
819 unsigned short mn_hi, mn_lo;
821 /** @defgroup mdb_node Node Flags
823 * Flags for node headers.
826 #define F_BIGDATA 0x01 /**< data put on overflow page */
827 #define F_SUBDATA 0x02 /**< data is a sub-database */
828 #define F_DUPDATA 0x04 /**< data has duplicates */
830 /** valid flags for #mdb_node_add() */
831 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
834 unsigned short mn_flags; /**< @ref mdb_node */
835 unsigned short mn_ksize; /**< key size */
836 char mn_data[1]; /**< key and data are appended here */
839 /** Size of the node header, excluding dynamic data at the end */
840 #define NODESIZE offsetof(MDB_node, mn_data)
842 /** Bit position of top word in page number, for shifting mn_flags */
843 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
845 /** Size of a node in a branch page with a given key.
846 * This is just the node header plus the key, there is no data.
848 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
850 /** Size of a node in a leaf page with a given key and data.
851 * This is node header plus key plus data size.
853 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
855 /** Address of node \b i in page \b p */
856 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
858 /** Address of the key for the node */
859 #define NODEKEY(node) (void *)((node)->mn_data)
861 /** Address of the data for a node */
862 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
864 /** Get the page number pointed to by a branch node */
865 #define NODEPGNO(node) \
866 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
867 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
868 /** Set the page number in a branch node */
869 #define SETPGNO(node,pgno) do { \
870 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
871 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
873 /** Get the size of the data in a leaf node */
874 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
875 /** Set the size of the data for a leaf node */
876 #define SETDSZ(node,size) do { \
877 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
878 /** The size of a key in a node */
879 #define NODEKSZ(node) ((node)->mn_ksize)
881 /** Copy a page number from src to dst */
883 #define COPY_PGNO(dst,src) dst = src
885 #if SIZE_MAX > 4294967295UL
886 #define COPY_PGNO(dst,src) do { \
887 unsigned short *s, *d; \
888 s = (unsigned short *)&(src); \
889 d = (unsigned short *)&(dst); \
896 #define COPY_PGNO(dst,src) do { \
897 unsigned short *s, *d; \
898 s = (unsigned short *)&(src); \
899 d = (unsigned short *)&(dst); \
905 /** The address of a key in a LEAF2 page.
906 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
907 * There are no node headers, keys are stored contiguously.
909 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
911 /** Set the \b node's key into \b keyptr, if requested. */
912 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
913 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
915 /** Set the \b node's key into \b key. */
916 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
918 /** Information about a single database in the environment. */
919 typedef struct MDB_db {
920 uint32_t md_pad; /**< also ksize for LEAF2 pages */
921 uint16_t md_flags; /**< @ref mdb_dbi_open */
922 uint16_t md_depth; /**< depth of this tree */
923 pgno_t md_branch_pages; /**< number of internal pages */
924 pgno_t md_leaf_pages; /**< number of leaf pages */
925 pgno_t md_overflow_pages; /**< number of overflow pages */
926 size_t md_entries; /**< number of data items */
927 pgno_t md_root; /**< the root page of this tree */
930 /** mdb_dbi_open flags */
931 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
932 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
933 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
934 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
936 /** Handle for the DB used to track free pages. */
938 /** Handle for the default DB. */
941 /** Meta page content.
942 * A meta page is the start point for accessing a database snapshot.
943 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
945 typedef struct MDB_meta {
946 /** Stamp identifying this as an LMDB file. It must be set
949 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
951 void *mm_address; /**< address for fixed mapping */
952 size_t mm_mapsize; /**< size of mmap region */
953 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
954 /** The size of pages used in this DB */
955 #define mm_psize mm_dbs[0].md_pad
956 /** Any persistent environment flags. @ref mdb_env */
957 #define mm_flags mm_dbs[0].md_flags
958 pgno_t mm_last_pg; /**< last used page in file */
959 volatile txnid_t mm_txnid; /**< txnid that committed this page */
962 /** Buffer for a stack-allocated meta page.
963 * The members define size and alignment, and silence type
964 * aliasing warnings. They are not used directly; that could
965 * mean incorrectly using several union members in parallel.
967 typedef union MDB_metabuf {
970 char mm_pad[PAGEHDRSZ];
975 /** Auxiliary DB info.
976 * The information here is mostly static/read-only. There is
977 * only a single copy of this record in the environment.
979 typedef struct MDB_dbx {
980 MDB_val md_name; /**< name of the database */
981 MDB_cmp_func *md_cmp; /**< function for comparing keys */
982 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
983 MDB_rel_func *md_rel; /**< user relocate function */
984 void *md_relctx; /**< user-provided context for md_rel */
987 /** A database transaction.
988 * Every operation requires a transaction handle.
991 MDB_txn *mt_parent; /**< parent of a nested txn */
992 MDB_txn *mt_child; /**< nested txn under this txn */
993 pgno_t mt_next_pgno; /**< next unallocated page */
994 /** The ID of this transaction. IDs are integers incrementing from 1.
995 * Only committed write transactions increment the ID. If a transaction
996 * aborts, the ID may be re-used by the next writer.
999 MDB_env *mt_env; /**< the DB environment */
1000 /** The list of pages that became unused during this transaction.
1002 MDB_IDL mt_free_pgs;
1003 /** The list of loose pages that became unused and may be reused
1004 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1006 MDB_page *mt_loose_pgs;
1007 /* #Number of loose pages (#mt_loose_pgs) */
1009 /** The sorted list of dirty pages we temporarily wrote to disk
1010 * because the dirty list was full. page numbers in here are
1011 * shifted left by 1, deleted slots have the LSB set.
1013 MDB_IDL mt_spill_pgs;
1015 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1016 MDB_ID2L dirty_list;
1017 /** For read txns: This thread/txn's reader table slot, or NULL. */
1020 /** Array of records for each DB known in the environment. */
1022 /** Array of MDB_db records for each known DB */
1024 /** Array of sequence numbers for each DB handle */
1025 unsigned int *mt_dbiseqs;
1026 /** @defgroup mt_dbflag Transaction DB Flags
1030 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
1031 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1032 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1033 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1035 /** In write txns, array of cursors for each DB */
1036 MDB_cursor **mt_cursors;
1037 /** Array of flags for each DB */
1038 unsigned char *mt_dbflags;
1039 /** Number of DB records in use. This number only ever increments;
1040 * we don't decrement it when individual DB handles are closed.
1044 /** @defgroup mdb_txn Transaction Flags
1048 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
1049 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1050 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1051 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1053 unsigned int mt_flags; /**< @ref mdb_txn */
1054 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1055 * Includes ancestor txns' dirty pages not hidden by other txns'
1056 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1057 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1059 unsigned int mt_dirty_room;
1062 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1063 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1064 * raise this on a 64 bit machine.
1066 #define CURSOR_STACK 32
1070 /** Cursors are used for all DB operations.
1071 * A cursor holds a path of (page pointer, key index) from the DB
1072 * root to a position in the DB, plus other state. #MDB_DUPSORT
1073 * cursors include an xcursor to the current data item. Write txns
1074 * track their cursors and keep them up to date when data moves.
1075 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1076 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1079 /** Next cursor on this DB in this txn */
1080 MDB_cursor *mc_next;
1081 /** Backup of the original cursor if this cursor is a shadow */
1082 MDB_cursor *mc_backup;
1083 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1084 struct MDB_xcursor *mc_xcursor;
1085 /** The transaction that owns this cursor */
1087 /** The database handle this cursor operates on */
1089 /** The database record for this cursor */
1091 /** The database auxiliary record for this cursor */
1093 /** The @ref mt_dbflag for this database */
1094 unsigned char *mc_dbflag;
1095 unsigned short mc_snum; /**< number of pushed pages */
1096 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1097 /** @defgroup mdb_cursor Cursor Flags
1099 * Cursor state flags.
1102 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1103 #define C_EOF 0x02 /**< No more data */
1104 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1105 #define C_DEL 0x08 /**< last op was a cursor_del */
1106 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
1107 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1109 unsigned int mc_flags; /**< @ref mdb_cursor */
1110 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1111 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1114 /** Context for sorted-dup records.
1115 * We could have gone to a fully recursive design, with arbitrarily
1116 * deep nesting of sub-databases. But for now we only handle these
1117 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1119 typedef struct MDB_xcursor {
1120 /** A sub-cursor for traversing the Dup DB */
1121 MDB_cursor mx_cursor;
1122 /** The database record for this Dup DB */
1124 /** The auxiliary DB record for this Dup DB */
1126 /** The @ref mt_dbflag for this Dup DB */
1127 unsigned char mx_dbflag;
1130 /** State of FreeDB old pages, stored in the MDB_env */
1131 typedef struct MDB_pgstate {
1132 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1133 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1136 /** The database environment. */
1138 HANDLE me_fd; /**< The main data file */
1139 HANDLE me_lfd; /**< The lock file */
1140 HANDLE me_mfd; /**< just for writing the meta pages */
1141 /** Failed to update the meta page. Probably an I/O error. */
1142 #define MDB_FATAL_ERROR 0x80000000U
1143 /** Some fields are initialized. */
1144 #define MDB_ENV_ACTIVE 0x20000000U
1145 /** me_txkey is set */
1146 #define MDB_ENV_TXKEY 0x10000000U
1147 uint32_t me_flags; /**< @ref mdb_env */
1148 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1149 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1150 unsigned int me_maxreaders; /**< size of the reader table */
1151 unsigned int me_numreaders; /**< max numreaders set by this env */
1152 MDB_dbi me_numdbs; /**< number of DBs opened */
1153 MDB_dbi me_maxdbs; /**< size of the DB table */
1154 MDB_PID_T me_pid; /**< process ID of this env */
1155 char *me_path; /**< path to the DB files */
1156 char *me_map; /**< the memory map of the data file */
1157 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1158 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
1159 void *me_pbuf; /**< scratch area for DUPSORT put() */
1160 MDB_txn *me_txn; /**< current write transaction */
1161 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1162 size_t me_mapsize; /**< size of the data memory map */
1163 off_t me_size; /**< current file size */
1164 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1165 MDB_dbx *me_dbxs; /**< array of static DB info */
1166 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1167 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1168 pthread_key_t me_txkey; /**< thread-key for readers */
1169 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1170 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1171 # define me_pglast me_pgstate.mf_pglast
1172 # define me_pghead me_pgstate.mf_pghead
1173 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1174 /** IDL of pages that became unused in a write txn */
1175 MDB_IDL me_free_pgs;
1176 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1177 MDB_ID2L me_dirty_list;
1178 /** Max number of freelist items that can fit in a single overflow page */
1180 /** Max size of a node on a page */
1181 unsigned int me_nodemax;
1182 #if !(MDB_MAXKEYSIZE)
1183 unsigned int me_maxkey; /**< max size of a key */
1185 int me_live_reader; /**< have liveness lock in reader table */
1187 int me_pidquery; /**< Used in OpenProcess */
1189 #ifdef BROKEN_FDATASYNC
1190 int me_fsynconly; /**< fdatasync is unreliable */
1192 #if defined(_WIN32) || defined(MDB_USE_SYSV_SEM)
1193 /* Windows mutexes/SysV semaphores do not reside in shared mem */
1194 mdb_mutex_t me_rmutex;
1195 mdb_mutex_t me_wmutex;
1197 void *me_userctx; /**< User-settable context */
1198 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1201 /** Nested transaction */
1202 typedef struct MDB_ntxn {
1203 MDB_txn mnt_txn; /**< the transaction */
1204 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1207 /** max number of pages to commit in one writev() call */
1208 #define MDB_COMMIT_PAGES 64
1209 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1210 #undef MDB_COMMIT_PAGES
1211 #define MDB_COMMIT_PAGES IOV_MAX
1214 /** max bytes to write in one call */
1215 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1217 /** Check \b txn and \b dbi arguments to a function */
1218 #define TXN_DBI_EXIST(txn, dbi) \
1219 ((txn) && (dbi) < (txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & DB_VALID))
1221 /** Check for misused \b dbi handles */
1222 #define TXN_DBI_CHANGED(txn, dbi) \
1223 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1225 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1226 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1227 static int mdb_page_touch(MDB_cursor *mc);
1229 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1230 static int mdb_page_search_root(MDB_cursor *mc,
1231 MDB_val *key, int modify);
1232 #define MDB_PS_MODIFY 1
1233 #define MDB_PS_ROOTONLY 2
1234 #define MDB_PS_FIRST 4
1235 #define MDB_PS_LAST 8
1236 static int mdb_page_search(MDB_cursor *mc,
1237 MDB_val *key, int flags);
1238 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1240 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1241 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1242 pgno_t newpgno, unsigned int nflags);
1244 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1245 static int mdb_env_pick_meta(const MDB_env *env);
1246 static int mdb_env_write_meta(MDB_txn *txn);
1247 #if !(defined(_WIN32) || defined(MDB_USE_SYSV_SEM)) /* Drop unused excl arg */
1248 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1250 static void mdb_env_close0(MDB_env *env, int excl);
1252 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1253 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1254 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1255 static void mdb_node_del(MDB_cursor *mc, int ksize);
1256 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1257 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1258 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1259 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1260 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1262 static int mdb_rebalance(MDB_cursor *mc);
1263 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1265 static void mdb_cursor_pop(MDB_cursor *mc);
1266 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1268 static int mdb_cursor_del0(MDB_cursor *mc);
1269 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1270 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1271 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1272 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1273 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1275 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1276 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1278 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1279 static void mdb_xcursor_init0(MDB_cursor *mc);
1280 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1282 static int mdb_drop0(MDB_cursor *mc, int subs);
1283 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1284 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1287 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1291 static SECURITY_DESCRIPTOR mdb_null_sd;
1292 static SECURITY_ATTRIBUTES mdb_all_sa;
1293 static int mdb_sec_inited;
1296 /** Return the library version info. */
1298 mdb_version(int *major, int *minor, int *patch)
1300 if (major) *major = MDB_VERSION_MAJOR;
1301 if (minor) *minor = MDB_VERSION_MINOR;
1302 if (patch) *patch = MDB_VERSION_PATCH;
1303 return MDB_VERSION_STRING;
1306 /** Table of descriptions for LMDB @ref errors */
1307 static char *const mdb_errstr[] = {
1308 "MDB_KEYEXIST: Key/data pair already exists",
1309 "MDB_NOTFOUND: No matching key/data pair found",
1310 "MDB_PAGE_NOTFOUND: Requested page not found",
1311 "MDB_CORRUPTED: Located page was wrong type",
1312 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1313 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1314 "MDB_INVALID: File is not an LMDB file",
1315 "MDB_MAP_FULL: Environment mapsize limit reached",
1316 "MDB_DBS_FULL: Environment maxdbs limit reached",
1317 "MDB_READERS_FULL: Environment maxreaders limit reached",
1318 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1319 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1320 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1321 "MDB_PAGE_FULL: Internal error - page has no more space",
1322 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1323 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1324 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1325 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1326 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1327 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1331 mdb_strerror(int err)
1334 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1335 * This works as long as no function between the call to mdb_strerror
1336 * and the actual use of the message uses more than 4K of stack.
1339 char buf[1024], *ptr = buf;
1343 return ("Successful return: 0");
1345 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1346 i = err - MDB_KEYEXIST;
1347 return mdb_errstr[i];
1351 /* These are the C-runtime error codes we use. The comment indicates
1352 * their numeric value, and the Win32 error they would correspond to
1353 * if the error actually came from a Win32 API. A major mess, we should
1354 * have used LMDB-specific error codes for everything.
1357 case ENOENT: /* 2, FILE_NOT_FOUND */
1358 case EIO: /* 5, ACCESS_DENIED */
1359 case ENOMEM: /* 12, INVALID_ACCESS */
1360 case EACCES: /* 13, INVALID_DATA */
1361 case EBUSY: /* 16, CURRENT_DIRECTORY */
1362 case EINVAL: /* 22, BAD_COMMAND */
1363 case ENOSPC: /* 28, OUT_OF_PAPER */
1364 return strerror(err);
1369 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1370 FORMAT_MESSAGE_IGNORE_INSERTS,
1371 NULL, err, 0, ptr, sizeof(buf), (va_list *)pad);
1374 return strerror(err);
1378 /** assert(3) variant in cursor context */
1379 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1380 /** assert(3) variant in transaction context */
1381 #define mdb_tassert(mc, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1382 /** assert(3) variant in environment context */
1383 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1386 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1387 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1390 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1391 const char *func, const char *file, int line)
1394 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1395 file, line, expr_txt, func);
1396 if (env->me_assert_func)
1397 env->me_assert_func(env, buf);
1398 fprintf(stderr, "%s\n", buf);
1402 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1406 /** Return the page number of \b mp which may be sub-page, for debug output */
1408 mdb_dbg_pgno(MDB_page *mp)
1411 COPY_PGNO(ret, mp->mp_pgno);
1415 /** Display a key in hexadecimal and return the address of the result.
1416 * @param[in] key the key to display
1417 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1418 * @return The key in hexadecimal form.
1421 mdb_dkey(MDB_val *key, char *buf)
1424 unsigned char *c = key->mv_data;
1430 if (key->mv_size > DKBUF_MAXKEYSIZE)
1431 return "MDB_MAXKEYSIZE";
1432 /* may want to make this a dynamic check: if the key is mostly
1433 * printable characters, print it as-is instead of converting to hex.
1437 for (i=0; i<key->mv_size; i++)
1438 ptr += sprintf(ptr, "%02x", *c++);
1440 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1446 mdb_leafnode_type(MDB_node *n)
1448 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1449 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1450 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1453 /** Display all the keys in the page. */
1455 mdb_page_list(MDB_page *mp)
1457 pgno_t pgno = mdb_dbg_pgno(mp);
1458 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1460 unsigned int i, nkeys, nsize, total = 0;
1464 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1465 case P_BRANCH: type = "Branch page"; break;
1466 case P_LEAF: type = "Leaf page"; break;
1467 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1468 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1469 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1471 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1472 pgno, mp->mp_pages, state);
1475 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1476 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1479 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1483 nkeys = NUMKEYS(mp);
1484 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1486 for (i=0; i<nkeys; i++) {
1487 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1488 key.mv_size = nsize = mp->mp_pad;
1489 key.mv_data = LEAF2KEY(mp, i, nsize);
1491 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1494 node = NODEPTR(mp, i);
1495 key.mv_size = node->mn_ksize;
1496 key.mv_data = node->mn_data;
1497 nsize = NODESIZE + key.mv_size;
1498 if (IS_BRANCH(mp)) {
1499 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1503 if (F_ISSET(node->mn_flags, F_BIGDATA))
1504 nsize += sizeof(pgno_t);
1506 nsize += NODEDSZ(node);
1508 nsize += sizeof(indx_t);
1509 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1510 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1512 total = EVEN(total);
1514 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1515 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1519 mdb_cursor_chk(MDB_cursor *mc)
1525 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1526 for (i=0; i<mc->mc_top; i++) {
1528 node = NODEPTR(mp, mc->mc_ki[i]);
1529 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1532 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1538 /** Count all the pages in each DB and in the freelist
1539 * and make sure it matches the actual number of pages
1541 * All named DBs must be open for a correct count.
1543 static void mdb_audit(MDB_txn *txn)
1547 MDB_ID freecount, count;
1552 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1553 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1554 freecount += *(MDB_ID *)data.mv_data;
1555 mdb_tassert(txn, rc == MDB_NOTFOUND);
1558 for (i = 0; i<txn->mt_numdbs; i++) {
1560 if (!(txn->mt_dbflags[i] & DB_VALID))
1562 mdb_cursor_init(&mc, txn, i, &mx);
1563 if (txn->mt_dbs[i].md_root == P_INVALID)
1565 count += txn->mt_dbs[i].md_branch_pages +
1566 txn->mt_dbs[i].md_leaf_pages +
1567 txn->mt_dbs[i].md_overflow_pages;
1568 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1569 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1570 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1573 mp = mc.mc_pg[mc.mc_top];
1574 for (j=0; j<NUMKEYS(mp); j++) {
1575 MDB_node *leaf = NODEPTR(mp, j);
1576 if (leaf->mn_flags & F_SUBDATA) {
1578 memcpy(&db, NODEDATA(leaf), sizeof(db));
1579 count += db.md_branch_pages + db.md_leaf_pages +
1580 db.md_overflow_pages;
1584 mdb_tassert(txn, rc == MDB_NOTFOUND);
1587 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1588 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1589 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1595 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1597 return txn->mt_dbxs[dbi].md_cmp(a, b);
1601 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1603 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1606 /** Allocate memory for a page.
1607 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1610 mdb_page_malloc(MDB_txn *txn, unsigned num)
1612 MDB_env *env = txn->mt_env;
1613 MDB_page *ret = env->me_dpages;
1614 size_t psize = env->me_psize, sz = psize, off;
1615 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1616 * For a single page alloc, we init everything after the page header.
1617 * For multi-page, we init the final page; if the caller needed that
1618 * many pages they will be filling in at least up to the last page.
1622 VGMEMP_ALLOC(env, ret, sz);
1623 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1624 env->me_dpages = ret->mp_next;
1627 psize -= off = PAGEHDRSZ;
1632 if ((ret = malloc(sz)) != NULL) {
1633 VGMEMP_ALLOC(env, ret, sz);
1634 if (!(env->me_flags & MDB_NOMEMINIT)) {
1635 memset((char *)ret + off, 0, psize);
1639 txn->mt_flags |= MDB_TXN_ERROR;
1643 /** Free a single page.
1644 * Saves single pages to a list, for future reuse.
1645 * (This is not used for multi-page overflow pages.)
1648 mdb_page_free(MDB_env *env, MDB_page *mp)
1650 mp->mp_next = env->me_dpages;
1651 VGMEMP_FREE(env, mp);
1652 env->me_dpages = mp;
1655 /** Free a dirty page */
1657 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1659 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1660 mdb_page_free(env, dp);
1662 /* large pages just get freed directly */
1663 VGMEMP_FREE(env, dp);
1668 /** Return all dirty pages to dpage list */
1670 mdb_dlist_free(MDB_txn *txn)
1672 MDB_env *env = txn->mt_env;
1673 MDB_ID2L dl = txn->mt_u.dirty_list;
1674 unsigned i, n = dl[0].mid;
1676 for (i = 1; i <= n; i++) {
1677 mdb_dpage_free(env, dl[i].mptr);
1682 /** Loosen or free a single page.
1683 * Saves single pages to a list for future reuse
1684 * in this same txn. It has been pulled from the freeDB
1685 * and already resides on the dirty list, but has been
1686 * deleted. Use these pages first before pulling again
1689 * If the page wasn't dirtied in this txn, just add it
1690 * to this txn's free list.
1693 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1696 pgno_t pgno = mp->mp_pgno;
1697 MDB_txn *txn = mc->mc_txn;
1699 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1700 if (txn->mt_parent) {
1701 MDB_ID2 *dl = txn->mt_u.dirty_list;
1702 /* If txn has a parent, make sure the page is in our
1706 unsigned x = mdb_mid2l_search(dl, pgno);
1707 if (x <= dl[0].mid && dl[x].mid == pgno) {
1708 if (mp != dl[x].mptr) { /* bad cursor? */
1709 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1710 txn->mt_flags |= MDB_TXN_ERROR;
1711 return MDB_CORRUPTED;
1718 /* no parent txn, so it's just ours */
1723 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1725 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1726 txn->mt_loose_pgs = mp;
1727 txn->mt_loose_count++;
1728 mp->mp_flags |= P_LOOSE;
1730 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1738 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1739 * @param[in] mc A cursor handle for the current operation.
1740 * @param[in] pflags Flags of the pages to update:
1741 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1742 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1743 * @return 0 on success, non-zero on failure.
1746 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1748 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1749 MDB_txn *txn = mc->mc_txn;
1755 int rc = MDB_SUCCESS, level;
1757 /* Mark pages seen by cursors */
1758 if (mc->mc_flags & C_UNTRACK)
1759 mc = NULL; /* will find mc in mt_cursors */
1760 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1761 for (; mc; mc=mc->mc_next) {
1762 if (!(mc->mc_flags & C_INITIALIZED))
1764 for (m3 = mc;; m3 = &mx->mx_cursor) {
1766 for (j=0; j<m3->mc_snum; j++) {
1768 if ((mp->mp_flags & Mask) == pflags)
1769 mp->mp_flags ^= P_KEEP;
1771 mx = m3->mc_xcursor;
1772 /* Proceed to mx if it is at a sub-database */
1773 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1775 if (! (mp && (mp->mp_flags & P_LEAF)))
1777 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1778 if (!(leaf->mn_flags & F_SUBDATA))
1787 /* Mark dirty root pages */
1788 for (i=0; i<txn->mt_numdbs; i++) {
1789 if (txn->mt_dbflags[i] & DB_DIRTY) {
1790 pgno_t pgno = txn->mt_dbs[i].md_root;
1791 if (pgno == P_INVALID)
1793 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1795 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1796 dp->mp_flags ^= P_KEEP;
1804 static int mdb_page_flush(MDB_txn *txn, int keep);
1806 /** Spill pages from the dirty list back to disk.
1807 * This is intended to prevent running into #MDB_TXN_FULL situations,
1808 * but note that they may still occur in a few cases:
1809 * 1) our estimate of the txn size could be too small. Currently this
1810 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1811 * 2) child txns may run out of space if their parents dirtied a
1812 * lot of pages and never spilled them. TODO: we probably should do
1813 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1814 * the parent's dirty_room is below a given threshold.
1816 * Otherwise, if not using nested txns, it is expected that apps will
1817 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1818 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1819 * If the txn never references them again, they can be left alone.
1820 * If the txn only reads them, they can be used without any fuss.
1821 * If the txn writes them again, they can be dirtied immediately without
1822 * going thru all of the work of #mdb_page_touch(). Such references are
1823 * handled by #mdb_page_unspill().
1825 * Also note, we never spill DB root pages, nor pages of active cursors,
1826 * because we'll need these back again soon anyway. And in nested txns,
1827 * we can't spill a page in a child txn if it was already spilled in a
1828 * parent txn. That would alter the parent txns' data even though
1829 * the child hasn't committed yet, and we'd have no way to undo it if
1830 * the child aborted.
1832 * @param[in] m0 cursor A cursor handle identifying the transaction and
1833 * database for which we are checking space.
1834 * @param[in] key For a put operation, the key being stored.
1835 * @param[in] data For a put operation, the data being stored.
1836 * @return 0 on success, non-zero on failure.
1839 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1841 MDB_txn *txn = m0->mc_txn;
1843 MDB_ID2L dl = txn->mt_u.dirty_list;
1844 unsigned int i, j, need;
1847 if (m0->mc_flags & C_SUB)
1850 /* Estimate how much space this op will take */
1851 i = m0->mc_db->md_depth;
1852 /* Named DBs also dirty the main DB */
1853 if (m0->mc_dbi > MAIN_DBI)
1854 i += txn->mt_dbs[MAIN_DBI].md_depth;
1855 /* For puts, roughly factor in the key+data size */
1857 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1858 i += i; /* double it for good measure */
1861 if (txn->mt_dirty_room > i)
1864 if (!txn->mt_spill_pgs) {
1865 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1866 if (!txn->mt_spill_pgs)
1869 /* purge deleted slots */
1870 MDB_IDL sl = txn->mt_spill_pgs;
1871 unsigned int num = sl[0];
1873 for (i=1; i<=num; i++) {
1880 /* Preserve pages which may soon be dirtied again */
1881 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1884 /* Less aggressive spill - we originally spilled the entire dirty list,
1885 * with a few exceptions for cursor pages and DB root pages. But this
1886 * turns out to be a lot of wasted effort because in a large txn many
1887 * of those pages will need to be used again. So now we spill only 1/8th
1888 * of the dirty pages. Testing revealed this to be a good tradeoff,
1889 * better than 1/2, 1/4, or 1/10.
1891 if (need < MDB_IDL_UM_MAX / 8)
1892 need = MDB_IDL_UM_MAX / 8;
1894 /* Save the page IDs of all the pages we're flushing */
1895 /* flush from the tail forward, this saves a lot of shifting later on. */
1896 for (i=dl[0].mid; i && need; i--) {
1897 MDB_ID pn = dl[i].mid << 1;
1899 if (dp->mp_flags & (P_LOOSE|P_KEEP))
1901 /* Can't spill twice, make sure it's not already in a parent's
1904 if (txn->mt_parent) {
1906 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1907 if (tx2->mt_spill_pgs) {
1908 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1909 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1910 dp->mp_flags |= P_KEEP;
1918 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1922 mdb_midl_sort(txn->mt_spill_pgs);
1924 /* Flush the spilled part of dirty list */
1925 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1928 /* Reset any dirty pages we kept that page_flush didn't see */
1929 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1932 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1936 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1938 mdb_find_oldest(MDB_txn *txn)
1941 txnid_t mr, oldest = txn->mt_txnid - 1;
1942 if (txn->mt_env->me_txns) {
1943 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1944 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1955 /** Add a page to the txn's dirty list */
1957 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1960 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
1962 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1963 insert = mdb_mid2l_append;
1965 insert = mdb_mid2l_insert;
1967 mid.mid = mp->mp_pgno;
1969 rc = insert(txn->mt_u.dirty_list, &mid);
1970 mdb_tassert(txn, rc == 0);
1971 txn->mt_dirty_room--;
1974 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1975 * me_pghead and mt_next_pgno.
1977 * If there are free pages available from older transactions, they
1978 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1979 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1980 * and move me_pglast to say which records were consumed. Only this
1981 * function can create me_pghead and move me_pglast/mt_next_pgno.
1982 * @param[in] mc cursor A cursor handle identifying the transaction and
1983 * database for which we are allocating.
1984 * @param[in] num the number of pages to allocate.
1985 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1986 * will always be satisfied by a single contiguous chunk of memory.
1987 * @return 0 on success, non-zero on failure.
1990 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1992 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1993 /* Get at most <Max_retries> more freeDB records once me_pghead
1994 * has enough pages. If not enough, use new pages from the map.
1995 * If <Paranoid> and mc is updating the freeDB, only get new
1996 * records if me_pghead is empty. Then the freelist cannot play
1997 * catch-up with itself by growing while trying to save it.
1999 enum { Paranoid = 1, Max_retries = 500 };
2001 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2003 int rc, retry = num * 60;
2004 MDB_txn *txn = mc->mc_txn;
2005 MDB_env *env = txn->mt_env;
2006 pgno_t pgno, *mop = env->me_pghead;
2007 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2009 txnid_t oldest = 0, last;
2014 /* If there are any loose pages, just use them */
2015 if (num == 1 && txn->mt_loose_pgs) {
2016 np = txn->mt_loose_pgs;
2017 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2018 txn->mt_loose_count--;
2019 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
2027 /* If our dirty list is already full, we can't do anything */
2028 if (txn->mt_dirty_room == 0) {
2033 for (op = MDB_FIRST;; op = MDB_NEXT) {
2038 /* Seek a big enough contiguous page range. Prefer
2039 * pages at the tail, just truncating the list.
2045 if (mop[i-n2] == pgno+n2)
2052 if (op == MDB_FIRST) { /* 1st iteration */
2053 /* Prepare to fetch more and coalesce */
2054 last = env->me_pglast;
2055 oldest = env->me_pgoldest;
2056 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2059 key.mv_data = &last; /* will look up last+1 */
2060 key.mv_size = sizeof(last);
2062 if (Paranoid && mc->mc_dbi == FREE_DBI)
2065 if (Paranoid && retry < 0 && mop_len)
2069 /* Do not fetch more if the record will be too recent */
2070 if (oldest <= last) {
2072 oldest = mdb_find_oldest(txn);
2073 env->me_pgoldest = oldest;
2079 rc = mdb_cursor_get(&m2, &key, NULL, op);
2081 if (rc == MDB_NOTFOUND)
2085 last = *(txnid_t*)key.mv_data;
2086 if (oldest <= last) {
2088 oldest = mdb_find_oldest(txn);
2089 env->me_pgoldest = oldest;
2095 np = m2.mc_pg[m2.mc_top];
2096 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2097 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
2100 idl = (MDB_ID *) data.mv_data;
2103 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2108 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2110 mop = env->me_pghead;
2112 env->me_pglast = last;
2114 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2115 last, txn->mt_dbs[FREE_DBI].md_root, i));
2117 DPRINTF(("IDL %"Z"u", idl[j]));
2119 /* Merge in descending sorted order */
2120 mdb_midl_xmerge(mop, idl);
2124 /* Use new pages from the map when nothing suitable in the freeDB */
2126 pgno = txn->mt_next_pgno;
2127 if (pgno + num >= env->me_maxpg) {
2128 DPUTS("DB size maxed out");
2134 if (env->me_flags & MDB_WRITEMAP) {
2135 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2137 if (!(np = mdb_page_malloc(txn, num))) {
2143 mop[0] = mop_len -= num;
2144 /* Move any stragglers down */
2145 for (j = i-num; j < mop_len; )
2146 mop[++j] = mop[++i];
2148 txn->mt_next_pgno = pgno + num;
2151 mdb_page_dirty(txn, np);
2157 txn->mt_flags |= MDB_TXN_ERROR;
2161 /** Copy the used portions of a non-overflow page.
2162 * @param[in] dst page to copy into
2163 * @param[in] src page to copy from
2164 * @param[in] psize size of a page
2167 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2169 enum { Align = sizeof(pgno_t) };
2170 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2172 /* If page isn't full, just copy the used portion. Adjust
2173 * alignment so memcpy may copy words instead of bytes.
2175 if ((unused &= -Align) && !IS_LEAF2(src)) {
2176 upper = (upper + PAGEBASE) & -Align;
2177 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2178 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2181 memcpy(dst, src, psize - unused);
2185 /** Pull a page off the txn's spill list, if present.
2186 * If a page being referenced was spilled to disk in this txn, bring
2187 * it back and make it dirty/writable again.
2188 * @param[in] txn the transaction handle.
2189 * @param[in] mp the page being referenced. It must not be dirty.
2190 * @param[out] ret the writable page, if any. ret is unchanged if
2191 * mp wasn't spilled.
2194 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2196 MDB_env *env = txn->mt_env;
2199 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2201 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2202 if (!tx2->mt_spill_pgs)
2204 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2205 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2208 if (txn->mt_dirty_room == 0)
2209 return MDB_TXN_FULL;
2210 if (IS_OVERFLOW(mp))
2214 if (env->me_flags & MDB_WRITEMAP) {
2217 np = mdb_page_malloc(txn, num);
2221 memcpy(np, mp, num * env->me_psize);
2223 mdb_page_copy(np, mp, env->me_psize);
2226 /* If in current txn, this page is no longer spilled.
2227 * If it happens to be the last page, truncate the spill list.
2228 * Otherwise mark it as deleted by setting the LSB.
2230 if (x == txn->mt_spill_pgs[0])
2231 txn->mt_spill_pgs[0]--;
2233 txn->mt_spill_pgs[x] |= 1;
2234 } /* otherwise, if belonging to a parent txn, the
2235 * page remains spilled until child commits
2238 mdb_page_dirty(txn, np);
2239 np->mp_flags |= P_DIRTY;
2247 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2248 * @param[in] mc cursor pointing to the page to be touched
2249 * @return 0 on success, non-zero on failure.
2252 mdb_page_touch(MDB_cursor *mc)
2254 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2255 MDB_txn *txn = mc->mc_txn;
2256 MDB_cursor *m2, *m3;
2260 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2261 if (txn->mt_flags & MDB_TXN_SPILLS) {
2263 rc = mdb_page_unspill(txn, mp, &np);
2269 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2270 (rc = mdb_page_alloc(mc, 1, &np)))
2273 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2274 mp->mp_pgno, pgno));
2275 mdb_cassert(mc, mp->mp_pgno != pgno);
2276 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2277 /* Update the parent page, if any, to point to the new page */
2279 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2280 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2281 SETPGNO(node, pgno);
2283 mc->mc_db->md_root = pgno;
2285 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2286 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2288 /* If txn has a parent, make sure the page is in our
2292 unsigned x = mdb_mid2l_search(dl, pgno);
2293 if (x <= dl[0].mid && dl[x].mid == pgno) {
2294 if (mp != dl[x].mptr) { /* bad cursor? */
2295 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2296 txn->mt_flags |= MDB_TXN_ERROR;
2297 return MDB_CORRUPTED;
2302 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2304 np = mdb_page_malloc(txn, 1);
2309 rc = mdb_mid2l_insert(dl, &mid);
2310 mdb_cassert(mc, rc == 0);
2315 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2317 np->mp_flags |= P_DIRTY;
2320 /* Adjust cursors pointing to mp */
2321 mc->mc_pg[mc->mc_top] = np;
2322 m2 = txn->mt_cursors[mc->mc_dbi];
2323 if (mc->mc_flags & C_SUB) {
2324 for (; m2; m2=m2->mc_next) {
2325 m3 = &m2->mc_xcursor->mx_cursor;
2326 if (m3->mc_snum < mc->mc_snum) continue;
2327 if (m3->mc_pg[mc->mc_top] == mp)
2328 m3->mc_pg[mc->mc_top] = np;
2331 for (; m2; m2=m2->mc_next) {
2332 if (m2->mc_snum < mc->mc_snum) continue;
2333 if (m2->mc_pg[mc->mc_top] == mp) {
2334 m2->mc_pg[mc->mc_top] = np;
2335 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2337 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2339 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2340 if (!(leaf->mn_flags & F_SUBDATA))
2341 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2349 txn->mt_flags |= MDB_TXN_ERROR;
2354 mdb_env_sync(MDB_env *env, int force)
2357 if (env->me_flags & MDB_RDONLY)
2359 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2360 if (env->me_flags & MDB_WRITEMAP) {
2361 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2362 ? MS_ASYNC : MS_SYNC;
2363 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2366 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2370 #ifdef BROKEN_FDATASYNC
2371 if (env->me_fsynconly) {
2372 if (fsync(env->me_fd))
2376 if (MDB_FDATASYNC(env->me_fd))
2383 /** Back up parent txn's cursors, then grab the originals for tracking */
2385 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2387 MDB_cursor *mc, *bk;
2392 for (i = src->mt_numdbs; --i >= 0; ) {
2393 if ((mc = src->mt_cursors[i]) != NULL) {
2394 size = sizeof(MDB_cursor);
2396 size += sizeof(MDB_xcursor);
2397 for (; mc; mc = bk->mc_next) {
2403 mc->mc_db = &dst->mt_dbs[i];
2404 /* Kill pointers into src - and dst to reduce abuse: The
2405 * user may not use mc until dst ends. Otherwise we'd...
2407 mc->mc_txn = NULL; /* ...set this to dst */
2408 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2409 if ((mx = mc->mc_xcursor) != NULL) {
2410 *(MDB_xcursor *)(bk+1) = *mx;
2411 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2413 mc->mc_next = dst->mt_cursors[i];
2414 dst->mt_cursors[i] = mc;
2421 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2422 * @param[in] txn the transaction handle.
2423 * @param[in] merge true to keep changes to parent cursors, false to revert.
2424 * @return 0 on success, non-zero on failure.
2427 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2429 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2433 for (i = txn->mt_numdbs; --i >= 0; ) {
2434 for (mc = cursors[i]; mc; mc = next) {
2436 if ((bk = mc->mc_backup) != NULL) {
2438 /* Commit changes to parent txn */
2439 mc->mc_next = bk->mc_next;
2440 mc->mc_backup = bk->mc_backup;
2441 mc->mc_txn = bk->mc_txn;
2442 mc->mc_db = bk->mc_db;
2443 mc->mc_dbflag = bk->mc_dbflag;
2444 if ((mx = mc->mc_xcursor) != NULL)
2445 mx->mx_cursor.mc_txn = bk->mc_txn;
2447 /* Abort nested txn */
2449 if ((mx = mc->mc_xcursor) != NULL)
2450 *mx = *(MDB_xcursor *)(bk+1);
2454 /* Only malloced cursors are permanently tracked. */
2462 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2465 mdb_txn_reset0(MDB_txn *txn, const char *act);
2467 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2473 Pidset = F_SETLK, Pidcheck = F_GETLK
2477 /** Set or check a pid lock. Set returns 0 on success.
2478 * Check returns 0 if the process is certainly dead, nonzero if it may
2479 * be alive (the lock exists or an error happened so we do not know).
2481 * On Windows Pidset is a no-op, we merely check for the existence
2482 * of the process with the given pid. On POSIX we use a single byte
2483 * lock on the lockfile, set at an offset equal to the pid.
2486 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2488 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2491 if (op == Pidcheck) {
2492 h = OpenProcess(env->me_pidquery, FALSE, pid);
2493 /* No documented "no such process" code, but other program use this: */
2495 return ErrCode() != ERROR_INVALID_PARAMETER;
2496 /* A process exists until all handles to it close. Has it exited? */
2497 ret = WaitForSingleObject(h, 0) != 0;
2504 struct flock lock_info;
2505 memset(&lock_info, 0, sizeof(lock_info));
2506 lock_info.l_type = F_WRLCK;
2507 lock_info.l_whence = SEEK_SET;
2508 lock_info.l_start = pid;
2509 lock_info.l_len = 1;
2510 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2511 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2513 } else if ((rc = ErrCode()) == EINTR) {
2521 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2522 * @param[in] txn the transaction handle to initialize
2523 * @return 0 on success, non-zero on failure.
2526 mdb_txn_renew0(MDB_txn *txn)
2528 MDB_env *env = txn->mt_env;
2529 MDB_txninfo *ti = env->me_txns;
2533 int rc, new_notls = 0;
2535 if (txn->mt_flags & MDB_TXN_RDONLY) {
2537 txn->mt_numdbs = env->me_numdbs;
2538 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2540 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2541 txn->mt_txnid = meta->mm_txnid;
2542 txn->mt_u.reader = NULL;
2544 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2545 pthread_getspecific(env->me_txkey);
2547 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2548 return MDB_BAD_RSLOT;
2550 MDB_PID_T pid = env->me_pid;
2551 MDB_THR_T tid = pthread_self();
2552 mdb_mutex_t *rmutex = MDB_MUTEX(env, r);
2554 if (!env->me_live_reader) {
2555 rc = mdb_reader_pid(env, Pidset, pid);
2558 env->me_live_reader = 1;
2561 if (LOCK_MUTEX(rc, env, rmutex))
2563 nr = ti->mti_numreaders;
2564 for (i=0; i<nr; i++)
2565 if (ti->mti_readers[i].mr_pid == 0)
2567 if (i == env->me_maxreaders) {
2568 UNLOCK_MUTEX(rmutex);
2569 return MDB_READERS_FULL;
2571 r = &ti->mti_readers[i];
2572 r->mr_txnid = (txnid_t)-1;
2574 r->mr_pid = pid; /* should be written last, see ITS#7971. */
2576 ti->mti_numreaders = ++nr;
2577 /* Save numreaders for un-mutexed mdb_env_close() */
2578 env->me_numreaders = nr;
2579 UNLOCK_MUTEX(rmutex);
2581 new_notls = (env->me_flags & MDB_NOTLS);
2582 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2587 do /* LY: Retry on a race, ITS#7970. */
2588 r->mr_txnid = ti->mti_txnid;
2589 while(r->mr_txnid != ti->mti_txnid);
2590 txn->mt_txnid = r->mr_txnid;
2591 txn->mt_u.reader = r;
2592 meta = env->me_metas[txn->mt_txnid & 1];
2596 if (LOCK_MUTEX(rc, env, MDB_MUTEX(env, w)))
2598 #ifdef MDB_USE_SYSV_SEM
2599 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2600 txn->mt_txnid = meta->mm_txnid;
2601 /* Update mti_txnid like mdb_mutex_failed() would,
2602 * in case last writer crashed before updating it.
2604 ti->mti_txnid = txn->mt_txnid;
2606 txn->mt_txnid = ti->mti_txnid;
2607 meta = env->me_metas[txn->mt_txnid & 1];
2610 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2611 txn->mt_txnid = meta->mm_txnid;
2614 txn->mt_numdbs = env->me_numdbs;
2617 if (txn->mt_txnid == mdb_debug_start)
2621 txn->mt_child = NULL;
2622 txn->mt_loose_pgs = NULL;
2623 txn->mt_loose_count = 0;
2624 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2625 txn->mt_u.dirty_list = env->me_dirty_list;
2626 txn->mt_u.dirty_list[0].mid = 0;
2627 txn->mt_free_pgs = env->me_free_pgs;
2628 txn->mt_free_pgs[0] = 0;
2629 txn->mt_spill_pgs = NULL;
2631 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2634 /* Copy the DB info and flags */
2635 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2637 /* Moved to here to avoid a data race in read TXNs */
2638 txn->mt_next_pgno = meta->mm_last_pg+1;
2640 for (i=2; i<txn->mt_numdbs; i++) {
2641 x = env->me_dbflags[i];
2642 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2643 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2645 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2647 if (env->me_maxpg < txn->mt_next_pgno) {
2648 mdb_txn_reset0(txn, "renew0-mapfail");
2650 txn->mt_u.reader->mr_pid = 0;
2651 txn->mt_u.reader = NULL;
2653 return MDB_MAP_RESIZED;
2660 mdb_txn_renew(MDB_txn *txn)
2664 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2667 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2668 DPUTS("environment had fatal error, must shutdown!");
2672 rc = mdb_txn_renew0(txn);
2673 if (rc == MDB_SUCCESS) {
2674 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2675 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2676 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2682 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2686 int rc, size, tsize = sizeof(MDB_txn);
2688 if (env->me_flags & MDB_FATAL_ERROR) {
2689 DPUTS("environment had fatal error, must shutdown!");
2692 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2695 /* Nested transactions: Max 1 child, write txns only, no writemap */
2696 if (parent->mt_child ||
2697 (flags & MDB_RDONLY) ||
2698 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2699 (env->me_flags & MDB_WRITEMAP))
2701 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2703 tsize = sizeof(MDB_ntxn);
2706 if (!(flags & MDB_RDONLY)) {
2708 txn = env->me_txn0; /* just reuse preallocated write txn */
2711 /* child txns use own copy of cursors */
2712 size += env->me_maxdbs * sizeof(MDB_cursor *);
2714 size += env->me_maxdbs * (sizeof(MDB_db)+1);
2716 if ((txn = calloc(1, size)) == NULL) {
2717 DPRINTF(("calloc: %s", strerror(errno)));
2720 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2721 if (flags & MDB_RDONLY) {
2722 txn->mt_flags |= MDB_TXN_RDONLY;
2723 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2724 txn->mt_dbiseqs = env->me_dbiseqs;
2726 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2728 txn->mt_dbiseqs = parent->mt_dbiseqs;
2729 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2731 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
2732 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
2740 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2741 if (!txn->mt_u.dirty_list ||
2742 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2744 free(txn->mt_u.dirty_list);
2748 txn->mt_txnid = parent->mt_txnid;
2749 txn->mt_dirty_room = parent->mt_dirty_room;
2750 txn->mt_u.dirty_list[0].mid = 0;
2751 txn->mt_spill_pgs = NULL;
2752 txn->mt_next_pgno = parent->mt_next_pgno;
2753 parent->mt_child = txn;
2754 txn->mt_parent = parent;
2755 txn->mt_numdbs = parent->mt_numdbs;
2756 txn->mt_flags = parent->mt_flags;
2757 txn->mt_dbxs = parent->mt_dbxs;
2758 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2759 /* Copy parent's mt_dbflags, but clear DB_NEW */
2760 for (i=0; i<txn->mt_numdbs; i++)
2761 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2763 ntxn = (MDB_ntxn *)txn;
2764 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2765 if (env->me_pghead) {
2766 size = MDB_IDL_SIZEOF(env->me_pghead);
2767 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2769 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2774 rc = mdb_cursor_shadow(parent, txn);
2776 mdb_txn_reset0(txn, "beginchild-fail");
2778 rc = mdb_txn_renew0(txn);
2781 if (txn != env->me_txn0)
2785 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2786 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2787 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2794 mdb_txn_env(MDB_txn *txn)
2796 if(!txn) return NULL;
2801 mdb_txn_id(MDB_txn *txn)
2804 return txn->mt_txnid;
2807 /** Export or close DBI handles opened in this txn. */
2809 mdb_dbis_update(MDB_txn *txn, int keep)
2812 MDB_dbi n = txn->mt_numdbs;
2813 MDB_env *env = txn->mt_env;
2814 unsigned char *tdbflags = txn->mt_dbflags;
2816 for (i = n; --i >= 2;) {
2817 if (tdbflags[i] & DB_NEW) {
2819 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2821 char *ptr = env->me_dbxs[i].md_name.mv_data;
2823 env->me_dbxs[i].md_name.mv_data = NULL;
2824 env->me_dbxs[i].md_name.mv_size = 0;
2825 env->me_dbflags[i] = 0;
2826 env->me_dbiseqs[i]++;
2832 if (keep && env->me_numdbs < n)
2836 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2837 * May be called twice for readonly txns: First reset it, then abort.
2838 * @param[in] txn the transaction handle to reset
2839 * @param[in] act why the transaction is being reset
2842 mdb_txn_reset0(MDB_txn *txn, const char *act)
2844 MDB_env *env = txn->mt_env;
2846 /* Close any DBI handles opened in this txn */
2847 mdb_dbis_update(txn, 0);
2849 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2850 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2851 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2853 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2854 if (txn->mt_u.reader) {
2855 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2856 if (!(env->me_flags & MDB_NOTLS))
2857 txn->mt_u.reader = NULL; /* txn does not own reader */
2859 txn->mt_numdbs = 0; /* close nothing if called again */
2860 txn->mt_dbxs = NULL; /* mark txn as reset */
2862 pgno_t *pghead = env->me_pghead;
2864 mdb_cursors_close(txn, 0);
2865 if (!(env->me_flags & MDB_WRITEMAP)) {
2866 mdb_dlist_free(txn);
2869 if (!txn->mt_parent) {
2870 if (mdb_midl_shrink(&txn->mt_free_pgs))
2871 env->me_free_pgs = txn->mt_free_pgs;
2873 env->me_pghead = NULL;
2877 /* The writer mutex was locked in mdb_txn_begin. */
2879 UNLOCK_MUTEX(MDB_MUTEX(env, w));
2881 txn->mt_parent->mt_child = NULL;
2882 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2883 mdb_midl_free(txn->mt_free_pgs);
2884 mdb_midl_free(txn->mt_spill_pgs);
2885 free(txn->mt_u.dirty_list);
2888 mdb_midl_free(pghead);
2893 mdb_txn_reset(MDB_txn *txn)
2898 /* This call is only valid for read-only txns */
2899 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2902 mdb_txn_reset0(txn, "reset");
2906 mdb_txn_abort(MDB_txn *txn)
2912 mdb_txn_abort(txn->mt_child);
2914 mdb_txn_reset0(txn, "abort");
2915 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2916 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2917 txn->mt_u.reader->mr_pid = 0;
2919 if (txn != txn->mt_env->me_txn0)
2923 /** Save the freelist as of this transaction to the freeDB.
2924 * This changes the freelist. Keep trying until it stabilizes.
2927 mdb_freelist_save(MDB_txn *txn)
2929 /* env->me_pghead[] can grow and shrink during this call.
2930 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2931 * Page numbers cannot disappear from txn->mt_free_pgs[].
2934 MDB_env *env = txn->mt_env;
2935 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2936 txnid_t pglast = 0, head_id = 0;
2937 pgno_t freecnt = 0, *free_pgs, *mop;
2938 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2940 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2942 if (env->me_pghead) {
2943 /* Make sure first page of freeDB is touched and on freelist */
2944 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2945 if (rc && rc != MDB_NOTFOUND)
2949 if (!env->me_pghead && txn->mt_loose_pgs) {
2950 /* Put loose page numbers in mt_free_pgs, since
2951 * we may be unable to return them to me_pghead.
2953 MDB_page *mp = txn->mt_loose_pgs;
2954 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
2956 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
2957 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2958 txn->mt_loose_pgs = NULL;
2959 txn->mt_loose_count = 0;
2962 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2963 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2964 ? SSIZE_MAX : maxfree_1pg;
2967 /* Come back here after each Put() in case freelist changed */
2972 /* If using records from freeDB which we have not yet
2973 * deleted, delete them and any we reserved for me_pghead.
2975 while (pglast < env->me_pglast) {
2976 rc = mdb_cursor_first(&mc, &key, NULL);
2979 pglast = head_id = *(txnid_t *)key.mv_data;
2980 total_room = head_room = 0;
2981 mdb_tassert(txn, pglast <= env->me_pglast);
2982 rc = mdb_cursor_del(&mc, 0);
2987 /* Save the IDL of pages freed by this txn, to a single record */
2988 if (freecnt < txn->mt_free_pgs[0]) {
2990 /* Make sure last page of freeDB is touched and on freelist */
2991 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2992 if (rc && rc != MDB_NOTFOUND)
2995 free_pgs = txn->mt_free_pgs;
2996 /* Write to last page of freeDB */
2997 key.mv_size = sizeof(txn->mt_txnid);
2998 key.mv_data = &txn->mt_txnid;
3000 freecnt = free_pgs[0];
3001 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3002 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3005 /* Retry if mt_free_pgs[] grew during the Put() */
3006 free_pgs = txn->mt_free_pgs;
3007 } while (freecnt < free_pgs[0]);
3008 mdb_midl_sort(free_pgs);
3009 memcpy(data.mv_data, free_pgs, data.mv_size);
3012 unsigned int i = free_pgs[0];
3013 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
3014 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3016 DPRINTF(("IDL %"Z"u", free_pgs[i]));
3022 mop = env->me_pghead;
3023 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3025 /* Reserve records for me_pghead[]. Split it if multi-page,
3026 * to avoid searching freeDB for a page range. Use keys in
3027 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3029 if (total_room >= mop_len) {
3030 if (total_room == mop_len || --more < 0)
3032 } else if (head_room >= maxfree_1pg && head_id > 1) {
3033 /* Keep current record (overflow page), add a new one */
3037 /* (Re)write {key = head_id, IDL length = head_room} */
3038 total_room -= head_room;
3039 head_room = mop_len - total_room;
3040 if (head_room > maxfree_1pg && head_id > 1) {
3041 /* Overflow multi-page for part of me_pghead */
3042 head_room /= head_id; /* amortize page sizes */
3043 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3044 } else if (head_room < 0) {
3045 /* Rare case, not bothering to delete this record */
3048 key.mv_size = sizeof(head_id);
3049 key.mv_data = &head_id;
3050 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3051 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3054 /* IDL is initially empty, zero out at least the length */
3055 pgs = (pgno_t *)data.mv_data;
3056 j = head_room > clean_limit ? head_room : 0;
3060 total_room += head_room;
3063 /* Return loose page numbers to me_pghead, though usually none are
3064 * left at this point. The pages themselves remain in dirty_list.
3066 if (txn->mt_loose_pgs) {
3067 MDB_page *mp = txn->mt_loose_pgs;
3068 unsigned count = txn->mt_loose_count;
3070 /* Room for loose pages + temp IDL with same */
3071 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3073 mop = env->me_pghead;
3074 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3075 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3076 loose[ ++count ] = mp->mp_pgno;
3078 mdb_midl_sort(loose);
3079 mdb_midl_xmerge(mop, loose);
3080 txn->mt_loose_pgs = NULL;
3081 txn->mt_loose_count = 0;
3085 /* Fill in the reserved me_pghead records */
3091 rc = mdb_cursor_first(&mc, &key, &data);
3092 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3093 txnid_t id = *(txnid_t *)key.mv_data;
3094 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3097 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3099 if (len > mop_len) {
3101 data.mv_size = (len + 1) * sizeof(MDB_ID);
3103 data.mv_data = mop -= len;
3106 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3108 if (rc || !(mop_len -= len))
3115 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3116 * @param[in] txn the transaction that's being committed
3117 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3118 * @return 0 on success, non-zero on failure.
3121 mdb_page_flush(MDB_txn *txn, int keep)
3123 MDB_env *env = txn->mt_env;
3124 MDB_ID2L dl = txn->mt_u.dirty_list;
3125 unsigned psize = env->me_psize, j;
3126 int i, pagecount = dl[0].mid, rc;
3127 size_t size = 0, pos = 0;
3129 MDB_page *dp = NULL;
3133 struct iovec iov[MDB_COMMIT_PAGES];
3134 ssize_t wpos = 0, wsize = 0, wres;
3135 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3141 if (env->me_flags & MDB_WRITEMAP) {
3142 /* Clear dirty flags */
3143 while (++i <= pagecount) {
3145 /* Don't flush this page yet */
3146 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3147 dp->mp_flags &= ~P_KEEP;
3151 dp->mp_flags &= ~P_DIRTY;
3156 /* Write the pages */
3158 if (++i <= pagecount) {
3160 /* Don't flush this page yet */
3161 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3162 dp->mp_flags &= ~P_KEEP;
3167 /* clear dirty flag */
3168 dp->mp_flags &= ~P_DIRTY;
3171 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3176 /* Windows actually supports scatter/gather I/O, but only on
3177 * unbuffered file handles. Since we're relying on the OS page
3178 * cache for all our data, that's self-defeating. So we just
3179 * write pages one at a time. We use the ov structure to set
3180 * the write offset, to at least save the overhead of a Seek
3183 DPRINTF(("committing page %"Z"u", pgno));
3184 memset(&ov, 0, sizeof(ov));
3185 ov.Offset = pos & 0xffffffff;
3186 ov.OffsetHigh = pos >> 16 >> 16;
3187 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3189 DPRINTF(("WriteFile: %d", rc));
3193 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3194 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3196 /* Write previous page(s) */
3197 #ifdef MDB_USE_PWRITEV
3198 wres = pwritev(env->me_fd, iov, n, wpos);
3201 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3203 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3205 DPRINTF(("lseek: %s", strerror(rc)));
3208 wres = writev(env->me_fd, iov, n);
3211 if (wres != wsize) {
3214 DPRINTF(("Write error: %s", strerror(rc)));
3216 rc = EIO; /* TODO: Use which error code? */
3217 DPUTS("short write, filesystem full?");
3228 DPRINTF(("committing page %"Z"u", pgno));
3229 next_pos = pos + size;
3230 iov[n].iov_len = size;
3231 iov[n].iov_base = (char *)dp;
3237 /* MIPS has cache coherency issues, this is a no-op everywhere else
3238 * Note: for any size >= on-chip cache size, entire on-chip cache is
3241 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3243 for (i = keep; ++i <= pagecount; ) {
3245 /* This is a page we skipped above */
3248 dl[j].mid = dp->mp_pgno;
3251 mdb_dpage_free(env, dp);
3256 txn->mt_dirty_room += i - j;
3262 mdb_txn_commit(MDB_txn *txn)
3268 if (txn == NULL || txn->mt_env == NULL)
3271 if (txn->mt_child) {
3272 rc = mdb_txn_commit(txn->mt_child);
3273 txn->mt_child = NULL;
3280 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3281 mdb_dbis_update(txn, 1);
3282 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
3287 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
3288 DPUTS("error flag is set, can't commit");
3290 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3295 if (txn->mt_parent) {
3296 MDB_txn *parent = txn->mt_parent;
3300 unsigned x, y, len, ps_len;
3302 /* Append our free list to parent's */
3303 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3306 mdb_midl_free(txn->mt_free_pgs);
3307 /* Failures after this must either undo the changes
3308 * to the parent or set MDB_TXN_ERROR in the parent.
3311 parent->mt_next_pgno = txn->mt_next_pgno;
3312 parent->mt_flags = txn->mt_flags;
3314 /* Merge our cursors into parent's and close them */
3315 mdb_cursors_close(txn, 1);
3317 /* Update parent's DB table. */
3318 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3319 parent->mt_numdbs = txn->mt_numdbs;
3320 parent->mt_dbflags[0] = txn->mt_dbflags[0];
3321 parent->mt_dbflags[1] = txn->mt_dbflags[1];
3322 for (i=2; i<txn->mt_numdbs; i++) {
3323 /* preserve parent's DB_NEW status */
3324 x = parent->mt_dbflags[i] & DB_NEW;
3325 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3328 dst = parent->mt_u.dirty_list;
3329 src = txn->mt_u.dirty_list;
3330 /* Remove anything in our dirty list from parent's spill list */
3331 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3333 pspill[0] = (pgno_t)-1;
3334 /* Mark our dirty pages as deleted in parent spill list */
3335 for (i=0, len=src[0].mid; ++i <= len; ) {
3336 MDB_ID pn = src[i].mid << 1;
3337 while (pn > pspill[x])
3339 if (pn == pspill[x]) {
3344 /* Squash deleted pagenums if we deleted any */
3345 for (x=y; ++x <= ps_len; )
3346 if (!(pspill[x] & 1))
3347 pspill[++y] = pspill[x];
3351 /* Find len = length of merging our dirty list with parent's */
3353 dst[0].mid = 0; /* simplify loops */
3354 if (parent->mt_parent) {
3355 len = x + src[0].mid;
3356 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3357 for (i = x; y && i; y--) {
3358 pgno_t yp = src[y].mid;
3359 while (yp < dst[i].mid)
3361 if (yp == dst[i].mid) {
3366 } else { /* Simplify the above for single-ancestor case */
3367 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3369 /* Merge our dirty list with parent's */
3371 for (i = len; y; dst[i--] = src[y--]) {
3372 pgno_t yp = src[y].mid;
3373 while (yp < dst[x].mid)
3374 dst[i--] = dst[x--];
3375 if (yp == dst[x].mid)
3376 free(dst[x--].mptr);
3378 mdb_tassert(txn, i == x);
3380 free(txn->mt_u.dirty_list);
3381 parent->mt_dirty_room = txn->mt_dirty_room;
3382 if (txn->mt_spill_pgs) {
3383 if (parent->mt_spill_pgs) {
3384 /* TODO: Prevent failure here, so parent does not fail */
3385 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3387 parent->mt_flags |= MDB_TXN_ERROR;
3388 mdb_midl_free(txn->mt_spill_pgs);
3389 mdb_midl_sort(parent->mt_spill_pgs);
3391 parent->mt_spill_pgs = txn->mt_spill_pgs;
3395 /* Append our loose page list to parent's */
3396 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(lp))
3398 *lp = txn->mt_loose_pgs;
3399 parent->mt_loose_count += txn->mt_loose_count;
3401 parent->mt_child = NULL;
3402 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3407 if (txn != env->me_txn) {
3408 DPUTS("attempt to commit unknown transaction");
3413 mdb_cursors_close(txn, 0);
3415 if (!txn->mt_u.dirty_list[0].mid &&
3416 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3419 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3420 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3422 /* Update DB root pointers */
3423 if (txn->mt_numdbs > 2) {
3427 data.mv_size = sizeof(MDB_db);
3429 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3430 for (i = 2; i < txn->mt_numdbs; i++) {
3431 if (txn->mt_dbflags[i] & DB_DIRTY) {
3432 if (TXN_DBI_CHANGED(txn, i)) {
3436 data.mv_data = &txn->mt_dbs[i];
3437 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
3444 rc = mdb_freelist_save(txn);
3448 mdb_midl_free(env->me_pghead);
3449 env->me_pghead = NULL;
3450 if (mdb_midl_shrink(&txn->mt_free_pgs))
3451 env->me_free_pgs = txn->mt_free_pgs;
3457 if ((rc = mdb_page_flush(txn, 0)) ||
3458 (rc = mdb_env_sync(env, 0)) ||
3459 (rc = mdb_env_write_meta(txn)))
3462 /* Free P_LOOSE pages left behind in dirty_list */
3463 if (!(env->me_flags & MDB_WRITEMAP))
3464 mdb_dlist_free(txn);
3469 mdb_dbis_update(txn, 1);
3472 UNLOCK_MUTEX(MDB_MUTEX(env, w));
3473 if (txn != env->me_txn0)
3483 /** Read the environment parameters of a DB environment before
3484 * mapping it into memory.
3485 * @param[in] env the environment handle
3486 * @param[out] meta address of where to store the meta information
3487 * @return 0 on success, non-zero on failure.
3490 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3496 enum { Size = sizeof(pbuf) };
3498 /* We don't know the page size yet, so use a minimum value.
3499 * Read both meta pages so we can use the latest one.
3502 for (i=off=0; i<2; i++, off = meta->mm_psize) {
3506 memset(&ov, 0, sizeof(ov));
3508 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3509 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3512 rc = pread(env->me_fd, &pbuf, Size, off);
3515 if (rc == 0 && off == 0)
3517 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3518 DPRINTF(("read: %s", mdb_strerror(rc)));
3522 p = (MDB_page *)&pbuf;
3524 if (!F_ISSET(p->mp_flags, P_META)) {
3525 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3530 if (m->mm_magic != MDB_MAGIC) {
3531 DPUTS("meta has invalid magic");
3535 if (m->mm_version != MDB_DATA_VERSION) {
3536 DPRINTF(("database is version %u, expected version %u",
3537 m->mm_version, MDB_DATA_VERSION));
3538 return MDB_VERSION_MISMATCH;
3541 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3547 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3549 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3551 meta->mm_magic = MDB_MAGIC;
3552 meta->mm_version = MDB_DATA_VERSION;
3553 meta->mm_mapsize = env->me_mapsize;
3554 meta->mm_psize = env->me_psize;
3555 meta->mm_last_pg = 1;
3556 meta->mm_flags = env->me_flags & 0xffff;
3557 meta->mm_flags |= MDB_INTEGERKEY;
3558 meta->mm_dbs[0].md_root = P_INVALID;
3559 meta->mm_dbs[1].md_root = P_INVALID;
3562 /** Write the environment parameters of a freshly created DB environment.
3563 * @param[in] env the environment handle
3564 * @param[in] meta the #MDB_meta to write
3565 * @return 0 on success, non-zero on failure.
3568 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3576 memset(&ov, 0, sizeof(ov));
3577 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3579 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3582 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3583 len = pwrite(fd, ptr, size, pos); \
3584 rc = (len >= 0); } while(0)
3587 DPUTS("writing new meta page");
3589 psize = env->me_psize;
3591 p = calloc(2, psize);
3593 p->mp_flags = P_META;
3594 *(MDB_meta *)METADATA(p) = *meta;
3596 q = (MDB_page *)((char *)p + psize);
3598 q->mp_flags = P_META;
3599 *(MDB_meta *)METADATA(q) = *meta;
3601 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3604 else if ((unsigned) len == psize * 2)
3612 /** Update the environment info to commit a transaction.
3613 * @param[in] txn the transaction that's being committed
3614 * @return 0 on success, non-zero on failure.
3617 mdb_env_write_meta(MDB_txn *txn)
3620 MDB_meta meta, metab, *mp;
3623 int rc, len, toggle;
3632 toggle = txn->mt_txnid & 1;
3633 DPRINTF(("writing meta page %d for root page %"Z"u",
3634 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3637 mp = env->me_metas[toggle];
3638 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3639 /* Persist any increases of mapsize config */
3640 if (mapsize < env->me_mapsize)
3641 mapsize = env->me_mapsize;
3643 if (env->me_flags & MDB_WRITEMAP) {
3644 mp->mm_mapsize = mapsize;
3645 mp->mm_dbs[0] = txn->mt_dbs[0];
3646 mp->mm_dbs[1] = txn->mt_dbs[1];
3647 mp->mm_last_pg = txn->mt_next_pgno - 1;
3648 #if !(defined(_MSC_VER) || defined(__i386__) || defined(__x86_64__))
3649 /* LY: issue a memory barrier, if not x86. ITS#7969 */
3650 __sync_synchronize();
3652 mp->mm_txnid = txn->mt_txnid;
3653 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3654 unsigned meta_size = env->me_psize;
3655 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3658 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3659 if (meta_size < env->me_os_psize)
3660 meta_size += meta_size;
3665 if (MDB_MSYNC(ptr, meta_size, rc)) {
3672 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3673 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3675 meta.mm_mapsize = mapsize;
3676 meta.mm_dbs[0] = txn->mt_dbs[0];
3677 meta.mm_dbs[1] = txn->mt_dbs[1];
3678 meta.mm_last_pg = txn->mt_next_pgno - 1;
3679 meta.mm_txnid = txn->mt_txnid;
3681 off = offsetof(MDB_meta, mm_mapsize);
3682 ptr = (char *)&meta + off;
3683 len = sizeof(MDB_meta) - off;
3685 off += env->me_psize;
3688 /* Write to the SYNC fd */
3689 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3690 env->me_fd : env->me_mfd;
3693 memset(&ov, 0, sizeof(ov));
3695 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3699 rc = pwrite(mfd, ptr, len, off);
3702 rc = rc < 0 ? ErrCode() : EIO;
3703 DPUTS("write failed, disk error?");
3704 /* On a failure, the pagecache still contains the new data.
3705 * Write some old data back, to prevent it from being used.
3706 * Use the non-SYNC fd; we know it will fail anyway.
3708 meta.mm_last_pg = metab.mm_last_pg;
3709 meta.mm_txnid = metab.mm_txnid;
3711 memset(&ov, 0, sizeof(ov));
3713 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3715 r2 = pwrite(env->me_fd, ptr, len, off);
3716 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3719 env->me_flags |= MDB_FATAL_ERROR;
3722 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3723 CACHEFLUSH(env->me_map + off, len, DCACHE);
3725 /* Memory ordering issues are irrelevant; since the entire writer
3726 * is wrapped by wmutex, all of these changes will become visible
3727 * after the wmutex is unlocked. Since the DB is multi-version,
3728 * readers will get consistent data regardless of how fresh or
3729 * how stale their view of these values is.
3732 env->me_txns->mti_txnid = txn->mt_txnid;
3737 /** Check both meta pages to see which one is newer.
3738 * @param[in] env the environment handle
3739 * @return meta toggle (0 or 1).
3742 mdb_env_pick_meta(const MDB_env *env)
3744 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3748 mdb_env_create(MDB_env **env)
3752 e = calloc(1, sizeof(MDB_env));
3756 e->me_maxreaders = DEFAULT_READERS;
3757 e->me_maxdbs = e->me_numdbs = 2;
3758 e->me_fd = INVALID_HANDLE_VALUE;
3759 e->me_lfd = INVALID_HANDLE_VALUE;
3760 e->me_mfd = INVALID_HANDLE_VALUE;
3761 #ifdef MDB_USE_SYSV_SEM
3762 e->me_rmutex.semid = -1;
3763 e->me_wmutex.semid = -1;
3765 e->me_pid = getpid();
3766 GET_PAGESIZE(e->me_os_psize);
3767 VGMEMP_CREATE(e,0,0);
3773 mdb_env_map(MDB_env *env, void *addr)
3776 unsigned int flags = env->me_flags;
3780 LONG sizelo, sizehi;
3783 if (flags & MDB_RDONLY) {
3784 /* Don't set explicit map size, use whatever exists */
3789 msize = env->me_mapsize;
3790 sizelo = msize & 0xffffffff;
3791 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3793 /* Windows won't create mappings for zero length files.
3794 * and won't map more than the file size.
3795 * Just set the maxsize right now.
3797 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3798 || !SetEndOfFile(env->me_fd)
3799 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3803 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3804 PAGE_READWRITE : PAGE_READONLY,
3805 sizehi, sizelo, NULL);
3808 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3809 FILE_MAP_WRITE : FILE_MAP_READ,
3811 rc = env->me_map ? 0 : ErrCode();
3816 int prot = PROT_READ;
3817 if (flags & MDB_WRITEMAP) {
3819 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3822 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3824 if (env->me_map == MAP_FAILED) {
3829 if (flags & MDB_NORDAHEAD) {
3830 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3832 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3834 #ifdef POSIX_MADV_RANDOM
3835 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3836 #endif /* POSIX_MADV_RANDOM */
3837 #endif /* MADV_RANDOM */
3841 /* Can happen because the address argument to mmap() is just a
3842 * hint. mmap() can pick another, e.g. if the range is in use.
3843 * The MAP_FIXED flag would prevent that, but then mmap could
3844 * instead unmap existing pages to make room for the new map.
3846 if (addr && env->me_map != addr)
3847 return EBUSY; /* TODO: Make a new MDB_* error code? */
3849 p = (MDB_page *)env->me_map;
3850 env->me_metas[0] = METADATA(p);
3851 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3857 mdb_env_set_mapsize(MDB_env *env, size_t size)
3859 /* If env is already open, caller is responsible for making
3860 * sure there are no active txns.
3868 meta = env->me_metas[mdb_env_pick_meta(env)];
3870 size = meta->mm_mapsize;
3872 /* Silently round up to minimum if the size is too small */
3873 size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
3877 munmap(env->me_map, env->me_mapsize);
3878 env->me_mapsize = size;
3879 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3880 rc = mdb_env_map(env, old);
3884 env->me_mapsize = size;
3886 env->me_maxpg = env->me_mapsize / env->me_psize;
3891 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3895 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3900 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3902 if (env->me_map || readers < 1)
3904 env->me_maxreaders = readers;
3909 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3911 if (!env || !readers)
3913 *readers = env->me_maxreaders;
3918 mdb_fsize(HANDLE fd, size_t *size)
3921 LARGE_INTEGER fsize;
3923 if (!GetFileSizeEx(fd, &fsize))
3926 *size = fsize.QuadPart;
3938 #ifdef BROKEN_FDATASYNC
3939 #include <sys/utsname.h>
3940 #include <sys/vfs.h>
3943 /** Further setup required for opening an LMDB environment
3946 mdb_env_open2(MDB_env *env)
3948 unsigned int flags = env->me_flags;
3949 int i, newenv = 0, rc;
3953 /* See if we should use QueryLimited */
3955 if ((rc & 0xff) > 5)
3956 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3958 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3961 #ifdef BROKEN_FDATASYNC
3962 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
3963 * https://lkml.org/lkml/2012/9/3/83
3964 * Kernels after 3.6-rc6 are known good.
3965 * https://lkml.org/lkml/2012/9/10/556
3966 * See if the DB is on ext3/ext4, then check for new enough kernel
3967 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
3972 fstatfs(env->me_fd, &st);
3973 while (st.f_type == 0xEF53) {
3977 if (uts.release[0] < '3') {
3978 if (!strncmp(uts.release, "2.6.32.", 7)) {
3979 i = atoi(uts.release+7);
3981 break; /* 2.6.32.60 and newer is OK */
3982 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
3983 i = atoi(uts.release+7);
3985 break; /* 2.6.34.15 and newer is OK */
3987 } else if (uts.release[0] == '3') {
3988 i = atoi(uts.release+2);
3990 break; /* 3.6 and newer is OK */
3992 i = atoi(uts.release+4);
3994 break; /* 3.5.4 and newer is OK */
3995 } else if (i == 2) {
3996 i = atoi(uts.release+4);
3998 break; /* 3.2.30 and newer is OK */
4000 } else { /* 4.x and newer is OK */
4003 env->me_fsynconly = 1;
4009 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4012 DPUTS("new mdbenv");
4014 env->me_psize = env->me_os_psize;
4015 if (env->me_psize > MAX_PAGESIZE)
4016 env->me_psize = MAX_PAGESIZE;
4017 memset(&meta, 0, sizeof(meta));
4018 mdb_env_init_meta0(env, &meta);
4019 meta.mm_mapsize = DEFAULT_MAPSIZE;
4021 env->me_psize = meta.mm_psize;
4024 /* Was a mapsize configured? */
4025 if (!env->me_mapsize) {
4026 env->me_mapsize = meta.mm_mapsize;
4029 /* Make sure mapsize >= committed data size. Even when using
4030 * mm_mapsize, which could be broken in old files (ITS#7789).
4032 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4033 if (env->me_mapsize < minsize)
4034 env->me_mapsize = minsize;
4036 meta.mm_mapsize = env->me_mapsize;
4038 if (newenv && !(flags & MDB_FIXEDMAP)) {
4039 /* mdb_env_map() may grow the datafile. Write the metapages
4040 * first, so the file will be valid if initialization fails.
4041 * Except with FIXEDMAP, since we do not yet know mm_address.
4042 * We could fill in mm_address later, but then a different
4043 * program might end up doing that - one with a memory layout
4044 * and map address which does not suit the main program.
4046 rc = mdb_env_init_meta(env, &meta);
4052 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4057 if (flags & MDB_FIXEDMAP)
4058 meta.mm_address = env->me_map;
4059 i = mdb_env_init_meta(env, &meta);
4060 if (i != MDB_SUCCESS) {
4065 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4066 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4068 #if !(MDB_MAXKEYSIZE)
4069 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4071 env->me_maxpg = env->me_mapsize / env->me_psize;
4075 int toggle = mdb_env_pick_meta(env);
4076 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
4078 DPRINTF(("opened database version %u, pagesize %u",
4079 env->me_metas[0]->mm_version, env->me_psize));
4080 DPRINTF(("using meta page %d", toggle));
4081 DPRINTF(("depth: %u", db->md_depth));
4082 DPRINTF(("entries: %"Z"u", db->md_entries));
4083 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
4084 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
4085 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
4086 DPRINTF(("root: %"Z"u", db->md_root));
4094 /** Release a reader thread's slot in the reader lock table.
4095 * This function is called automatically when a thread exits.
4096 * @param[in] ptr This points to the slot in the reader lock table.
4099 mdb_env_reader_dest(void *ptr)
4101 MDB_reader *reader = ptr;
4107 /** Junk for arranging thread-specific callbacks on Windows. This is
4108 * necessarily platform and compiler-specific. Windows supports up
4109 * to 1088 keys. Let's assume nobody opens more than 64 environments
4110 * in a single process, for now. They can override this if needed.
4112 #ifndef MAX_TLS_KEYS
4113 #define MAX_TLS_KEYS 64
4115 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4116 static int mdb_tls_nkeys;
4118 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4122 case DLL_PROCESS_ATTACH: break;
4123 case DLL_THREAD_ATTACH: break;
4124 case DLL_THREAD_DETACH:
4125 for (i=0; i<mdb_tls_nkeys; i++) {
4126 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4128 mdb_env_reader_dest(r);
4132 case DLL_PROCESS_DETACH: break;
4137 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4139 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4143 /* Force some symbol references.
4144 * _tls_used forces the linker to create the TLS directory if not already done
4145 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4147 #pragma comment(linker, "/INCLUDE:_tls_used")
4148 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4149 #pragma const_seg(".CRT$XLB")
4150 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4151 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4154 #pragma comment(linker, "/INCLUDE:__tls_used")
4155 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4156 #pragma data_seg(".CRT$XLB")
4157 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4159 #endif /* WIN 32/64 */
4160 #endif /* !__GNUC__ */
4163 /** Downgrade the exclusive lock on the region back to shared */
4165 mdb_env_share_locks(MDB_env *env, int *excl)
4167 int rc = 0, toggle = mdb_env_pick_meta(env);
4169 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
4174 /* First acquire a shared lock. The Unlock will
4175 * then release the existing exclusive lock.
4177 memset(&ov, 0, sizeof(ov));
4178 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4181 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4187 struct flock lock_info;
4188 /* The shared lock replaces the existing lock */
4189 memset((void *)&lock_info, 0, sizeof(lock_info));
4190 lock_info.l_type = F_RDLCK;
4191 lock_info.l_whence = SEEK_SET;
4192 lock_info.l_start = 0;
4193 lock_info.l_len = 1;
4194 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4195 (rc = ErrCode()) == EINTR) ;
4196 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4203 /** Try to get exclusive lock, otherwise shared.
4204 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4207 mdb_env_excl_lock(MDB_env *env, int *excl)
4211 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4215 memset(&ov, 0, sizeof(ov));
4216 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4223 struct flock lock_info;
4224 memset((void *)&lock_info, 0, sizeof(lock_info));
4225 lock_info.l_type = F_WRLCK;
4226 lock_info.l_whence = SEEK_SET;
4227 lock_info.l_start = 0;
4228 lock_info.l_len = 1;
4229 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4230 (rc = ErrCode()) == EINTR) ;
4234 # ifdef MDB_USE_SYSV_SEM
4235 if (*excl < 0) /* always true when !MDB_USE_SYSV_SEM */
4238 lock_info.l_type = F_RDLCK;
4239 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4240 (rc = ErrCode()) == EINTR) ;
4250 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4252 * @(#) $Revision: 5.1 $
4253 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4254 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4256 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4260 * Please do not copyright this code. This code is in the public domain.
4262 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4263 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4264 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4265 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4266 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4267 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4268 * PERFORMANCE OF THIS SOFTWARE.
4271 * chongo <Landon Curt Noll> /\oo/\
4272 * http://www.isthe.com/chongo/
4274 * Share and Enjoy! :-)
4277 typedef unsigned long long mdb_hash_t;
4278 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4280 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4281 * @param[in] val value to hash
4282 * @param[in] hval initial value for hash
4283 * @return 64 bit hash
4285 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4286 * hval arg on the first call.
4289 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4291 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4292 unsigned char *end = s + val->mv_size;
4294 * FNV-1a hash each octet of the string
4297 /* xor the bottom with the current octet */
4298 hval ^= (mdb_hash_t)*s++;
4300 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4301 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4302 (hval << 7) + (hval << 8) + (hval << 40);
4304 /* return our new hash value */
4308 /** Hash the string and output the encoded hash.
4309 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4310 * very short name limits. We don't care about the encoding being reversible,
4311 * we just want to preserve as many bits of the input as possible in a
4312 * small printable string.
4313 * @param[in] str string to hash
4314 * @param[out] encbuf an array of 11 chars to hold the hash
4316 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4319 mdb_pack85(unsigned long l, char *out)
4323 for (i=0; i<5; i++) {
4324 *out++ = mdb_a85[l % 85];
4330 mdb_hash_enc(MDB_val *val, char *encbuf)
4332 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4334 mdb_pack85(h, encbuf);
4335 mdb_pack85(h>>32, encbuf+5);
4340 /** Open and/or initialize the lock region for the environment.
4341 * @param[in] env The LMDB environment.
4342 * @param[in] lpath The pathname of the file used for the lock region.
4343 * @param[in] mode The Unix permissions for the file, if we create it.
4344 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4345 * @return 0 on success, non-zero on failure.
4348 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4351 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4353 # define MDB_ERRCODE_ROFS EROFS
4354 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4355 # define MDB_CLOEXEC O_CLOEXEC
4358 # define MDB_CLOEXEC 0
4365 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
4366 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4367 FILE_ATTRIBUTE_NORMAL, NULL);
4369 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4371 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4373 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4378 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4379 /* Lose record locks when exec*() */
4380 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4381 fcntl(env->me_lfd, F_SETFD, fdflags);
4384 if (!(env->me_flags & MDB_NOTLS)) {
4385 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4388 env->me_flags |= MDB_ENV_TXKEY;
4390 /* Windows TLS callbacks need help finding their TLS info. */
4391 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4395 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4399 /* Try to get exclusive lock. If we succeed, then
4400 * nobody is using the lock region and we should initialize it.
4402 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4405 size = GetFileSize(env->me_lfd, NULL);
4407 size = lseek(env->me_lfd, 0, SEEK_END);
4408 if (size == -1) goto fail_errno;
4410 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4411 if (size < rsize && *excl > 0) {
4413 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4414 || !SetEndOfFile(env->me_lfd))
4417 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4421 size = rsize - sizeof(MDB_txninfo);
4422 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4427 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4429 if (!mh) goto fail_errno;
4430 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4432 if (!env->me_txns) goto fail_errno;
4434 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4436 if (m == MAP_FAILED) goto fail_errno;
4442 BY_HANDLE_FILE_INFORMATION stbuf;
4451 if (!mdb_sec_inited) {
4452 InitializeSecurityDescriptor(&mdb_null_sd,
4453 SECURITY_DESCRIPTOR_REVISION);
4454 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4455 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4456 mdb_all_sa.bInheritHandle = FALSE;
4457 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4460 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4461 idbuf.volume = stbuf.dwVolumeSerialNumber;
4462 idbuf.nhigh = stbuf.nFileIndexHigh;
4463 idbuf.nlow = stbuf.nFileIndexLow;
4464 val.mv_data = &idbuf;
4465 val.mv_size = sizeof(idbuf);
4466 mdb_hash_enc(&val, encbuf);
4467 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4468 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4469 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4470 if (!env->me_rmutex) goto fail_errno;
4471 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4472 if (!env->me_wmutex) goto fail_errno;
4473 #elif defined(MDB_USE_SYSV_SEM)
4475 unsigned short vals[2] = {1, 1};
4476 int semid = semget(IPC_PRIVATE, 2, mode);
4480 env->me_rmutex.semid = semid;
4481 env->me_wmutex.semid = semid;
4482 env->me_rmutex.semnum = 0;
4483 env->me_wmutex.semnum = 1;
4486 if (semctl(semid, 0, SETALL, semu) < 0)
4488 env->me_txns->mti_semid = semid;
4489 #else /* MDB_USE_SYSV_SEM */
4490 pthread_mutexattr_t mattr;
4492 if ((rc = pthread_mutexattr_init(&mattr))
4493 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4494 #ifdef MDB_ROBUST_SUPPORTED
4495 || (rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST))
4497 || (rc = pthread_mutex_init(&env->me_txns->mti_rmutex, &mattr))
4498 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
4500 pthread_mutexattr_destroy(&mattr);
4501 #endif /* _WIN32 || MDB_USE_SYSV_SEM */
4503 env->me_txns->mti_magic = MDB_MAGIC;
4504 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4505 env->me_txns->mti_txnid = 0;
4506 env->me_txns->mti_numreaders = 0;
4509 #ifdef MDB_USE_SYSV_SEM
4510 struct semid_ds buf;
4514 if (env->me_txns->mti_magic != MDB_MAGIC) {
4515 DPUTS("lock region has invalid magic");
4519 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4520 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4521 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4522 rc = MDB_VERSION_MISMATCH;
4526 if (rc && rc != EACCES && rc != EAGAIN) {
4530 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4531 if (!env->me_rmutex) goto fail_errno;
4532 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4533 if (!env->me_wmutex) goto fail_errno;
4534 #elif defined(MDB_USE_SYSV_SEM)
4535 semid = env->me_txns->mti_semid;
4538 /* check for read access */
4539 if (semctl(semid, 0, IPC_STAT, semu) < 0)
4541 /* check for write access */
4542 if (semctl(semid, 0, IPC_SET, semu) < 0)
4545 env->me_rmutex.semid = semid;
4546 env->me_wmutex.semid = semid;
4547 env->me_rmutex.semnum = 0;
4548 env->me_wmutex.semnum = 1;
4559 /** The name of the lock file in the DB environment */
4560 #define LOCKNAME "/lock.mdb"
4561 /** The name of the data file in the DB environment */
4562 #define DATANAME "/data.mdb"
4563 /** The suffix of the lock file when no subdir is used */
4564 #define LOCKSUFF "-lock"
4565 /** Only a subset of the @ref mdb_env flags can be changed
4566 * at runtime. Changing other flags requires closing the
4567 * environment and re-opening it with the new flags.
4569 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4570 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
4571 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4573 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4574 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4578 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4580 int oflags, rc, len, excl = -1;
4581 char *lpath, *dpath;
4583 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4587 if (flags & MDB_NOSUBDIR) {
4588 rc = len + sizeof(LOCKSUFF) + len + 1;
4590 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4595 if (flags & MDB_NOSUBDIR) {
4596 dpath = lpath + len + sizeof(LOCKSUFF);
4597 sprintf(lpath, "%s" LOCKSUFF, path);
4598 strcpy(dpath, path);
4600 dpath = lpath + len + sizeof(LOCKNAME);
4601 sprintf(lpath, "%s" LOCKNAME, path);
4602 sprintf(dpath, "%s" DATANAME, path);
4606 flags |= env->me_flags;
4607 if (flags & MDB_RDONLY) {
4608 /* silently ignore WRITEMAP when we're only getting read access */
4609 flags &= ~MDB_WRITEMAP;
4611 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4612 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4615 env->me_flags = flags |= MDB_ENV_ACTIVE;
4619 env->me_path = strdup(path);
4620 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4621 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4622 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4623 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4628 /* For RDONLY, get lockfile after we know datafile exists */
4629 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4630 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4636 if (F_ISSET(flags, MDB_RDONLY)) {
4637 oflags = GENERIC_READ;
4638 len = OPEN_EXISTING;
4640 oflags = GENERIC_READ|GENERIC_WRITE;
4643 mode = FILE_ATTRIBUTE_NORMAL;
4644 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4645 NULL, len, mode, NULL);
4647 if (F_ISSET(flags, MDB_RDONLY))
4650 oflags = O_RDWR | O_CREAT;
4652 env->me_fd = open(dpath, oflags, mode);
4654 if (env->me_fd == INVALID_HANDLE_VALUE) {
4659 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4660 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4665 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4666 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4667 env->me_mfd = env->me_fd;
4669 /* Synchronous fd for meta writes. Needed even with
4670 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4673 len = OPEN_EXISTING;
4674 env->me_mfd = CreateFile(dpath, oflags,
4675 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4676 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4679 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4681 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4686 DPRINTF(("opened dbenv %p", (void *) env));
4688 rc = mdb_env_share_locks(env, &excl);
4692 if (!((flags & MDB_RDONLY) ||
4693 (env->me_pbuf = calloc(1, env->me_psize))))
4695 if (!(flags & MDB_RDONLY)) {
4697 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
4698 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
4699 txn = calloc(1, size);
4701 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
4702 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
4703 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
4704 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
4706 txn->mt_dbxs = env->me_dbxs;
4716 mdb_env_close0(env, excl);
4722 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4724 mdb_env_close0(MDB_env *env, int excl)
4728 if (!(env->me_flags & MDB_ENV_ACTIVE))
4731 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4732 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4733 free(env->me_dbxs[i].md_name.mv_data);
4736 free(env->me_dbiseqs);
4737 free(env->me_dbflags);
4740 free(env->me_dirty_list);
4742 mdb_midl_free(env->me_free_pgs);
4744 if (env->me_flags & MDB_ENV_TXKEY) {
4745 pthread_key_delete(env->me_txkey);
4747 /* Delete our key from the global list */
4748 for (i=0; i<mdb_tls_nkeys; i++)
4749 if (mdb_tls_keys[i] == env->me_txkey) {
4750 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4758 munmap(env->me_map, env->me_mapsize);
4760 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4761 (void) close(env->me_mfd);
4762 if (env->me_fd != INVALID_HANDLE_VALUE)
4763 (void) close(env->me_fd);
4765 MDB_PID_T pid = env->me_pid;
4766 /* Clearing readers is done in this function because
4767 * me_txkey with its destructor must be disabled first.
4769 for (i = env->me_numreaders; --i >= 0; )
4770 if (env->me_txns->mti_readers[i].mr_pid == pid)
4771 env->me_txns->mti_readers[i].mr_pid = 0;
4773 if (env->me_rmutex) {
4774 CloseHandle(env->me_rmutex);
4775 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4777 /* Windows automatically destroys the mutexes when
4778 * the last handle closes.
4780 #elif defined(MDB_USE_SYSV_SEM)
4781 if (env->me_rmutex.semid != -1) {
4782 /* If we have the filelock: If we are the
4783 * only remaining user, clean up semaphores.
4786 mdb_env_excl_lock(env, &excl);
4788 semctl(env->me_rmutex.semid, 0, IPC_RMID);
4791 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4793 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4796 /* Unlock the lockfile. Windows would have unlocked it
4797 * after closing anyway, but not necessarily at once.
4799 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4802 (void) close(env->me_lfd);
4805 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4809 mdb_env_close(MDB_env *env)
4816 VGMEMP_DESTROY(env);
4817 while ((dp = env->me_dpages) != NULL) {
4818 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4819 env->me_dpages = dp->mp_next;
4823 mdb_env_close0(env, 0);
4827 /** Compare two items pointing at aligned size_t's */
4829 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4831 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4832 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4835 /** Compare two items pointing at aligned unsigned int's */
4837 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4839 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4840 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4843 /** Compare two items pointing at unsigned ints of unknown alignment.
4844 * Nodes and keys are guaranteed to be 2-byte aligned.
4847 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4849 #if BYTE_ORDER == LITTLE_ENDIAN
4850 unsigned short *u, *c;
4853 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4854 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4857 } while(!x && u > (unsigned short *)a->mv_data);
4860 unsigned short *u, *c, *end;
4863 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4864 u = (unsigned short *)a->mv_data;
4865 c = (unsigned short *)b->mv_data;
4868 } while(!x && u < end);
4873 /** Compare two items pointing at size_t's of unknown alignment. */
4874 #ifdef MISALIGNED_OK
4875 # define mdb_cmp_clong mdb_cmp_long
4877 # define mdb_cmp_clong mdb_cmp_cint
4880 /** Compare two items lexically */
4882 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4889 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4895 diff = memcmp(a->mv_data, b->mv_data, len);
4896 return diff ? diff : len_diff<0 ? -1 : len_diff;
4899 /** Compare two items in reverse byte order */
4901 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4903 const unsigned char *p1, *p2, *p1_lim;
4907 p1_lim = (const unsigned char *)a->mv_data;
4908 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4909 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4911 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4917 while (p1 > p1_lim) {
4918 diff = *--p1 - *--p2;
4922 return len_diff<0 ? -1 : len_diff;
4925 /** Search for key within a page, using binary search.
4926 * Returns the smallest entry larger or equal to the key.
4927 * If exactp is non-null, stores whether the found entry was an exact match
4928 * in *exactp (1 or 0).
4929 * Updates the cursor index with the index of the found entry.
4930 * If no entry larger or equal to the key is found, returns NULL.
4933 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4935 unsigned int i = 0, nkeys;
4938 MDB_page *mp = mc->mc_pg[mc->mc_top];
4939 MDB_node *node = NULL;
4944 nkeys = NUMKEYS(mp);
4946 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4947 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4950 low = IS_LEAF(mp) ? 0 : 1;
4952 cmp = mc->mc_dbx->md_cmp;
4954 /* Branch pages have no data, so if using integer keys,
4955 * alignment is guaranteed. Use faster mdb_cmp_int.
4957 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4958 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4965 nodekey.mv_size = mc->mc_db->md_pad;
4966 node = NODEPTR(mp, 0); /* fake */
4967 while (low <= high) {
4968 i = (low + high) >> 1;
4969 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4970 rc = cmp(key, &nodekey);
4971 DPRINTF(("found leaf index %u [%s], rc = %i",
4972 i, DKEY(&nodekey), rc));
4981 while (low <= high) {
4982 i = (low + high) >> 1;
4984 node = NODEPTR(mp, i);
4985 nodekey.mv_size = NODEKSZ(node);
4986 nodekey.mv_data = NODEKEY(node);
4988 rc = cmp(key, &nodekey);
4991 DPRINTF(("found leaf index %u [%s], rc = %i",
4992 i, DKEY(&nodekey), rc));
4994 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4995 i, DKEY(&nodekey), NODEPGNO(node), rc));
5006 if (rc > 0) { /* Found entry is less than the key. */
5007 i++; /* Skip to get the smallest entry larger than key. */
5009 node = NODEPTR(mp, i);
5012 *exactp = (rc == 0 && nkeys > 0);
5013 /* store the key index */
5014 mc->mc_ki[mc->mc_top] = i;
5016 /* There is no entry larger or equal to the key. */
5019 /* nodeptr is fake for LEAF2 */
5025 mdb_cursor_adjust(MDB_cursor *mc, func)
5029 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5030 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5037 /** Pop a page off the top of the cursor's stack. */
5039 mdb_cursor_pop(MDB_cursor *mc)
5043 MDB_page *top = mc->mc_pg[mc->mc_top];
5049 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
5050 DDBI(mc), (void *) mc));
5054 /** Push a page onto the top of the cursor's stack. */
5056 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5058 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
5059 DDBI(mc), (void *) mc));
5061 if (mc->mc_snum >= CURSOR_STACK) {
5062 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5063 return MDB_CURSOR_FULL;
5066 mc->mc_top = mc->mc_snum++;
5067 mc->mc_pg[mc->mc_top] = mp;
5068 mc->mc_ki[mc->mc_top] = 0;
5073 /** Find the address of the page corresponding to a given page number.
5074 * @param[in] txn the transaction for this access.
5075 * @param[in] pgno the page number for the page to retrieve.
5076 * @param[out] ret address of a pointer where the page's address will be stored.
5077 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5078 * @return 0 on success, non-zero on failure.
5081 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
5083 MDB_env *env = txn->mt_env;
5087 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
5091 MDB_ID2L dl = tx2->mt_u.dirty_list;
5093 /* Spilled pages were dirtied in this txn and flushed
5094 * because the dirty list got full. Bring this page
5095 * back in from the map (but don't unspill it here,
5096 * leave that unless page_touch happens again).
5098 if (tx2->mt_spill_pgs) {
5099 MDB_ID pn = pgno << 1;
5100 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5101 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5102 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5107 unsigned x = mdb_mid2l_search(dl, pgno);
5108 if (x <= dl[0].mid && dl[x].mid == pgno) {
5114 } while ((tx2 = tx2->mt_parent) != NULL);
5117 if (pgno < txn->mt_next_pgno) {
5119 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5121 DPRINTF(("page %"Z"u not found", pgno));
5122 txn->mt_flags |= MDB_TXN_ERROR;
5123 return MDB_PAGE_NOTFOUND;
5133 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
5134 * The cursor is at the root page, set up the rest of it.
5137 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
5139 MDB_page *mp = mc->mc_pg[mc->mc_top];
5143 while (IS_BRANCH(mp)) {
5147 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
5148 mdb_cassert(mc, NUMKEYS(mp) > 1);
5149 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
5151 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
5153 if (flags & MDB_PS_LAST)
5154 i = NUMKEYS(mp) - 1;
5157 node = mdb_node_search(mc, key, &exact);
5159 i = NUMKEYS(mp) - 1;
5161 i = mc->mc_ki[mc->mc_top];
5163 mdb_cassert(mc, i > 0);
5167 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
5170 mdb_cassert(mc, i < NUMKEYS(mp));
5171 node = NODEPTR(mp, i);
5173 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5176 mc->mc_ki[mc->mc_top] = i;
5177 if ((rc = mdb_cursor_push(mc, mp)))
5180 if (flags & MDB_PS_MODIFY) {
5181 if ((rc = mdb_page_touch(mc)) != 0)
5183 mp = mc->mc_pg[mc->mc_top];
5188 DPRINTF(("internal error, index points to a %02X page!?",
5190 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5191 return MDB_CORRUPTED;
5194 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
5195 key ? DKEY(key) : "null"));
5196 mc->mc_flags |= C_INITIALIZED;
5197 mc->mc_flags &= ~C_EOF;
5202 /** Search for the lowest key under the current branch page.
5203 * This just bypasses a NUMKEYS check in the current page
5204 * before calling mdb_page_search_root(), because the callers
5205 * are all in situations where the current page is known to
5209 mdb_page_search_lowest(MDB_cursor *mc)
5211 MDB_page *mp = mc->mc_pg[mc->mc_top];
5212 MDB_node *node = NODEPTR(mp, 0);
5215 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5218 mc->mc_ki[mc->mc_top] = 0;
5219 if ((rc = mdb_cursor_push(mc, mp)))
5221 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5224 /** Search for the page a given key should be in.
5225 * Push it and its parent pages on the cursor stack.
5226 * @param[in,out] mc the cursor for this operation.
5227 * @param[in] key the key to search for, or NULL for first/last page.
5228 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5229 * are touched (updated with new page numbers).
5230 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5231 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5232 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5233 * @return 0 on success, non-zero on failure.
5236 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5241 /* Make sure the txn is still viable, then find the root from
5242 * the txn's db table and set it as the root of the cursor's stack.
5244 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
5245 DPUTS("transaction has failed, must abort");
5248 /* Make sure we're using an up-to-date root */
5249 if (*mc->mc_dbflag & DB_STALE) {
5251 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5253 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5254 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5261 MDB_node *leaf = mdb_node_search(&mc2,
5262 &mc->mc_dbx->md_name, &exact);
5264 return MDB_NOTFOUND;
5265 rc = mdb_node_read(mc->mc_txn, leaf, &data);
5268 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5270 /* The txn may not know this DBI, or another process may
5271 * have dropped and recreated the DB with other flags.
5273 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5274 return MDB_INCOMPATIBLE;
5275 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5277 *mc->mc_dbflag &= ~DB_STALE;
5279 root = mc->mc_db->md_root;
5281 if (root == P_INVALID) { /* Tree is empty. */
5282 DPUTS("tree is empty");
5283 return MDB_NOTFOUND;
5287 mdb_cassert(mc, root > 1);
5288 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5289 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
5295 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5296 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5298 if (flags & MDB_PS_MODIFY) {
5299 if ((rc = mdb_page_touch(mc)))
5303 if (flags & MDB_PS_ROOTONLY)
5306 return mdb_page_search_root(mc, key, flags);
5310 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5312 MDB_txn *txn = mc->mc_txn;
5313 pgno_t pg = mp->mp_pgno;
5314 unsigned x = 0, ovpages = mp->mp_pages;
5315 MDB_env *env = txn->mt_env;
5316 MDB_IDL sl = txn->mt_spill_pgs;
5317 MDB_ID pn = pg << 1;
5320 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5321 /* If the page is dirty or on the spill list we just acquired it,
5322 * so we should give it back to our current free list, if any.
5323 * Otherwise put it onto the list of pages we freed in this txn.
5325 * Won't create me_pghead: me_pglast must be inited along with it.
5326 * Unsupported in nested txns: They would need to hide the page
5327 * range in ancestor txns' dirty and spilled lists.
5329 if (env->me_pghead &&
5331 ((mp->mp_flags & P_DIRTY) ||
5332 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5336 MDB_ID2 *dl, ix, iy;
5337 rc = mdb_midl_need(&env->me_pghead, ovpages);
5340 if (!(mp->mp_flags & P_DIRTY)) {
5341 /* This page is no longer spilled */
5348 /* Remove from dirty list */
5349 dl = txn->mt_u.dirty_list;
5351 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5357 mdb_cassert(mc, x > 1);
5359 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5360 txn->mt_flags |= MDB_TXN_ERROR;
5361 return MDB_CORRUPTED;
5364 if (!(env->me_flags & MDB_WRITEMAP))
5365 mdb_dpage_free(env, mp);
5367 /* Insert in me_pghead */
5368 mop = env->me_pghead;
5369 j = mop[0] + ovpages;
5370 for (i = mop[0]; i && mop[i] < pg; i--)
5376 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5380 mc->mc_db->md_overflow_pages -= ovpages;
5384 /** Return the data associated with a given node.
5385 * @param[in] txn The transaction for this operation.
5386 * @param[in] leaf The node being read.
5387 * @param[out] data Updated to point to the node's data.
5388 * @return 0 on success, non-zero on failure.
5391 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5393 MDB_page *omp; /* overflow page */
5397 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5398 data->mv_size = NODEDSZ(leaf);
5399 data->mv_data = NODEDATA(leaf);
5403 /* Read overflow data.
5405 data->mv_size = NODEDSZ(leaf);
5406 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5407 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5408 DPRINTF(("read overflow page %"Z"u failed", pgno));
5411 data->mv_data = METADATA(omp);
5417 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5418 MDB_val *key, MDB_val *data)
5425 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5427 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
5430 if (txn->mt_flags & MDB_TXN_ERROR)
5433 mdb_cursor_init(&mc, txn, dbi, &mx);
5434 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5437 /** Find a sibling for a page.
5438 * Replaces the page at the top of the cursor's stack with the
5439 * specified sibling, if one exists.
5440 * @param[in] mc The cursor for this operation.
5441 * @param[in] move_right Non-zero if the right sibling is requested,
5442 * otherwise the left sibling.
5443 * @return 0 on success, non-zero on failure.
5446 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5452 if (mc->mc_snum < 2) {
5453 return MDB_NOTFOUND; /* root has no siblings */
5457 DPRINTF(("parent page is page %"Z"u, index %u",
5458 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5460 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5461 : (mc->mc_ki[mc->mc_top] == 0)) {
5462 DPRINTF(("no more keys left, moving to %s sibling",
5463 move_right ? "right" : "left"));
5464 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5465 /* undo cursor_pop before returning */
5472 mc->mc_ki[mc->mc_top]++;
5474 mc->mc_ki[mc->mc_top]--;
5475 DPRINTF(("just moving to %s index key %u",
5476 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5478 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5480 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5481 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5482 /* mc will be inconsistent if caller does mc_snum++ as above */
5483 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5487 mdb_cursor_push(mc, mp);
5489 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5494 /** Move the cursor to the next data item. */
5496 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5502 if (mc->mc_flags & C_EOF) {
5503 return MDB_NOTFOUND;
5506 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5508 mp = mc->mc_pg[mc->mc_top];
5510 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5511 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5512 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5513 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5514 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5515 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5516 if (rc == MDB_SUCCESS)
5517 MDB_GET_KEY(leaf, key);
5522 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5523 if (op == MDB_NEXT_DUP)
5524 return MDB_NOTFOUND;
5528 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5529 mdb_dbg_pgno(mp), (void *) mc));
5530 if (mc->mc_flags & C_DEL)
5533 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5534 DPUTS("=====> move to next sibling page");
5535 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5536 mc->mc_flags |= C_EOF;
5539 mp = mc->mc_pg[mc->mc_top];
5540 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5542 mc->mc_ki[mc->mc_top]++;
5545 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5546 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5549 key->mv_size = mc->mc_db->md_pad;
5550 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5554 mdb_cassert(mc, IS_LEAF(mp));
5555 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5557 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5558 mdb_xcursor_init1(mc, leaf);
5561 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5564 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5565 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5566 if (rc != MDB_SUCCESS)
5571 MDB_GET_KEY(leaf, key);
5575 /** Move the cursor to the previous data item. */
5577 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5583 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5585 mp = mc->mc_pg[mc->mc_top];
5587 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5588 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5589 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5590 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5591 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5592 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5593 if (rc == MDB_SUCCESS) {
5594 MDB_GET_KEY(leaf, key);
5595 mc->mc_flags &= ~C_EOF;
5601 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5602 if (op == MDB_PREV_DUP)
5603 return MDB_NOTFOUND;
5607 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5608 mdb_dbg_pgno(mp), (void *) mc));
5610 if (mc->mc_ki[mc->mc_top] == 0) {
5611 DPUTS("=====> move to prev sibling page");
5612 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5615 mp = mc->mc_pg[mc->mc_top];
5616 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5617 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5619 mc->mc_ki[mc->mc_top]--;
5621 mc->mc_flags &= ~C_EOF;
5623 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5624 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5627 key->mv_size = mc->mc_db->md_pad;
5628 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5632 mdb_cassert(mc, IS_LEAF(mp));
5633 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5635 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5636 mdb_xcursor_init1(mc, leaf);
5639 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5642 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5643 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5644 if (rc != MDB_SUCCESS)
5649 MDB_GET_KEY(leaf, key);
5653 /** Set the cursor on a specific data item. */
5655 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5656 MDB_cursor_op op, int *exactp)
5660 MDB_node *leaf = NULL;
5663 if (key->mv_size == 0)
5664 return MDB_BAD_VALSIZE;
5667 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5669 /* See if we're already on the right page */
5670 if (mc->mc_flags & C_INITIALIZED) {
5673 mp = mc->mc_pg[mc->mc_top];
5675 mc->mc_ki[mc->mc_top] = 0;
5676 return MDB_NOTFOUND;
5678 if (mp->mp_flags & P_LEAF2) {
5679 nodekey.mv_size = mc->mc_db->md_pad;
5680 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5682 leaf = NODEPTR(mp, 0);
5683 MDB_GET_KEY2(leaf, nodekey);
5685 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5687 /* Probably happens rarely, but first node on the page
5688 * was the one we wanted.
5690 mc->mc_ki[mc->mc_top] = 0;
5697 unsigned int nkeys = NUMKEYS(mp);
5699 if (mp->mp_flags & P_LEAF2) {
5700 nodekey.mv_data = LEAF2KEY(mp,
5701 nkeys-1, nodekey.mv_size);
5703 leaf = NODEPTR(mp, nkeys-1);
5704 MDB_GET_KEY2(leaf, nodekey);
5706 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5708 /* last node was the one we wanted */
5709 mc->mc_ki[mc->mc_top] = nkeys-1;
5715 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5716 /* This is definitely the right page, skip search_page */
5717 if (mp->mp_flags & P_LEAF2) {
5718 nodekey.mv_data = LEAF2KEY(mp,
5719 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5721 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5722 MDB_GET_KEY2(leaf, nodekey);
5724 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5726 /* current node was the one we wanted */
5736 /* If any parents have right-sibs, search.
5737 * Otherwise, there's nothing further.
5739 for (i=0; i<mc->mc_top; i++)
5741 NUMKEYS(mc->mc_pg[i])-1)
5743 if (i == mc->mc_top) {
5744 /* There are no other pages */
5745 mc->mc_ki[mc->mc_top] = nkeys;
5746 return MDB_NOTFOUND;
5750 /* There are no other pages */
5751 mc->mc_ki[mc->mc_top] = 0;
5752 if (op == MDB_SET_RANGE && !exactp) {
5756 return MDB_NOTFOUND;
5760 rc = mdb_page_search(mc, key, 0);
5761 if (rc != MDB_SUCCESS)
5764 mp = mc->mc_pg[mc->mc_top];
5765 mdb_cassert(mc, IS_LEAF(mp));
5768 leaf = mdb_node_search(mc, key, exactp);
5769 if (exactp != NULL && !*exactp) {
5770 /* MDB_SET specified and not an exact match. */
5771 return MDB_NOTFOUND;
5775 DPUTS("===> inexact leaf not found, goto sibling");
5776 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5777 return rc; /* no entries matched */
5778 mp = mc->mc_pg[mc->mc_top];
5779 mdb_cassert(mc, IS_LEAF(mp));
5780 leaf = NODEPTR(mp, 0);
5784 mc->mc_flags |= C_INITIALIZED;
5785 mc->mc_flags &= ~C_EOF;
5788 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5789 key->mv_size = mc->mc_db->md_pad;
5790 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5795 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5796 mdb_xcursor_init1(mc, leaf);
5799 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5800 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5801 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5804 if (op == MDB_GET_BOTH) {
5810 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5811 if (rc != MDB_SUCCESS)
5814 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5816 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5818 rc = mc->mc_dbx->md_dcmp(data, &d2);
5820 if (op == MDB_GET_BOTH || rc > 0)
5821 return MDB_NOTFOUND;
5828 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5829 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5834 /* The key already matches in all other cases */
5835 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5836 MDB_GET_KEY(leaf, key);
5837 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5842 /** Move the cursor to the first item in the database. */
5844 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5850 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5852 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5853 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5854 if (rc != MDB_SUCCESS)
5857 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5859 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5860 mc->mc_flags |= C_INITIALIZED;
5861 mc->mc_flags &= ~C_EOF;
5863 mc->mc_ki[mc->mc_top] = 0;
5865 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5866 key->mv_size = mc->mc_db->md_pad;
5867 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5872 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5873 mdb_xcursor_init1(mc, leaf);
5874 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5878 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5882 MDB_GET_KEY(leaf, key);
5886 /** Move the cursor to the last item in the database. */
5888 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5894 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5896 if (!(mc->mc_flags & C_EOF)) {
5898 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5899 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5900 if (rc != MDB_SUCCESS)
5903 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5906 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5907 mc->mc_flags |= C_INITIALIZED|C_EOF;
5908 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5910 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5911 key->mv_size = mc->mc_db->md_pad;
5912 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5917 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5918 mdb_xcursor_init1(mc, leaf);
5919 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5923 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5928 MDB_GET_KEY(leaf, key);
5933 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5938 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5943 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5947 case MDB_GET_CURRENT:
5948 if (!(mc->mc_flags & C_INITIALIZED)) {
5951 MDB_page *mp = mc->mc_pg[mc->mc_top];
5952 int nkeys = NUMKEYS(mp);
5953 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5954 mc->mc_ki[mc->mc_top] = nkeys;
5960 key->mv_size = mc->mc_db->md_pad;
5961 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5963 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5964 MDB_GET_KEY(leaf, key);
5966 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5967 if (mc->mc_flags & C_DEL)
5968 mdb_xcursor_init1(mc, leaf);
5969 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5971 rc = mdb_node_read(mc->mc_txn, leaf, data);
5978 case MDB_GET_BOTH_RANGE:
5983 if (mc->mc_xcursor == NULL) {
5984 rc = MDB_INCOMPATIBLE;
5994 rc = mdb_cursor_set(mc, key, data, op,
5995 op == MDB_SET_RANGE ? NULL : &exact);
5998 case MDB_GET_MULTIPLE:
5999 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6003 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6004 rc = MDB_INCOMPATIBLE;
6008 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6009 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6012 case MDB_NEXT_MULTIPLE:
6017 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6018 rc = MDB_INCOMPATIBLE;
6021 if (!(mc->mc_flags & C_INITIALIZED))
6022 rc = mdb_cursor_first(mc, key, data);
6024 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6025 if (rc == MDB_SUCCESS) {
6026 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6029 mx = &mc->mc_xcursor->mx_cursor;
6030 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
6032 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
6033 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
6041 case MDB_NEXT_NODUP:
6042 if (!(mc->mc_flags & C_INITIALIZED))
6043 rc = mdb_cursor_first(mc, key, data);
6045 rc = mdb_cursor_next(mc, key, data, op);
6049 case MDB_PREV_NODUP:
6050 if (!(mc->mc_flags & C_INITIALIZED)) {
6051 rc = mdb_cursor_last(mc, key, data);
6054 mc->mc_flags |= C_INITIALIZED;
6055 mc->mc_ki[mc->mc_top]++;
6057 rc = mdb_cursor_prev(mc, key, data, op);
6060 rc = mdb_cursor_first(mc, key, data);
6063 mfunc = mdb_cursor_first;
6065 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6069 if (mc->mc_xcursor == NULL) {
6070 rc = MDB_INCOMPATIBLE;
6074 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6075 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6076 MDB_GET_KEY(leaf, key);
6077 rc = mdb_node_read(mc->mc_txn, leaf, data);
6081 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6085 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
6088 rc = mdb_cursor_last(mc, key, data);
6091 mfunc = mdb_cursor_last;
6094 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
6099 if (mc->mc_flags & C_DEL)
6100 mc->mc_flags ^= C_DEL;
6105 /** Touch all the pages in the cursor stack. Set mc_top.
6106 * Makes sure all the pages are writable, before attempting a write operation.
6107 * @param[in] mc The cursor to operate on.
6110 mdb_cursor_touch(MDB_cursor *mc)
6112 int rc = MDB_SUCCESS;
6114 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
6117 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6119 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
6120 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
6123 *mc->mc_dbflag |= DB_DIRTY;
6128 rc = mdb_page_touch(mc);
6129 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
6130 mc->mc_top = mc->mc_snum-1;
6135 /** Do not spill pages to disk if txn is getting full, may fail instead */
6136 #define MDB_NOSPILL 0x8000
6139 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6142 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
6144 MDB_node *leaf = NULL;
6147 MDB_val xdata, *rdata, dkey, olddata;
6149 int do_sub = 0, insert_key, insert_data;
6150 unsigned int mcount = 0, dcount = 0, nospill;
6153 unsigned int nflags;
6156 if (mc == NULL || key == NULL)
6159 env = mc->mc_txn->mt_env;
6161 /* Check this first so counter will always be zero on any
6164 if (flags & MDB_MULTIPLE) {
6165 dcount = data[1].mv_size;
6166 data[1].mv_size = 0;
6167 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
6168 return MDB_INCOMPATIBLE;
6171 nospill = flags & MDB_NOSPILL;
6172 flags &= ~MDB_NOSPILL;
6174 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6175 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6177 if (key->mv_size-1 >= ENV_MAXKEY(env))
6178 return MDB_BAD_VALSIZE;
6180 #if SIZE_MAX > MAXDATASIZE
6181 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
6182 return MDB_BAD_VALSIZE;
6184 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
6185 return MDB_BAD_VALSIZE;
6188 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
6189 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
6193 if (flags == MDB_CURRENT) {
6194 if (!(mc->mc_flags & C_INITIALIZED))
6197 } else if (mc->mc_db->md_root == P_INVALID) {
6198 /* new database, cursor has nothing to point to */
6201 mc->mc_flags &= ~C_INITIALIZED;
6206 if (flags & MDB_APPEND) {
6208 rc = mdb_cursor_last(mc, &k2, &d2);
6210 rc = mc->mc_dbx->md_cmp(key, &k2);
6213 mc->mc_ki[mc->mc_top]++;
6215 /* new key is <= last key */
6220 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6222 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6223 DPRINTF(("duplicate key [%s]", DKEY(key)));
6225 return MDB_KEYEXIST;
6227 if (rc && rc != MDB_NOTFOUND)
6231 if (mc->mc_flags & C_DEL)
6232 mc->mc_flags ^= C_DEL;
6234 /* Cursor is positioned, check for room in the dirty list */
6236 if (flags & MDB_MULTIPLE) {
6238 xdata.mv_size = data->mv_size * dcount;
6242 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6246 if (rc == MDB_NO_ROOT) {
6248 /* new database, write a root leaf page */
6249 DPUTS("allocating new root leaf page");
6250 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6253 mdb_cursor_push(mc, np);
6254 mc->mc_db->md_root = np->mp_pgno;
6255 mc->mc_db->md_depth++;
6256 *mc->mc_dbflag |= DB_DIRTY;
6257 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6259 np->mp_flags |= P_LEAF2;
6260 mc->mc_flags |= C_INITIALIZED;
6262 /* make sure all cursor pages are writable */
6263 rc2 = mdb_cursor_touch(mc);
6268 insert_key = insert_data = rc;
6270 /* The key does not exist */
6271 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6272 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6273 LEAFSIZE(key, data) > env->me_nodemax)
6275 /* Too big for a node, insert in sub-DB. Set up an empty
6276 * "old sub-page" for prep_subDB to expand to a full page.
6278 fp_flags = P_LEAF|P_DIRTY;
6280 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6281 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6282 olddata.mv_size = PAGEHDRSZ;
6286 /* there's only a key anyway, so this is a no-op */
6287 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6289 unsigned int ksize = mc->mc_db->md_pad;
6290 if (key->mv_size != ksize)
6291 return MDB_BAD_VALSIZE;
6292 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6293 memcpy(ptr, key->mv_data, ksize);
6295 /* if overwriting slot 0 of leaf, need to
6296 * update branch key if there is a parent page
6298 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6299 unsigned short top = mc->mc_top;
6301 /* slot 0 is always an empty key, find real slot */
6302 while (mc->mc_top && !mc->mc_ki[mc->mc_top])
6304 if (mc->mc_ki[mc->mc_top])
6305 rc2 = mdb_update_key(mc, key);
6316 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6317 olddata.mv_size = NODEDSZ(leaf);
6318 olddata.mv_data = NODEDATA(leaf);
6321 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6322 /* Prepare (sub-)page/sub-DB to accept the new item,
6323 * if needed. fp: old sub-page or a header faking
6324 * it. mp: new (sub-)page. offset: growth in page
6325 * size. xdata: node data with new page or DB.
6327 unsigned i, offset = 0;
6328 mp = fp = xdata.mv_data = env->me_pbuf;
6329 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6331 /* Was a single item before, must convert now */
6332 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6333 /* Just overwrite the current item */
6334 if (flags == MDB_CURRENT)
6337 #if UINT_MAX < SIZE_MAX
6338 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6339 mc->mc_dbx->md_dcmp = mdb_cmp_clong;
6341 /* does data match? */
6342 if (!mc->mc_dbx->md_dcmp(data, &olddata)) {
6343 if (flags & MDB_NODUPDATA)
6344 return MDB_KEYEXIST;
6349 /* Back up original data item */
6350 dkey.mv_size = olddata.mv_size;
6351 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6353 /* Make sub-page header for the dup items, with dummy body */
6354 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6355 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6356 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6357 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6358 fp->mp_flags |= P_LEAF2;
6359 fp->mp_pad = data->mv_size;
6360 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6362 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6363 (dkey.mv_size & 1) + (data->mv_size & 1);
6365 fp->mp_upper = xdata.mv_size - PAGEBASE;
6366 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6367 } else if (leaf->mn_flags & F_SUBDATA) {
6368 /* Data is on sub-DB, just store it */
6369 flags |= F_DUPDATA|F_SUBDATA;
6372 /* Data is on sub-page */
6373 fp = olddata.mv_data;
6376 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6377 offset = EVEN(NODESIZE + sizeof(indx_t) +
6381 offset = fp->mp_pad;
6382 if (SIZELEFT(fp) < offset) {
6383 offset *= 4; /* space for 4 more */
6386 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6388 fp->mp_flags |= P_DIRTY;
6389 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6390 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6394 xdata.mv_size = olddata.mv_size + offset;
6397 fp_flags = fp->mp_flags;
6398 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6399 /* Too big for a sub-page, convert to sub-DB */
6400 fp_flags &= ~P_SUBP;
6402 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6403 fp_flags |= P_LEAF2;
6404 dummy.md_pad = fp->mp_pad;
6405 dummy.md_flags = MDB_DUPFIXED;
6406 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6407 dummy.md_flags |= MDB_INTEGERKEY;
6413 dummy.md_branch_pages = 0;
6414 dummy.md_leaf_pages = 1;
6415 dummy.md_overflow_pages = 0;
6416 dummy.md_entries = NUMKEYS(fp);
6417 xdata.mv_size = sizeof(MDB_db);
6418 xdata.mv_data = &dummy;
6419 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6421 offset = env->me_psize - olddata.mv_size;
6422 flags |= F_DUPDATA|F_SUBDATA;
6423 dummy.md_root = mp->mp_pgno;
6426 mp->mp_flags = fp_flags | P_DIRTY;
6427 mp->mp_pad = fp->mp_pad;
6428 mp->mp_lower = fp->mp_lower;
6429 mp->mp_upper = fp->mp_upper + offset;
6430 if (fp_flags & P_LEAF2) {
6431 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6433 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6434 olddata.mv_size - fp->mp_upper - PAGEBASE);
6435 for (i=0; i<NUMKEYS(fp); i++)
6436 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6444 mdb_node_del(mc, 0);
6448 /* overflow page overwrites need special handling */
6449 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6452 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6454 memcpy(&pg, olddata.mv_data, sizeof(pg));
6455 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6457 ovpages = omp->mp_pages;
6459 /* Is the ov page large enough? */
6460 if (ovpages >= dpages) {
6461 if (!(omp->mp_flags & P_DIRTY) &&
6462 (level || (env->me_flags & MDB_WRITEMAP)))
6464 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6467 level = 0; /* dirty in this txn or clean */
6470 if (omp->mp_flags & P_DIRTY) {
6471 /* yes, overwrite it. Note in this case we don't
6472 * bother to try shrinking the page if the new data
6473 * is smaller than the overflow threshold.
6476 /* It is writable only in a parent txn */
6477 size_t sz = (size_t) env->me_psize * ovpages, off;
6478 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6484 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6485 mdb_cassert(mc, rc2 == 0);
6486 if (!(flags & MDB_RESERVE)) {
6487 /* Copy end of page, adjusting alignment so
6488 * compiler may copy words instead of bytes.
6490 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6491 memcpy((size_t *)((char *)np + off),
6492 (size_t *)((char *)omp + off), sz - off);
6495 memcpy(np, omp, sz); /* Copy beginning of page */
6498 SETDSZ(leaf, data->mv_size);
6499 if (F_ISSET(flags, MDB_RESERVE))
6500 data->mv_data = METADATA(omp);
6502 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6506 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6508 } else if (data->mv_size == olddata.mv_size) {
6509 /* same size, just replace it. Note that we could
6510 * also reuse this node if the new data is smaller,
6511 * but instead we opt to shrink the node in that case.
6513 if (F_ISSET(flags, MDB_RESERVE))
6514 data->mv_data = olddata.mv_data;
6515 else if (!(mc->mc_flags & C_SUB))
6516 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6518 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6523 mdb_node_del(mc, 0);
6529 nflags = flags & NODE_ADD_FLAGS;
6530 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6531 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6532 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6533 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6535 nflags |= MDB_SPLIT_REPLACE;
6536 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6538 /* There is room already in this leaf page. */
6539 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6540 if (rc == 0 && insert_key) {
6541 /* Adjust other cursors pointing to mp */
6542 MDB_cursor *m2, *m3;
6543 MDB_dbi dbi = mc->mc_dbi;
6544 unsigned i = mc->mc_top;
6545 MDB_page *mp = mc->mc_pg[i];
6547 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6548 if (mc->mc_flags & C_SUB)
6549 m3 = &m2->mc_xcursor->mx_cursor;
6552 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6553 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6560 if (rc == MDB_SUCCESS) {
6561 /* Now store the actual data in the child DB. Note that we're
6562 * storing the user data in the keys field, so there are strict
6563 * size limits on dupdata. The actual data fields of the child
6564 * DB are all zero size.
6572 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6573 if (flags & MDB_CURRENT) {
6574 xflags = MDB_CURRENT|MDB_NOSPILL;
6576 mdb_xcursor_init1(mc, leaf);
6577 xflags = (flags & MDB_NODUPDATA) ?
6578 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6580 /* converted, write the original data first */
6582 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6586 /* Adjust other cursors pointing to mp */
6588 unsigned i = mc->mc_top;
6589 MDB_page *mp = mc->mc_pg[i];
6591 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6592 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6593 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6594 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6595 mdb_xcursor_init1(m2, leaf);
6599 /* we've done our job */
6602 ecount = mc->mc_xcursor->mx_db.md_entries;
6603 if (flags & MDB_APPENDDUP)
6604 xflags |= MDB_APPEND;
6605 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6606 if (flags & F_SUBDATA) {
6607 void *db = NODEDATA(leaf);
6608 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6610 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6612 /* Increment count unless we just replaced an existing item. */
6614 mc->mc_db->md_entries++;
6616 /* Invalidate txn if we created an empty sub-DB */
6619 /* If we succeeded and the key didn't exist before,
6620 * make sure the cursor is marked valid.
6622 mc->mc_flags |= C_INITIALIZED;
6624 if (flags & MDB_MULTIPLE) {
6627 /* let caller know how many succeeded, if any */
6628 data[1].mv_size = mcount;
6629 if (mcount < dcount) {
6630 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6631 insert_key = insert_data = 0;
6638 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6641 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6646 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6652 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6653 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6655 if (!(mc->mc_flags & C_INITIALIZED))
6658 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6659 return MDB_NOTFOUND;
6661 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6664 rc = mdb_cursor_touch(mc);
6668 mp = mc->mc_pg[mc->mc_top];
6671 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6673 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6674 if (flags & MDB_NODUPDATA) {
6675 /* mdb_cursor_del0() will subtract the final entry */
6676 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6678 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6679 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6681 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6684 /* If sub-DB still has entries, we're done */
6685 if (mc->mc_xcursor->mx_db.md_entries) {
6686 if (leaf->mn_flags & F_SUBDATA) {
6687 /* update subDB info */
6688 void *db = NODEDATA(leaf);
6689 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6692 /* shrink fake page */
6693 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6694 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6695 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6696 /* fix other sub-DB cursors pointed at this fake page */
6697 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6698 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6699 if (m2->mc_pg[mc->mc_top] == mp &&
6700 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6701 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6704 mc->mc_db->md_entries--;
6705 mc->mc_flags |= C_DEL;
6708 /* otherwise fall thru and delete the sub-DB */
6711 if (leaf->mn_flags & F_SUBDATA) {
6712 /* add all the child DB's pages to the free list */
6713 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6719 /* add overflow pages to free list */
6720 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6724 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6725 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6726 (rc = mdb_ovpage_free(mc, omp)))
6731 return mdb_cursor_del0(mc);
6734 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6738 /** Allocate and initialize new pages for a database.
6739 * @param[in] mc a cursor on the database being added to.
6740 * @param[in] flags flags defining what type of page is being allocated.
6741 * @param[in] num the number of pages to allocate. This is usually 1,
6742 * unless allocating overflow pages for a large record.
6743 * @param[out] mp Address of a page, or NULL on failure.
6744 * @return 0 on success, non-zero on failure.
6747 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6752 if ((rc = mdb_page_alloc(mc, num, &np)))
6754 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6755 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6756 np->mp_flags = flags | P_DIRTY;
6757 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
6758 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
6761 mc->mc_db->md_branch_pages++;
6762 else if (IS_LEAF(np))
6763 mc->mc_db->md_leaf_pages++;
6764 else if (IS_OVERFLOW(np)) {
6765 mc->mc_db->md_overflow_pages += num;
6773 /** Calculate the size of a leaf node.
6774 * The size depends on the environment's page size; if a data item
6775 * is too large it will be put onto an overflow page and the node
6776 * size will only include the key and not the data. Sizes are always
6777 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6778 * of the #MDB_node headers.
6779 * @param[in] env The environment handle.
6780 * @param[in] key The key for the node.
6781 * @param[in] data The data for the node.
6782 * @return The number of bytes needed to store the node.
6785 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6789 sz = LEAFSIZE(key, data);
6790 if (sz > env->me_nodemax) {
6791 /* put on overflow page */
6792 sz -= data->mv_size - sizeof(pgno_t);
6795 return EVEN(sz + sizeof(indx_t));
6798 /** Calculate the size of a branch node.
6799 * The size should depend on the environment's page size but since
6800 * we currently don't support spilling large keys onto overflow
6801 * pages, it's simply the size of the #MDB_node header plus the
6802 * size of the key. Sizes are always rounded up to an even number
6803 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6804 * @param[in] env The environment handle.
6805 * @param[in] key The key for the node.
6806 * @return The number of bytes needed to store the node.
6809 mdb_branch_size(MDB_env *env, MDB_val *key)
6814 if (sz > env->me_nodemax) {
6815 /* put on overflow page */
6816 /* not implemented */
6817 /* sz -= key->size - sizeof(pgno_t); */
6820 return sz + sizeof(indx_t);
6823 /** Add a node to the page pointed to by the cursor.
6824 * @param[in] mc The cursor for this operation.
6825 * @param[in] indx The index on the page where the new node should be added.
6826 * @param[in] key The key for the new node.
6827 * @param[in] data The data for the new node, if any.
6828 * @param[in] pgno The page number, if adding a branch node.
6829 * @param[in] flags Flags for the node.
6830 * @return 0 on success, non-zero on failure. Possible errors are:
6832 * <li>ENOMEM - failed to allocate overflow pages for the node.
6833 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6834 * should never happen since all callers already calculate the
6835 * page's free space before calling this function.
6839 mdb_node_add(MDB_cursor *mc, indx_t indx,
6840 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6843 size_t node_size = NODESIZE;
6847 MDB_page *mp = mc->mc_pg[mc->mc_top];
6848 MDB_page *ofp = NULL; /* overflow page */
6851 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
6853 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6854 IS_LEAF(mp) ? "leaf" : "branch",
6855 IS_SUBP(mp) ? "sub-" : "",
6856 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
6857 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6860 /* Move higher keys up one slot. */
6861 int ksize = mc->mc_db->md_pad, dif;
6862 char *ptr = LEAF2KEY(mp, indx, ksize);
6863 dif = NUMKEYS(mp) - indx;
6865 memmove(ptr+ksize, ptr, dif*ksize);
6866 /* insert new key */
6867 memcpy(ptr, key->mv_data, ksize);
6869 /* Just using these for counting */
6870 mp->mp_lower += sizeof(indx_t);
6871 mp->mp_upper -= ksize - sizeof(indx_t);
6875 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6877 node_size += key->mv_size;
6879 mdb_cassert(mc, data);
6880 if (F_ISSET(flags, F_BIGDATA)) {
6881 /* Data already on overflow page. */
6882 node_size += sizeof(pgno_t);
6883 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
6884 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6886 /* Put data on overflow page. */
6887 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6888 data->mv_size, node_size+data->mv_size));
6889 node_size = EVEN(node_size + sizeof(pgno_t));
6890 if ((ssize_t)node_size > room)
6892 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6894 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6898 node_size += data->mv_size;
6901 node_size = EVEN(node_size);
6902 if ((ssize_t)node_size > room)
6906 /* Move higher pointers up one slot. */
6907 for (i = NUMKEYS(mp); i > indx; i--)
6908 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6910 /* Adjust free space offsets. */
6911 ofs = mp->mp_upper - node_size;
6912 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
6913 mp->mp_ptrs[indx] = ofs;
6915 mp->mp_lower += sizeof(indx_t);
6917 /* Write the node data. */
6918 node = NODEPTR(mp, indx);
6919 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6920 node->mn_flags = flags;
6922 SETDSZ(node,data->mv_size);
6927 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6930 mdb_cassert(mc, key);
6932 if (F_ISSET(flags, F_BIGDATA))
6933 memcpy(node->mn_data + key->mv_size, data->mv_data,
6935 else if (F_ISSET(flags, MDB_RESERVE))
6936 data->mv_data = node->mn_data + key->mv_size;
6938 memcpy(node->mn_data + key->mv_size, data->mv_data,
6941 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6943 if (F_ISSET(flags, MDB_RESERVE))
6944 data->mv_data = METADATA(ofp);
6946 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6953 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6954 mdb_dbg_pgno(mp), NUMKEYS(mp)));
6955 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6956 DPRINTF(("node size = %"Z"u", node_size));
6957 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6958 return MDB_PAGE_FULL;
6961 /** Delete the specified node from a page.
6962 * @param[in] mc Cursor pointing to the node to delete.
6963 * @param[in] ksize The size of a node. Only used if the page is
6964 * part of a #MDB_DUPFIXED database.
6967 mdb_node_del(MDB_cursor *mc, int ksize)
6969 MDB_page *mp = mc->mc_pg[mc->mc_top];
6970 indx_t indx = mc->mc_ki[mc->mc_top];
6972 indx_t i, j, numkeys, ptr;
6976 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6977 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
6978 numkeys = NUMKEYS(mp);
6979 mdb_cassert(mc, indx < numkeys);
6982 int x = numkeys - 1 - indx;
6983 base = LEAF2KEY(mp, indx, ksize);
6985 memmove(base, base + ksize, x * ksize);
6986 mp->mp_lower -= sizeof(indx_t);
6987 mp->mp_upper += ksize - sizeof(indx_t);
6991 node = NODEPTR(mp, indx);
6992 sz = NODESIZE + node->mn_ksize;
6994 if (F_ISSET(node->mn_flags, F_BIGDATA))
6995 sz += sizeof(pgno_t);
6997 sz += NODEDSZ(node);
7001 ptr = mp->mp_ptrs[indx];
7002 for (i = j = 0; i < numkeys; i++) {
7004 mp->mp_ptrs[j] = mp->mp_ptrs[i];
7005 if (mp->mp_ptrs[i] < ptr)
7006 mp->mp_ptrs[j] += sz;
7011 base = (char *)mp + mp->mp_upper + PAGEBASE;
7012 memmove(base + sz, base, ptr - mp->mp_upper);
7014 mp->mp_lower -= sizeof(indx_t);
7018 /** Compact the main page after deleting a node on a subpage.
7019 * @param[in] mp The main page to operate on.
7020 * @param[in] indx The index of the subpage on the main page.
7023 mdb_node_shrink(MDB_page *mp, indx_t indx)
7029 indx_t i, numkeys, ptr;
7031 node = NODEPTR(mp, indx);
7032 sp = (MDB_page *)NODEDATA(node);
7033 delta = SIZELEFT(sp);
7034 xp = (MDB_page *)((char *)sp + delta);
7036 /* shift subpage upward */
7038 nsize = NUMKEYS(sp) * sp->mp_pad;
7040 return; /* do not make the node uneven-sized */
7041 memmove(METADATA(xp), METADATA(sp), nsize);
7044 numkeys = NUMKEYS(sp);
7045 for (i=numkeys-1; i>=0; i--)
7046 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
7048 xp->mp_upper = sp->mp_lower;
7049 xp->mp_lower = sp->mp_lower;
7050 xp->mp_flags = sp->mp_flags;
7051 xp->mp_pad = sp->mp_pad;
7052 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
7054 nsize = NODEDSZ(node) - delta;
7055 SETDSZ(node, nsize);
7057 /* shift lower nodes upward */
7058 ptr = mp->mp_ptrs[indx];
7059 numkeys = NUMKEYS(mp);
7060 for (i = 0; i < numkeys; i++) {
7061 if (mp->mp_ptrs[i] <= ptr)
7062 mp->mp_ptrs[i] += delta;
7065 base = (char *)mp + mp->mp_upper + PAGEBASE;
7066 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
7067 mp->mp_upper += delta;
7070 /** Initial setup of a sorted-dups cursor.
7071 * Sorted duplicates are implemented as a sub-database for the given key.
7072 * The duplicate data items are actually keys of the sub-database.
7073 * Operations on the duplicate data items are performed using a sub-cursor
7074 * initialized when the sub-database is first accessed. This function does
7075 * the preliminary setup of the sub-cursor, filling in the fields that
7076 * depend only on the parent DB.
7077 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7080 mdb_xcursor_init0(MDB_cursor *mc)
7082 MDB_xcursor *mx = mc->mc_xcursor;
7084 mx->mx_cursor.mc_xcursor = NULL;
7085 mx->mx_cursor.mc_txn = mc->mc_txn;
7086 mx->mx_cursor.mc_db = &mx->mx_db;
7087 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
7088 mx->mx_cursor.mc_dbi = mc->mc_dbi;
7089 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
7090 mx->mx_cursor.mc_snum = 0;
7091 mx->mx_cursor.mc_top = 0;
7092 mx->mx_cursor.mc_flags = C_SUB;
7093 mx->mx_dbx.md_name.mv_size = 0;
7094 mx->mx_dbx.md_name.mv_data = NULL;
7095 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
7096 mx->mx_dbx.md_dcmp = NULL;
7097 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
7100 /** Final setup of a sorted-dups cursor.
7101 * Sets up the fields that depend on the data from the main cursor.
7102 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7103 * @param[in] node The data containing the #MDB_db record for the
7104 * sorted-dup database.
7107 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
7109 MDB_xcursor *mx = mc->mc_xcursor;
7111 if (node->mn_flags & F_SUBDATA) {
7112 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
7113 mx->mx_cursor.mc_pg[0] = 0;
7114 mx->mx_cursor.mc_snum = 0;
7115 mx->mx_cursor.mc_top = 0;
7116 mx->mx_cursor.mc_flags = C_SUB;
7118 MDB_page *fp = NODEDATA(node);
7119 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
7120 mx->mx_db.md_flags = 0;
7121 mx->mx_db.md_depth = 1;
7122 mx->mx_db.md_branch_pages = 0;
7123 mx->mx_db.md_leaf_pages = 1;
7124 mx->mx_db.md_overflow_pages = 0;
7125 mx->mx_db.md_entries = NUMKEYS(fp);
7126 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
7127 mx->mx_cursor.mc_snum = 1;
7128 mx->mx_cursor.mc_top = 0;
7129 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
7130 mx->mx_cursor.mc_pg[0] = fp;
7131 mx->mx_cursor.mc_ki[0] = 0;
7132 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7133 mx->mx_db.md_flags = MDB_DUPFIXED;
7134 mx->mx_db.md_pad = fp->mp_pad;
7135 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7136 mx->mx_db.md_flags |= MDB_INTEGERKEY;
7139 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7140 mx->mx_db.md_root));
7141 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
7142 #if UINT_MAX < SIZE_MAX
7143 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
7144 mx->mx_dbx.md_cmp = mdb_cmp_clong;
7148 /** Initialize a cursor for a given transaction and database. */
7150 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
7153 mc->mc_backup = NULL;
7156 mc->mc_db = &txn->mt_dbs[dbi];
7157 mc->mc_dbx = &txn->mt_dbxs[dbi];
7158 mc->mc_dbflag = &txn->mt_dbflags[dbi];
7163 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
7164 mdb_tassert(txn, mx != NULL);
7165 mc->mc_xcursor = mx;
7166 mdb_xcursor_init0(mc);
7168 mc->mc_xcursor = NULL;
7170 if (*mc->mc_dbflag & DB_STALE) {
7171 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
7176 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
7179 size_t size = sizeof(MDB_cursor);
7181 if (!ret || !TXN_DBI_EXIST(txn, dbi))
7184 if (txn->mt_flags & MDB_TXN_ERROR)
7187 /* Allow read access to the freelist */
7188 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7191 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
7192 size += sizeof(MDB_xcursor);
7194 if ((mc = malloc(size)) != NULL) {
7195 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
7196 if (txn->mt_cursors) {
7197 mc->mc_next = txn->mt_cursors[dbi];
7198 txn->mt_cursors[dbi] = mc;
7199 mc->mc_flags |= C_UNTRACK;
7211 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
7213 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi))
7216 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
7219 if (txn->mt_flags & MDB_TXN_ERROR)
7222 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
7226 /* Return the count of duplicate data items for the current key */
7228 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7232 if (mc == NULL || countp == NULL)
7235 if (mc->mc_xcursor == NULL)
7236 return MDB_INCOMPATIBLE;
7238 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
7241 if (!(mc->mc_flags & C_INITIALIZED))
7244 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
7245 return MDB_NOTFOUND;
7247 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7248 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7251 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7254 *countp = mc->mc_xcursor->mx_db.md_entries;
7260 mdb_cursor_close(MDB_cursor *mc)
7262 if (mc && !mc->mc_backup) {
7263 /* remove from txn, if tracked */
7264 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7265 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7266 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7268 *prev = mc->mc_next;
7275 mdb_cursor_txn(MDB_cursor *mc)
7277 if (!mc) return NULL;
7282 mdb_cursor_dbi(MDB_cursor *mc)
7287 /** Replace the key for a branch node with a new key.
7288 * @param[in] mc Cursor pointing to the node to operate on.
7289 * @param[in] key The new key to use.
7290 * @return 0 on success, non-zero on failure.
7293 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7299 int delta, ksize, oksize;
7300 indx_t ptr, i, numkeys, indx;
7303 indx = mc->mc_ki[mc->mc_top];
7304 mp = mc->mc_pg[mc->mc_top];
7305 node = NODEPTR(mp, indx);
7306 ptr = mp->mp_ptrs[indx];
7310 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7311 k2.mv_data = NODEKEY(node);
7312 k2.mv_size = node->mn_ksize;
7313 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7315 mdb_dkey(&k2, kbuf2),
7321 /* Sizes must be 2-byte aligned. */
7322 ksize = EVEN(key->mv_size);
7323 oksize = EVEN(node->mn_ksize);
7324 delta = ksize - oksize;
7326 /* Shift node contents if EVEN(key length) changed. */
7328 if (delta > 0 && SIZELEFT(mp) < delta) {
7330 /* not enough space left, do a delete and split */
7331 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7332 pgno = NODEPGNO(node);
7333 mdb_node_del(mc, 0);
7334 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7337 numkeys = NUMKEYS(mp);
7338 for (i = 0; i < numkeys; i++) {
7339 if (mp->mp_ptrs[i] <= ptr)
7340 mp->mp_ptrs[i] -= delta;
7343 base = (char *)mp + mp->mp_upper + PAGEBASE;
7344 len = ptr - mp->mp_upper + NODESIZE;
7345 memmove(base - delta, base, len);
7346 mp->mp_upper -= delta;
7348 node = NODEPTR(mp, indx);
7351 /* But even if no shift was needed, update ksize */
7352 if (node->mn_ksize != key->mv_size)
7353 node->mn_ksize = key->mv_size;
7356 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7362 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7364 /** Move a node from csrc to cdst.
7367 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
7374 unsigned short flags;
7378 /* Mark src and dst as dirty. */
7379 if ((rc = mdb_page_touch(csrc)) ||
7380 (rc = mdb_page_touch(cdst)))
7383 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7384 key.mv_size = csrc->mc_db->md_pad;
7385 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7387 data.mv_data = NULL;
7391 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7392 mdb_cassert(csrc, !((size_t)srcnode & 1));
7393 srcpg = NODEPGNO(srcnode);
7394 flags = srcnode->mn_flags;
7395 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7396 unsigned int snum = csrc->mc_snum;
7398 /* must find the lowest key below src */
7399 rc = mdb_page_search_lowest(csrc);
7402 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7403 key.mv_size = csrc->mc_db->md_pad;
7404 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7406 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7407 key.mv_size = NODEKSZ(s2);
7408 key.mv_data = NODEKEY(s2);
7410 csrc->mc_snum = snum--;
7411 csrc->mc_top = snum;
7413 key.mv_size = NODEKSZ(srcnode);
7414 key.mv_data = NODEKEY(srcnode);
7416 data.mv_size = NODEDSZ(srcnode);
7417 data.mv_data = NODEDATA(srcnode);
7419 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7420 unsigned int snum = cdst->mc_snum;
7423 /* must find the lowest key below dst */
7424 mdb_cursor_copy(cdst, &mn);
7425 rc = mdb_page_search_lowest(&mn);
7428 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7429 bkey.mv_size = mn.mc_db->md_pad;
7430 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7432 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7433 bkey.mv_size = NODEKSZ(s2);
7434 bkey.mv_data = NODEKEY(s2);
7436 mn.mc_snum = snum--;
7439 rc = mdb_update_key(&mn, &bkey);
7444 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7445 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7446 csrc->mc_ki[csrc->mc_top],
7448 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7449 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7451 /* Add the node to the destination page.
7453 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7454 if (rc != MDB_SUCCESS)
7457 /* Delete the node from the source page.
7459 mdb_node_del(csrc, key.mv_size);
7462 /* Adjust other cursors pointing to mp */
7463 MDB_cursor *m2, *m3;
7464 MDB_dbi dbi = csrc->mc_dbi;
7465 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
7467 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7468 if (csrc->mc_flags & C_SUB)
7469 m3 = &m2->mc_xcursor->mx_cursor;
7472 if (m3 == csrc) continue;
7473 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
7474 csrc->mc_ki[csrc->mc_top]) {
7475 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7476 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7481 /* Update the parent separators.
7483 if (csrc->mc_ki[csrc->mc_top] == 0) {
7484 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7485 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7486 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7488 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7489 key.mv_size = NODEKSZ(srcnode);
7490 key.mv_data = NODEKEY(srcnode);
7492 DPRINTF(("update separator for source page %"Z"u to [%s]",
7493 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7494 mdb_cursor_copy(csrc, &mn);
7497 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7500 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7502 indx_t ix = csrc->mc_ki[csrc->mc_top];
7503 nullkey.mv_size = 0;
7504 csrc->mc_ki[csrc->mc_top] = 0;
7505 rc = mdb_update_key(csrc, &nullkey);
7506 csrc->mc_ki[csrc->mc_top] = ix;
7507 mdb_cassert(csrc, rc == MDB_SUCCESS);
7511 if (cdst->mc_ki[cdst->mc_top] == 0) {
7512 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7513 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7514 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7516 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7517 key.mv_size = NODEKSZ(srcnode);
7518 key.mv_data = NODEKEY(srcnode);
7520 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7521 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7522 mdb_cursor_copy(cdst, &mn);
7525 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7528 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7530 indx_t ix = cdst->mc_ki[cdst->mc_top];
7531 nullkey.mv_size = 0;
7532 cdst->mc_ki[cdst->mc_top] = 0;
7533 rc = mdb_update_key(cdst, &nullkey);
7534 cdst->mc_ki[cdst->mc_top] = ix;
7535 mdb_cassert(csrc, rc == MDB_SUCCESS);
7542 /** Merge one page into another.
7543 * The nodes from the page pointed to by \b csrc will
7544 * be copied to the page pointed to by \b cdst and then
7545 * the \b csrc page will be freed.
7546 * @param[in] csrc Cursor pointing to the source page.
7547 * @param[in] cdst Cursor pointing to the destination page.
7548 * @return 0 on success, non-zero on failure.
7551 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7553 MDB_page *psrc, *pdst;
7560 psrc = csrc->mc_pg[csrc->mc_top];
7561 pdst = cdst->mc_pg[cdst->mc_top];
7563 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7565 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7566 mdb_cassert(csrc, cdst->mc_snum > 1);
7568 /* Mark dst as dirty. */
7569 if ((rc = mdb_page_touch(cdst)))
7572 /* Move all nodes from src to dst.
7574 j = nkeys = NUMKEYS(pdst);
7575 if (IS_LEAF2(psrc)) {
7576 key.mv_size = csrc->mc_db->md_pad;
7577 key.mv_data = METADATA(psrc);
7578 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7579 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7580 if (rc != MDB_SUCCESS)
7582 key.mv_data = (char *)key.mv_data + key.mv_size;
7585 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7586 srcnode = NODEPTR(psrc, i);
7587 if (i == 0 && IS_BRANCH(psrc)) {
7590 mdb_cursor_copy(csrc, &mn);
7591 /* must find the lowest key below src */
7592 rc = mdb_page_search_lowest(&mn);
7595 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7596 key.mv_size = mn.mc_db->md_pad;
7597 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7599 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7600 key.mv_size = NODEKSZ(s2);
7601 key.mv_data = NODEKEY(s2);
7604 key.mv_size = srcnode->mn_ksize;
7605 key.mv_data = NODEKEY(srcnode);
7608 data.mv_size = NODEDSZ(srcnode);
7609 data.mv_data = NODEDATA(srcnode);
7610 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7611 if (rc != MDB_SUCCESS)
7616 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7617 pdst->mp_pgno, NUMKEYS(pdst),
7618 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7620 /* Unlink the src page from parent and add to free list.
7623 mdb_node_del(csrc, 0);
7624 if (csrc->mc_ki[csrc->mc_top] == 0) {
7626 rc = mdb_update_key(csrc, &key);
7634 psrc = csrc->mc_pg[csrc->mc_top];
7635 /* If not operating on FreeDB, allow this page to be reused
7636 * in this txn. Otherwise just add to free list.
7638 rc = mdb_page_loose(csrc, psrc);
7642 csrc->mc_db->md_leaf_pages--;
7644 csrc->mc_db->md_branch_pages--;
7646 /* Adjust other cursors pointing to mp */
7647 MDB_cursor *m2, *m3;
7648 MDB_dbi dbi = csrc->mc_dbi;
7650 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7651 if (csrc->mc_flags & C_SUB)
7652 m3 = &m2->mc_xcursor->mx_cursor;
7655 if (m3 == csrc) continue;
7656 if (m3->mc_snum < csrc->mc_snum) continue;
7657 if (m3->mc_pg[csrc->mc_top] == psrc) {
7658 m3->mc_pg[csrc->mc_top] = pdst;
7659 m3->mc_ki[csrc->mc_top] += nkeys;
7664 unsigned int snum = cdst->mc_snum;
7665 uint16_t depth = cdst->mc_db->md_depth;
7666 mdb_cursor_pop(cdst);
7667 rc = mdb_rebalance(cdst);
7668 /* Did the tree shrink? */
7669 if (depth > cdst->mc_db->md_depth)
7671 cdst->mc_snum = snum;
7672 cdst->mc_top = snum-1;
7677 /** Copy the contents of a cursor.
7678 * @param[in] csrc The cursor to copy from.
7679 * @param[out] cdst The cursor to copy to.
7682 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7686 cdst->mc_txn = csrc->mc_txn;
7687 cdst->mc_dbi = csrc->mc_dbi;
7688 cdst->mc_db = csrc->mc_db;
7689 cdst->mc_dbx = csrc->mc_dbx;
7690 cdst->mc_snum = csrc->mc_snum;
7691 cdst->mc_top = csrc->mc_top;
7692 cdst->mc_flags = csrc->mc_flags;
7694 for (i=0; i<csrc->mc_snum; i++) {
7695 cdst->mc_pg[i] = csrc->mc_pg[i];
7696 cdst->mc_ki[i] = csrc->mc_ki[i];
7700 /** Rebalance the tree after a delete operation.
7701 * @param[in] mc Cursor pointing to the page where rebalancing
7703 * @return 0 on success, non-zero on failure.
7706 mdb_rebalance(MDB_cursor *mc)
7710 unsigned int ptop, minkeys;
7714 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7715 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7716 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7717 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7718 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7720 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7721 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7722 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7723 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7727 if (mc->mc_snum < 2) {
7728 MDB_page *mp = mc->mc_pg[0];
7730 DPUTS("Can't rebalance a subpage, ignoring");
7733 if (NUMKEYS(mp) == 0) {
7734 DPUTS("tree is completely empty");
7735 mc->mc_db->md_root = P_INVALID;
7736 mc->mc_db->md_depth = 0;
7737 mc->mc_db->md_leaf_pages = 0;
7738 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7741 /* Adjust cursors pointing to mp */
7744 mc->mc_flags &= ~C_INITIALIZED;
7746 MDB_cursor *m2, *m3;
7747 MDB_dbi dbi = mc->mc_dbi;
7749 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7750 if (mc->mc_flags & C_SUB)
7751 m3 = &m2->mc_xcursor->mx_cursor;
7754 if (m3->mc_snum < mc->mc_snum) continue;
7755 if (m3->mc_pg[0] == mp) {
7758 m3->mc_flags &= ~C_INITIALIZED;
7762 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7764 DPUTS("collapsing root page!");
7765 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7768 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7769 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7772 mc->mc_db->md_depth--;
7773 mc->mc_db->md_branch_pages--;
7774 mc->mc_ki[0] = mc->mc_ki[1];
7775 for (i = 1; i<mc->mc_db->md_depth; i++) {
7776 mc->mc_pg[i] = mc->mc_pg[i+1];
7777 mc->mc_ki[i] = mc->mc_ki[i+1];
7780 /* Adjust other cursors pointing to mp */
7781 MDB_cursor *m2, *m3;
7782 MDB_dbi dbi = mc->mc_dbi;
7784 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7785 if (mc->mc_flags & C_SUB)
7786 m3 = &m2->mc_xcursor->mx_cursor;
7789 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7790 if (m3->mc_pg[0] == mp) {
7793 for (i=0; i<m3->mc_snum; i++) {
7794 m3->mc_pg[i] = m3->mc_pg[i+1];
7795 m3->mc_ki[i] = m3->mc_ki[i+1];
7801 DPUTS("root page doesn't need rebalancing");
7805 /* The parent (branch page) must have at least 2 pointers,
7806 * otherwise the tree is invalid.
7808 ptop = mc->mc_top-1;
7809 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
7811 /* Leaf page fill factor is below the threshold.
7812 * Try to move keys from left or right neighbor, or
7813 * merge with a neighbor page.
7818 mdb_cursor_copy(mc, &mn);
7819 mn.mc_xcursor = NULL;
7821 oldki = mc->mc_ki[mc->mc_top];
7822 if (mc->mc_ki[ptop] == 0) {
7823 /* We're the leftmost leaf in our parent.
7825 DPUTS("reading right neighbor");
7827 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7828 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7831 mn.mc_ki[mn.mc_top] = 0;
7832 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7834 /* There is at least one neighbor to the left.
7836 DPUTS("reading left neighbor");
7838 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7839 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7842 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7843 mc->mc_ki[mc->mc_top] = 0;
7846 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7847 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7848 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7850 /* If the neighbor page is above threshold and has enough keys,
7851 * move one key from it. Otherwise we should try to merge them.
7852 * (A branch page must never have less than 2 keys.)
7854 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7855 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
7856 rc = mdb_node_move(&mn, mc);
7857 if (mc->mc_ki[ptop]) {
7861 if (mc->mc_ki[ptop] == 0) {
7862 rc = mdb_page_merge(&mn, mc);
7864 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
7865 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7866 rc = mdb_page_merge(mc, &mn);
7867 mdb_cursor_copy(&mn, mc);
7869 mc->mc_flags &= ~C_EOF;
7871 mc->mc_ki[mc->mc_top] = oldki;
7875 /** Complete a delete operation started by #mdb_cursor_del(). */
7877 mdb_cursor_del0(MDB_cursor *mc)
7884 ki = mc->mc_ki[mc->mc_top];
7885 mdb_node_del(mc, mc->mc_db->md_pad);
7886 mc->mc_db->md_entries--;
7887 rc = mdb_rebalance(mc);
7889 if (rc == MDB_SUCCESS) {
7890 MDB_cursor *m2, *m3;
7891 MDB_dbi dbi = mc->mc_dbi;
7893 mp = mc->mc_pg[mc->mc_top];
7894 nkeys = NUMKEYS(mp);
7896 /* if mc points past last node in page, find next sibling */
7897 if (mc->mc_ki[mc->mc_top] >= nkeys) {
7898 rc = mdb_cursor_sibling(mc, 1);
7899 if (rc == MDB_NOTFOUND) {
7900 mc->mc_flags |= C_EOF;
7905 /* Adjust other cursors pointing to mp */
7906 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
7907 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
7908 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7910 if (m3 == mc || m3->mc_snum < mc->mc_snum)
7912 if (m3->mc_pg[mc->mc_top] == mp) {
7913 if (m3->mc_ki[mc->mc_top] >= ki) {
7914 m3->mc_flags |= C_DEL;
7915 if (m3->mc_ki[mc->mc_top] > ki)
7916 m3->mc_ki[mc->mc_top]--;
7917 else if (mc->mc_db->md_flags & MDB_DUPSORT)
7918 m3->mc_xcursor->mx_cursor.mc_flags |= C_EOF;
7920 if (m3->mc_ki[mc->mc_top] >= nkeys) {
7921 rc = mdb_cursor_sibling(m3, 1);
7922 if (rc == MDB_NOTFOUND) {
7923 m3->mc_flags |= C_EOF;
7929 mc->mc_flags |= C_DEL;
7933 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7938 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7939 MDB_val *key, MDB_val *data)
7941 if (!key || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
7944 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7945 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7947 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7948 /* must ignore any data */
7952 return mdb_del0(txn, dbi, key, data, 0);
7956 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
7957 MDB_val *key, MDB_val *data, unsigned flags)
7962 MDB_val rdata, *xdata;
7966 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7968 mdb_cursor_init(&mc, txn, dbi, &mx);
7977 flags |= MDB_NODUPDATA;
7979 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7981 /* let mdb_page_split know about this cursor if needed:
7982 * delete will trigger a rebalance; if it needs to move
7983 * a node from one page to another, it will have to
7984 * update the parent's separator key(s). If the new sepkey
7985 * is larger than the current one, the parent page may
7986 * run out of space, triggering a split. We need this
7987 * cursor to be consistent until the end of the rebalance.
7989 mc.mc_flags |= C_UNTRACK;
7990 mc.mc_next = txn->mt_cursors[dbi];
7991 txn->mt_cursors[dbi] = &mc;
7992 rc = mdb_cursor_del(&mc, flags);
7993 txn->mt_cursors[dbi] = mc.mc_next;
7998 /** Split a page and insert a new node.
7999 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
8000 * The cursor will be updated to point to the actual page and index where
8001 * the node got inserted after the split.
8002 * @param[in] newkey The key for the newly inserted node.
8003 * @param[in] newdata The data for the newly inserted node.
8004 * @param[in] newpgno The page number, if the new node is a branch node.
8005 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
8006 * @return 0 on success, non-zero on failure.
8009 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
8010 unsigned int nflags)
8013 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
8016 int i, j, split_indx, nkeys, pmax;
8017 MDB_env *env = mc->mc_txn->mt_env;
8019 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
8020 MDB_page *copy = NULL;
8021 MDB_page *mp, *rp, *pp;
8026 mp = mc->mc_pg[mc->mc_top];
8027 newindx = mc->mc_ki[mc->mc_top];
8028 nkeys = NUMKEYS(mp);
8030 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
8031 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
8032 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
8034 /* Create a right sibling. */
8035 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
8037 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
8039 if (mc->mc_snum < 2) {
8040 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
8042 /* shift current top to make room for new parent */
8043 mc->mc_pg[1] = mc->mc_pg[0];
8044 mc->mc_ki[1] = mc->mc_ki[0];
8047 mc->mc_db->md_root = pp->mp_pgno;
8048 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
8049 mc->mc_db->md_depth++;
8052 /* Add left (implicit) pointer. */
8053 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
8054 /* undo the pre-push */
8055 mc->mc_pg[0] = mc->mc_pg[1];
8056 mc->mc_ki[0] = mc->mc_ki[1];
8057 mc->mc_db->md_root = mp->mp_pgno;
8058 mc->mc_db->md_depth--;
8065 ptop = mc->mc_top-1;
8066 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
8069 mc->mc_flags |= C_SPLITTING;
8070 mdb_cursor_copy(mc, &mn);
8071 mn.mc_pg[mn.mc_top] = rp;
8072 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
8074 if (nflags & MDB_APPEND) {
8075 mn.mc_ki[mn.mc_top] = 0;
8077 split_indx = newindx;
8081 split_indx = (nkeys+1) / 2;
8086 unsigned int lsize, rsize, ksize;
8087 /* Move half of the keys to the right sibling */
8088 x = mc->mc_ki[mc->mc_top] - split_indx;
8089 ksize = mc->mc_db->md_pad;
8090 split = LEAF2KEY(mp, split_indx, ksize);
8091 rsize = (nkeys - split_indx) * ksize;
8092 lsize = (nkeys - split_indx) * sizeof(indx_t);
8093 mp->mp_lower -= lsize;
8094 rp->mp_lower += lsize;
8095 mp->mp_upper += rsize - lsize;
8096 rp->mp_upper -= rsize - lsize;
8097 sepkey.mv_size = ksize;
8098 if (newindx == split_indx) {
8099 sepkey.mv_data = newkey->mv_data;
8101 sepkey.mv_data = split;
8104 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
8105 memcpy(rp->mp_ptrs, split, rsize);
8106 sepkey.mv_data = rp->mp_ptrs;
8107 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
8108 memcpy(ins, newkey->mv_data, ksize);
8109 mp->mp_lower += sizeof(indx_t);
8110 mp->mp_upper -= ksize - sizeof(indx_t);
8113 memcpy(rp->mp_ptrs, split, x * ksize);
8114 ins = LEAF2KEY(rp, x, ksize);
8115 memcpy(ins, newkey->mv_data, ksize);
8116 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
8117 rp->mp_lower += sizeof(indx_t);
8118 rp->mp_upper -= ksize - sizeof(indx_t);
8119 mc->mc_ki[mc->mc_top] = x;
8120 mc->mc_pg[mc->mc_top] = rp;
8123 int psize, nsize, k;
8124 /* Maximum free space in an empty page */
8125 pmax = env->me_psize - PAGEHDRSZ;
8127 nsize = mdb_leaf_size(env, newkey, newdata);
8129 nsize = mdb_branch_size(env, newkey);
8130 nsize = EVEN(nsize);
8132 /* grab a page to hold a temporary copy */
8133 copy = mdb_page_malloc(mc->mc_txn, 1);
8138 copy->mp_pgno = mp->mp_pgno;
8139 copy->mp_flags = mp->mp_flags;
8140 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
8141 copy->mp_upper = env->me_psize - PAGEBASE;
8143 /* prepare to insert */
8144 for (i=0, j=0; i<nkeys; i++) {
8146 copy->mp_ptrs[j++] = 0;
8148 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
8151 /* When items are relatively large the split point needs
8152 * to be checked, because being off-by-one will make the
8153 * difference between success or failure in mdb_node_add.
8155 * It's also relevant if a page happens to be laid out
8156 * such that one half of its nodes are all "small" and
8157 * the other half of its nodes are "large." If the new
8158 * item is also "large" and falls on the half with
8159 * "large" nodes, it also may not fit.
8161 * As a final tweak, if the new item goes on the last
8162 * spot on the page (and thus, onto the new page), bias
8163 * the split so the new page is emptier than the old page.
8164 * This yields better packing during sequential inserts.
8166 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
8167 /* Find split point */
8169 if (newindx <= split_indx || newindx >= nkeys) {
8171 k = newindx >= nkeys ? nkeys : split_indx+2;
8176 for (; i!=k; i+=j) {
8181 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8182 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
8184 if (F_ISSET(node->mn_flags, F_BIGDATA))
8185 psize += sizeof(pgno_t);
8187 psize += NODEDSZ(node);
8189 psize = EVEN(psize);
8191 if (psize > pmax || i == k-j) {
8192 split_indx = i + (j<0);
8197 if (split_indx == newindx) {
8198 sepkey.mv_size = newkey->mv_size;
8199 sepkey.mv_data = newkey->mv_data;
8201 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
8202 sepkey.mv_size = node->mn_ksize;
8203 sepkey.mv_data = NODEKEY(node);
8208 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
8210 /* Copy separator key to the parent.
8212 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
8216 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
8221 if (mn.mc_snum == mc->mc_snum) {
8222 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
8223 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
8224 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
8225 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
8230 /* Right page might now have changed parent.
8231 * Check if left page also changed parent.
8233 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8234 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8235 for (i=0; i<ptop; i++) {
8236 mc->mc_pg[i] = mn.mc_pg[i];
8237 mc->mc_ki[i] = mn.mc_ki[i];
8239 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8240 if (mn.mc_ki[ptop]) {
8241 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8243 /* find right page's left sibling */
8244 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8245 mdb_cursor_sibling(mc, 0);
8250 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8253 mc->mc_flags ^= C_SPLITTING;
8254 if (rc != MDB_SUCCESS) {
8257 if (nflags & MDB_APPEND) {
8258 mc->mc_pg[mc->mc_top] = rp;
8259 mc->mc_ki[mc->mc_top] = 0;
8260 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8263 for (i=0; i<mc->mc_top; i++)
8264 mc->mc_ki[i] = mn.mc_ki[i];
8265 } else if (!IS_LEAF2(mp)) {
8267 mc->mc_pg[mc->mc_top] = rp;
8272 rkey.mv_data = newkey->mv_data;
8273 rkey.mv_size = newkey->mv_size;
8279 /* Update index for the new key. */
8280 mc->mc_ki[mc->mc_top] = j;
8282 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8283 rkey.mv_data = NODEKEY(node);
8284 rkey.mv_size = node->mn_ksize;
8286 xdata.mv_data = NODEDATA(node);
8287 xdata.mv_size = NODEDSZ(node);
8290 pgno = NODEPGNO(node);
8291 flags = node->mn_flags;
8294 if (!IS_LEAF(mp) && j == 0) {
8295 /* First branch index doesn't need key data. */
8299 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8305 mc->mc_pg[mc->mc_top] = copy;
8310 } while (i != split_indx);
8312 nkeys = NUMKEYS(copy);
8313 for (i=0; i<nkeys; i++)
8314 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8315 mp->mp_lower = copy->mp_lower;
8316 mp->mp_upper = copy->mp_upper;
8317 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8318 env->me_psize - copy->mp_upper - PAGEBASE);
8320 /* reset back to original page */
8321 if (newindx < split_indx) {
8322 mc->mc_pg[mc->mc_top] = mp;
8323 if (nflags & MDB_RESERVE) {
8324 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
8325 if (!(node->mn_flags & F_BIGDATA))
8326 newdata->mv_data = NODEDATA(node);
8329 mc->mc_pg[mc->mc_top] = rp;
8331 /* Make sure mc_ki is still valid.
8333 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8334 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8335 for (i=0; i<=ptop; i++) {
8336 mc->mc_pg[i] = mn.mc_pg[i];
8337 mc->mc_ki[i] = mn.mc_ki[i];
8344 /* Adjust other cursors pointing to mp */
8345 MDB_cursor *m2, *m3;
8346 MDB_dbi dbi = mc->mc_dbi;
8347 int fixup = NUMKEYS(mp);
8349 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8350 if (mc->mc_flags & C_SUB)
8351 m3 = &m2->mc_xcursor->mx_cursor;
8356 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8358 if (m3->mc_flags & C_SPLITTING)
8363 for (k=m3->mc_top; k>=0; k--) {
8364 m3->mc_ki[k+1] = m3->mc_ki[k];
8365 m3->mc_pg[k+1] = m3->mc_pg[k];
8367 if (m3->mc_ki[0] >= split_indx) {
8372 m3->mc_pg[0] = mc->mc_pg[0];
8376 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8377 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8378 m3->mc_ki[mc->mc_top]++;
8379 if (m3->mc_ki[mc->mc_top] >= fixup) {
8380 m3->mc_pg[mc->mc_top] = rp;
8381 m3->mc_ki[mc->mc_top] -= fixup;
8382 m3->mc_ki[ptop] = mn.mc_ki[ptop];
8384 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8385 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8390 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8393 if (copy) /* tmp page */
8394 mdb_page_free(env, copy);
8396 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8401 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8402 MDB_val *key, MDB_val *data, unsigned int flags)
8407 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8410 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
8413 mdb_cursor_init(&mc, txn, dbi, &mx);
8414 return mdb_cursor_put(&mc, key, data, flags);
8418 #define MDB_WBUF (1024*1024)
8421 /** State needed for a compacting copy. */
8422 typedef struct mdb_copy {
8423 pthread_mutex_t mc_mutex;
8424 pthread_cond_t mc_cond;
8431 pgno_t mc_next_pgno;
8434 volatile int mc_new;
8439 /** Dedicated writer thread for compacting copy. */
8440 static THREAD_RET ESECT
8441 mdb_env_copythr(void *arg)
8445 int toggle = 0, wsize, rc;
8448 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8451 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8454 pthread_mutex_lock(&my->mc_mutex);
8456 pthread_cond_signal(&my->mc_cond);
8459 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8460 if (my->mc_new < 0) {
8465 wsize = my->mc_wlen[toggle];
8466 ptr = my->mc_wbuf[toggle];
8469 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8473 } else if (len > 0) {
8487 /* If there's an overflow page tail, write it too */
8488 if (my->mc_olen[toggle]) {
8489 wsize = my->mc_olen[toggle];
8490 ptr = my->mc_over[toggle];
8491 my->mc_olen[toggle] = 0;
8494 my->mc_wlen[toggle] = 0;
8496 pthread_cond_signal(&my->mc_cond);
8498 pthread_cond_signal(&my->mc_cond);
8499 pthread_mutex_unlock(&my->mc_mutex);
8500 return (THREAD_RET)0;
8504 /** Tell the writer thread there's a buffer ready to write */
8506 mdb_env_cthr_toggle(mdb_copy *my, int st)
8508 int toggle = my->mc_toggle ^ 1;
8509 pthread_mutex_lock(&my->mc_mutex);
8510 if (my->mc_status) {
8511 pthread_mutex_unlock(&my->mc_mutex);
8512 return my->mc_status;
8514 while (my->mc_new == 1)
8515 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8517 my->mc_toggle = toggle;
8518 pthread_cond_signal(&my->mc_cond);
8519 pthread_mutex_unlock(&my->mc_mutex);
8523 /** Depth-first tree traversal for compacting copy. */
8525 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8528 MDB_txn *txn = my->mc_txn;
8530 MDB_page *mo, *mp, *leaf;
8535 /* Empty DB, nothing to do */
8536 if (*pg == P_INVALID)
8543 rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
8546 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8550 /* Make cursor pages writable */
8551 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8555 for (i=0; i<mc.mc_top; i++) {
8556 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8557 mc.mc_pg[i] = (MDB_page *)ptr;
8558 ptr += my->mc_env->me_psize;
8561 /* This is writable space for a leaf page. Usually not needed. */
8562 leaf = (MDB_page *)ptr;
8564 toggle = my->mc_toggle;
8565 while (mc.mc_snum > 0) {
8567 mp = mc.mc_pg[mc.mc_top];
8571 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8572 for (i=0; i<n; i++) {
8573 ni = NODEPTR(mp, i);
8574 if (ni->mn_flags & F_BIGDATA) {
8578 /* Need writable leaf */
8580 mc.mc_pg[mc.mc_top] = leaf;
8581 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8583 ni = NODEPTR(mp, i);
8586 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8587 rc = mdb_page_get(txn, pg, &omp, NULL);
8590 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8591 rc = mdb_env_cthr_toggle(my, 1);
8594 toggle = my->mc_toggle;
8596 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8597 memcpy(mo, omp, my->mc_env->me_psize);
8598 mo->mp_pgno = my->mc_next_pgno;
8599 my->mc_next_pgno += omp->mp_pages;
8600 my->mc_wlen[toggle] += my->mc_env->me_psize;
8601 if (omp->mp_pages > 1) {
8602 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
8603 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
8604 rc = mdb_env_cthr_toggle(my, 1);
8607 toggle = my->mc_toggle;
8609 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
8610 } else if (ni->mn_flags & F_SUBDATA) {
8613 /* Need writable leaf */
8615 mc.mc_pg[mc.mc_top] = leaf;
8616 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8618 ni = NODEPTR(mp, i);
8621 memcpy(&db, NODEDATA(ni), sizeof(db));
8622 my->mc_toggle = toggle;
8623 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
8626 toggle = my->mc_toggle;
8627 memcpy(NODEDATA(ni), &db, sizeof(db));
8632 mc.mc_ki[mc.mc_top]++;
8633 if (mc.mc_ki[mc.mc_top] < n) {
8636 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
8638 rc = mdb_page_get(txn, pg, &mp, NULL);
8643 mc.mc_ki[mc.mc_top] = 0;
8644 if (IS_BRANCH(mp)) {
8645 /* Whenever we advance to a sibling branch page,
8646 * we must proceed all the way down to its first leaf.
8648 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
8651 mc.mc_pg[mc.mc_top] = mp;
8655 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8656 rc = mdb_env_cthr_toggle(my, 1);
8659 toggle = my->mc_toggle;
8661 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8662 mdb_page_copy(mo, mp, my->mc_env->me_psize);
8663 mo->mp_pgno = my->mc_next_pgno++;
8664 my->mc_wlen[toggle] += my->mc_env->me_psize;
8666 /* Update parent if there is one */
8667 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
8668 SETPGNO(ni, mo->mp_pgno);
8669 mdb_cursor_pop(&mc);
8671 /* Otherwise we're done */
8681 /** Copy environment with compaction. */
8683 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
8688 MDB_txn *txn = NULL;
8693 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
8694 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
8695 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
8696 if (my.mc_wbuf[0] == NULL)
8699 pthread_mutex_init(&my.mc_mutex, NULL);
8700 pthread_cond_init(&my.mc_cond, NULL);
8701 #ifdef HAVE_MEMALIGN
8702 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
8703 if (my.mc_wbuf[0] == NULL)
8706 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_os_psize, MDB_WBUF*2);
8711 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
8712 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
8717 my.mc_next_pgno = 2;
8723 THREAD_CREATE(thr, mdb_env_copythr, &my);
8725 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8729 mp = (MDB_page *)my.mc_wbuf[0];
8730 memset(mp, 0, 2*env->me_psize);
8732 mp->mp_flags = P_META;
8733 mm = (MDB_meta *)METADATA(mp);
8734 mdb_env_init_meta0(env, mm);
8735 mm->mm_address = env->me_metas[0]->mm_address;
8737 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
8739 mp->mp_flags = P_META;
8740 *(MDB_meta *)METADATA(mp) = *mm;
8741 mm = (MDB_meta *)METADATA(mp);
8743 /* Count the number of free pages, subtract from lastpg to find
8744 * number of active pages
8747 MDB_ID freecount = 0;
8750 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
8751 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
8752 freecount += *(MDB_ID *)data.mv_data;
8753 freecount += txn->mt_dbs[0].md_branch_pages +
8754 txn->mt_dbs[0].md_leaf_pages +
8755 txn->mt_dbs[0].md_overflow_pages;
8757 /* Set metapage 1 */
8758 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
8759 mm->mm_dbs[1] = txn->mt_dbs[1];
8760 if (mm->mm_last_pg > 1) {
8761 mm->mm_dbs[1].md_root = mm->mm_last_pg;
8764 mm->mm_dbs[1].md_root = P_INVALID;
8767 my.mc_wlen[0] = env->me_psize * 2;
8769 pthread_mutex_lock(&my.mc_mutex);
8771 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8772 pthread_mutex_unlock(&my.mc_mutex);
8773 rc = mdb_env_cwalk(&my, &txn->mt_dbs[1].md_root, 0);
8774 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
8775 rc = mdb_env_cthr_toggle(&my, 1);
8776 mdb_env_cthr_toggle(&my, -1);
8777 pthread_mutex_lock(&my.mc_mutex);
8779 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8780 pthread_mutex_unlock(&my.mc_mutex);
8785 CloseHandle(my.mc_cond);
8786 CloseHandle(my.mc_mutex);
8787 _aligned_free(my.mc_wbuf[0]);
8789 pthread_cond_destroy(&my.mc_cond);
8790 pthread_mutex_destroy(&my.mc_mutex);
8791 free(my.mc_wbuf[0]);
8796 /** Copy environment as-is. */
8798 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
8800 MDB_txn *txn = NULL;
8801 mdb_mutex_t *wmutex = NULL;
8807 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8811 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8814 /* Do the lock/unlock of the reader mutex before starting the
8815 * write txn. Otherwise other read txns could block writers.
8817 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8822 /* We must start the actual read txn after blocking writers */
8823 mdb_txn_reset0(txn, "reset-stage1");
8825 /* Temporarily block writers until we snapshot the meta pages */
8826 wmutex = MDB_MUTEX(env, w);
8827 if (LOCK_MUTEX(rc, env, wmutex))
8830 rc = mdb_txn_renew0(txn);
8832 UNLOCK_MUTEX(wmutex);
8837 wsize = env->me_psize * 2;
8841 DO_WRITE(rc, fd, ptr, w2, len);
8845 } else if (len > 0) {
8851 /* Non-blocking or async handles are not supported */
8857 UNLOCK_MUTEX(wmutex);
8862 w2 = txn->mt_next_pgno * env->me_psize;
8865 if ((rc = mdb_fsize(env->me_fd, &fsize)))
8872 if (wsize > MAX_WRITE)
8876 DO_WRITE(rc, fd, ptr, w2, len);
8880 } else if (len > 0) {
8897 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
8899 if (flags & MDB_CP_COMPACT)
8900 return mdb_env_copyfd1(env, fd);
8902 return mdb_env_copyfd0(env, fd);
8906 mdb_env_copyfd(MDB_env *env, HANDLE fd)
8908 return mdb_env_copyfd2(env, fd, 0);
8912 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
8916 HANDLE newfd = INVALID_HANDLE_VALUE;
8918 if (env->me_flags & MDB_NOSUBDIR) {
8919 lpath = (char *)path;
8922 len += sizeof(DATANAME);
8923 lpath = malloc(len);
8926 sprintf(lpath, "%s" DATANAME, path);
8929 /* The destination path must exist, but the destination file must not.
8930 * We don't want the OS to cache the writes, since the source data is
8931 * already in the OS cache.
8934 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
8935 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
8937 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
8939 if (newfd == INVALID_HANDLE_VALUE) {
8944 if (env->me_psize >= env->me_os_psize) {
8946 /* Set O_DIRECT if the file system supports it */
8947 if ((rc = fcntl(newfd, F_GETFL)) != -1)
8948 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
8950 #ifdef F_NOCACHE /* __APPLE__ */
8951 rc = fcntl(newfd, F_NOCACHE, 1);
8959 rc = mdb_env_copyfd2(env, newfd, flags);
8962 if (!(env->me_flags & MDB_NOSUBDIR))
8964 if (newfd != INVALID_HANDLE_VALUE)
8965 if (close(newfd) < 0 && rc == MDB_SUCCESS)
8972 mdb_env_copy(MDB_env *env, const char *path)
8974 return mdb_env_copy2(env, path, 0);
8978 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
8980 if (flag & (env->me_map ? ~CHANGEABLE : ~(CHANGEABLE|CHANGELESS)))
8983 env->me_flags |= flag;
8985 env->me_flags &= ~flag;
8990 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
8995 *arg = env->me_flags;
9000 mdb_env_set_userctx(MDB_env *env, void *ctx)
9004 env->me_userctx = ctx;
9009 mdb_env_get_userctx(MDB_env *env)
9011 return env ? env->me_userctx : NULL;
9015 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
9020 env->me_assert_func = func;
9026 mdb_env_get_path(MDB_env *env, const char **arg)
9031 *arg = env->me_path;
9036 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
9045 /** Common code for #mdb_stat() and #mdb_env_stat().
9046 * @param[in] env the environment to operate in.
9047 * @param[in] db the #MDB_db record containing the stats to return.
9048 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
9049 * @return 0, this function always succeeds.
9052 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
9054 arg->ms_psize = env->me_psize;
9055 arg->ms_depth = db->md_depth;
9056 arg->ms_branch_pages = db->md_branch_pages;
9057 arg->ms_leaf_pages = db->md_leaf_pages;
9058 arg->ms_overflow_pages = db->md_overflow_pages;
9059 arg->ms_entries = db->md_entries;
9065 mdb_env_stat(MDB_env *env, MDB_stat *arg)
9069 if (env == NULL || arg == NULL)
9072 toggle = mdb_env_pick_meta(env);
9074 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
9078 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
9082 if (env == NULL || arg == NULL)
9085 toggle = mdb_env_pick_meta(env);
9086 arg->me_mapaddr = env->me_metas[toggle]->mm_address;
9087 arg->me_mapsize = env->me_mapsize;
9088 arg->me_maxreaders = env->me_maxreaders;
9090 /* me_numreaders may be zero if this process never used any readers. Use
9091 * the shared numreader count if it exists.
9093 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
9095 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
9096 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
9100 /** Set the default comparison functions for a database.
9101 * Called immediately after a database is opened to set the defaults.
9102 * The user can then override them with #mdb_set_compare() or
9103 * #mdb_set_dupsort().
9104 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
9105 * @param[in] dbi A database handle returned by #mdb_dbi_open()
9108 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
9110 uint16_t f = txn->mt_dbs[dbi].md_flags;
9112 txn->mt_dbxs[dbi].md_cmp =
9113 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
9114 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
9116 txn->mt_dbxs[dbi].md_dcmp =
9117 !(f & MDB_DUPSORT) ? 0 :
9118 ((f & MDB_INTEGERDUP)
9119 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
9120 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
9123 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
9129 int rc, dbflag, exact;
9130 unsigned int unused = 0, seq;
9133 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
9134 mdb_default_cmp(txn, FREE_DBI);
9137 if ((flags & VALID_FLAGS) != flags)
9139 if (txn->mt_flags & MDB_TXN_ERROR)
9145 if (flags & PERSISTENT_FLAGS) {
9146 uint16_t f2 = flags & PERSISTENT_FLAGS;
9147 /* make sure flag changes get committed */
9148 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
9149 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
9150 txn->mt_flags |= MDB_TXN_DIRTY;
9153 mdb_default_cmp(txn, MAIN_DBI);
9157 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
9158 mdb_default_cmp(txn, MAIN_DBI);
9161 /* Is the DB already open? */
9163 for (i=2; i<txn->mt_numdbs; i++) {
9164 if (!txn->mt_dbxs[i].md_name.mv_size) {
9165 /* Remember this free slot */
9166 if (!unused) unused = i;
9169 if (len == txn->mt_dbxs[i].md_name.mv_size &&
9170 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
9176 /* If no free slot and max hit, fail */
9177 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
9178 return MDB_DBS_FULL;
9180 /* Cannot mix named databases with some mainDB flags */
9181 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
9182 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
9184 /* Find the DB info */
9185 dbflag = DB_NEW|DB_VALID;
9188 key.mv_data = (void *)name;
9189 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
9190 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
9191 if (rc == MDB_SUCCESS) {
9192 /* make sure this is actually a DB */
9193 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
9194 if (!(node->mn_flags & F_SUBDATA))
9195 return MDB_INCOMPATIBLE;
9196 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
9197 /* Create if requested */
9198 data.mv_size = sizeof(MDB_db);
9199 data.mv_data = &dummy;
9200 memset(&dummy, 0, sizeof(dummy));
9201 dummy.md_root = P_INVALID;
9202 dummy.md_flags = flags & PERSISTENT_FLAGS;
9203 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
9207 /* OK, got info, add to table */
9208 if (rc == MDB_SUCCESS) {
9209 unsigned int slot = unused ? unused : txn->mt_numdbs;
9210 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
9211 txn->mt_dbxs[slot].md_name.mv_size = len;
9212 txn->mt_dbxs[slot].md_rel = NULL;
9213 txn->mt_dbflags[slot] = dbflag;
9214 /* txn-> and env-> are the same in read txns, use
9215 * tmp variable to avoid undefined assignment
9217 seq = ++txn->mt_env->me_dbiseqs[slot];
9218 txn->mt_dbiseqs[slot] = seq;
9220 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
9222 mdb_default_cmp(txn, slot);
9231 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9233 if (!arg || !TXN_DBI_EXIST(txn, dbi))
9236 if (txn->mt_flags & MDB_TXN_ERROR)
9239 if (txn->mt_dbflags[dbi] & DB_STALE) {
9242 /* Stale, must read the DB's root. cursor_init does it for us. */
9243 mdb_cursor_init(&mc, txn, dbi, &mx);
9245 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9248 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9251 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
9253 ptr = env->me_dbxs[dbi].md_name.mv_data;
9254 /* If there was no name, this was already closed */
9256 env->me_dbxs[dbi].md_name.mv_data = NULL;
9257 env->me_dbxs[dbi].md_name.mv_size = 0;
9258 env->me_dbflags[dbi] = 0;
9259 env->me_dbiseqs[dbi]++;
9264 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9266 /* We could return the flags for the FREE_DBI too but what's the point? */
9267 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9269 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9273 /** Add all the DB's pages to the free list.
9274 * @param[in] mc Cursor on the DB to free.
9275 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9276 * @return 0 on success, non-zero on failure.
9279 mdb_drop0(MDB_cursor *mc, int subs)
9283 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9284 if (rc == MDB_SUCCESS) {
9285 MDB_txn *txn = mc->mc_txn;
9290 /* LEAF2 pages have no nodes, cannot have sub-DBs */
9291 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
9294 mdb_cursor_copy(mc, &mx);
9295 while (mc->mc_snum > 0) {
9296 MDB_page *mp = mc->mc_pg[mc->mc_top];
9297 unsigned n = NUMKEYS(mp);
9299 for (i=0; i<n; i++) {
9300 ni = NODEPTR(mp, i);
9301 if (ni->mn_flags & F_BIGDATA) {
9304 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9305 rc = mdb_page_get(txn, pg, &omp, NULL);
9308 mdb_cassert(mc, IS_OVERFLOW(omp));
9309 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9313 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9314 mdb_xcursor_init1(mc, ni);
9315 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9321 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9323 for (i=0; i<n; i++) {
9325 ni = NODEPTR(mp, i);
9328 mdb_midl_xappend(txn->mt_free_pgs, pg);
9333 mc->mc_ki[mc->mc_top] = i;
9334 rc = mdb_cursor_sibling(mc, 1);
9336 if (rc != MDB_NOTFOUND)
9338 /* no more siblings, go back to beginning
9339 * of previous level.
9343 for (i=1; i<mc->mc_snum; i++) {
9345 mc->mc_pg[i] = mx.mc_pg[i];
9350 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9353 txn->mt_flags |= MDB_TXN_ERROR;
9354 } else if (rc == MDB_NOTFOUND) {
9360 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9362 MDB_cursor *mc, *m2;
9365 if ((unsigned)del > 1 || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9368 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9371 if (dbi > MAIN_DBI && TXN_DBI_CHANGED(txn, dbi))
9374 rc = mdb_cursor_open(txn, dbi, &mc);
9378 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9379 /* Invalidate the dropped DB's cursors */
9380 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9381 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9385 /* Can't delete the main DB */
9386 if (del && dbi > MAIN_DBI) {
9387 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, 0);
9389 txn->mt_dbflags[dbi] = DB_STALE;
9390 mdb_dbi_close(txn->mt_env, dbi);
9392 txn->mt_flags |= MDB_TXN_ERROR;
9395 /* reset the DB record, mark it dirty */
9396 txn->mt_dbflags[dbi] |= DB_DIRTY;
9397 txn->mt_dbs[dbi].md_depth = 0;
9398 txn->mt_dbs[dbi].md_branch_pages = 0;
9399 txn->mt_dbs[dbi].md_leaf_pages = 0;
9400 txn->mt_dbs[dbi].md_overflow_pages = 0;
9401 txn->mt_dbs[dbi].md_entries = 0;
9402 txn->mt_dbs[dbi].md_root = P_INVALID;
9404 txn->mt_flags |= MDB_TXN_DIRTY;
9407 mdb_cursor_close(mc);
9411 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9413 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9416 txn->mt_dbxs[dbi].md_cmp = cmp;
9420 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9422 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9425 txn->mt_dbxs[dbi].md_dcmp = cmp;
9429 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9431 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9434 txn->mt_dbxs[dbi].md_rel = rel;
9438 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9440 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9443 txn->mt_dbxs[dbi].md_relctx = ctx;
9448 mdb_env_get_maxkeysize(MDB_env *env)
9450 return ENV_MAXKEY(env);
9454 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9456 unsigned int i, rdrs;
9459 int rc = 0, first = 1;
9463 if (!env->me_txns) {
9464 return func("(no reader locks)\n", ctx);
9466 rdrs = env->me_txns->mti_numreaders;
9467 mr = env->me_txns->mti_readers;
9468 for (i=0; i<rdrs; i++) {
9470 txnid_t txnid = mr[i].mr_txnid;
9471 sprintf(buf, txnid == (txnid_t)-1 ?
9472 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9473 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9476 rc = func(" pid thread txnid\n", ctx);
9480 rc = func(buf, ctx);
9486 rc = func("(no active readers)\n", ctx);
9491 /** Insert pid into list if not already present.
9492 * return -1 if already present.
9495 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9497 /* binary search of pid in list */
9499 unsigned cursor = 1;
9501 unsigned n = ids[0];
9504 unsigned pivot = n >> 1;
9505 cursor = base + pivot + 1;
9506 val = pid - ids[cursor];
9511 } else if ( val > 0 ) {
9516 /* found, so it's a duplicate */
9525 for (n = ids[0]; n > cursor; n--)
9532 mdb_reader_check(MDB_env *env, int *dead)
9538 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
9541 /** As #mdb_reader_check(). rlocked = <caller locked the reader mutex>. */
9542 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
9544 mdb_mutex_t *rmutex = rlocked ? NULL : MDB_MUTEX(env, r);
9545 unsigned int i, j, rdrs;
9547 MDB_PID_T *pids, pid;
9548 int rc = MDB_SUCCESS, count = 0;
9550 rdrs = env->me_txns->mti_numreaders;
9551 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
9555 mr = env->me_txns->mti_readers;
9556 for (i=0; i<rdrs; i++) {
9558 if (pid && pid != env->me_pid) {
9559 if (mdb_pid_insert(pids, pid) == 0) {
9560 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9561 /* Stale reader found */
9564 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
9565 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
9567 rdrs = 0; /* the above checked all readers */
9569 /* Recheck, a new process may have reused pid */
9570 if (mdb_reader_pid(env, Pidcheck, pid))
9575 if (mr[j].mr_pid == pid) {
9576 DPRINTF(("clear stale reader pid %u txn %"Z"d",
9577 (unsigned) pid, mr[j].mr_txnid));
9582 UNLOCK_MUTEX(rmutex);
9593 #ifdef MDB_ROBUST_SUPPORTED
9594 /** Handle #LOCK_MUTEX0() failure.
9595 * With #MDB_ROBUST, try to repair the lock file if the mutex owner died.
9596 * @param[in] env the environment handle
9597 * @param[in] mutex LOCK_MUTEX0() mutex
9598 * @param[in] rc LOCK_MUTEX0() error (nonzero)
9599 * @return 0 on success with the mutex locked, or an error code on failure.
9601 static int mdb_mutex_failed(MDB_env *env, mdb_mutex_t *mutex, int rc)
9603 int toggle, rlocked, rc2;
9605 enum { WAIT_ABANDONED = EOWNERDEAD };
9608 if (rc == (int) WAIT_ABANDONED) {
9609 /* We own the mutex. Clean up after dead previous owner. */
9611 rlocked = (mutex == MDB_MUTEX(env, r));
9613 /* Keep mti_txnid updated, otherwise next writer can
9614 * overwrite data which latest meta page refers to.
9616 toggle = mdb_env_pick_meta(env);
9617 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
9618 /* env is hosed if the dead thread was ours */
9620 env->me_flags |= MDB_FATAL_ERROR;
9625 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
9626 (rc ? "this process' env is hosed" : "recovering")));
9627 rc2 = mdb_reader_check0(env, rlocked, NULL);
9629 rc2 = pthread_mutex_consistent(mutex);
9630 if (rc || (rc = rc2)) {
9631 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
9632 UNLOCK_MUTEX(mutex);
9638 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
9643 #endif /* MDB_ROBUST_SUPPORTED */