2 * @brief Lightning memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2014 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
41 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
42 * as int64 which is wrong. MSVC doesn't define it at all, so just
46 #define MDB_THR_T DWORD
47 #include <sys/types.h>
50 # include <sys/param.h>
52 # define LITTLE_ENDIAN 1234
53 # define BIG_ENDIAN 4321
54 # define BYTE_ORDER LITTLE_ENDIAN
56 # define SSIZE_MAX INT_MAX
60 #include <sys/types.h>
62 #define MDB_PID_T pid_t
63 #define MDB_THR_T pthread_t
64 #include <sys/param.h>
67 #ifdef HAVE_SYS_FILE_H
73 #if defined(__mips) && defined(__linux)
74 /* MIPS has cache coherency issues, requires explicit cache control */
75 #include <asm/cachectl.h>
76 extern int cacheflush(char *addr, int nbytes, int cache);
77 #define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
79 #define CACHEFLUSH(addr, bytes, cache)
93 #if defined(__sun) || defined(ANDROID)
94 /* Most platforms have posix_memalign, older may only have memalign */
95 #define HAVE_MEMALIGN 1
99 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
100 #include <netinet/in.h>
101 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
104 #if defined(__APPLE__) || defined (BSD)
105 # define MDB_USE_POSIX_SEM 1
106 # define MDB_FDATASYNC fsync
107 #elif defined(ANDROID)
108 # define MDB_FDATASYNC fsync
113 #ifdef MDB_USE_POSIX_SEM
114 # define MDB_USE_HASH 1
115 #include <semaphore.h>
120 #include <valgrind/memcheck.h>
121 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
122 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
123 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
124 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
125 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
127 #define VGMEMP_CREATE(h,r,z)
128 #define VGMEMP_ALLOC(h,a,s)
129 #define VGMEMP_FREE(h,a)
130 #define VGMEMP_DESTROY(h)
131 #define VGMEMP_DEFINED(a,s)
135 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
136 /* Solaris just defines one or the other */
137 # define LITTLE_ENDIAN 1234
138 # define BIG_ENDIAN 4321
139 # ifdef _LITTLE_ENDIAN
140 # define BYTE_ORDER LITTLE_ENDIAN
142 # define BYTE_ORDER BIG_ENDIAN
145 # define BYTE_ORDER __BYTE_ORDER
149 #ifndef LITTLE_ENDIAN
150 #define LITTLE_ENDIAN __LITTLE_ENDIAN
153 #define BIG_ENDIAN __BIG_ENDIAN
156 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
157 #define MISALIGNED_OK 1
163 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
164 # error "Unknown or unsupported endianness (BYTE_ORDER)"
165 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
166 # error "Two's complement, reasonably sized integer types, please"
170 /** Put infrequently used env functions in separate section */
172 # define ESECT __attribute__ ((section("__TEXT,text_env")))
174 # define ESECT __attribute__ ((section("text_env")))
180 /** @defgroup internal LMDB Internals
183 /** @defgroup compat Compatibility Macros
184 * A bunch of macros to minimize the amount of platform-specific ifdefs
185 * needed throughout the rest of the code. When the features this library
186 * needs are similar enough to POSIX to be hidden in a one-or-two line
187 * replacement, this macro approach is used.
191 /** Features under development */
196 /** Wrapper around __func__, which is a C99 feature */
197 #if __STDC_VERSION__ >= 199901L
198 # define mdb_func_ __func__
199 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
200 # define mdb_func_ __FUNCTION__
202 /* If a debug message says <mdb_unknown>(), update the #if statements above */
203 # define mdb_func_ "<mdb_unknown>"
207 #define MDB_USE_HASH 1
208 #define MDB_PIDLOCK 0
209 #define THREAD_RET DWORD
210 #define pthread_t HANDLE
211 #define pthread_mutex_t HANDLE
212 #define pthread_cond_t HANDLE
213 #define pthread_key_t DWORD
214 #define pthread_self() GetCurrentThreadId()
215 #define pthread_key_create(x,y) \
216 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
217 #define pthread_key_delete(x) TlsFree(x)
218 #define pthread_getspecific(x) TlsGetValue(x)
219 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
220 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
221 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
222 #define pthread_cond_signal(x) SetEvent(*x)
223 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
224 #define THREAD_CREATE(thr,start,arg) thr=CreateThread(NULL,0,start,arg,0,NULL)
225 #define THREAD_FINISH(thr) WaitForSingleObject(thr, INFINITE)
226 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_rmutex)
227 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_rmutex)
228 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_wmutex)
229 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_wmutex)
230 #define getpid() GetCurrentProcessId()
231 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
232 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
233 #define ErrCode() GetLastError()
234 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
235 #define close(fd) (CloseHandle(fd) ? 0 : -1)
236 #define munmap(ptr,len) UnmapViewOfFile(ptr)
237 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
238 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
240 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
244 #define THREAD_RET void *
245 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
246 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
247 #define Z "z" /**< printf format modifier for size_t */
249 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
250 #define MDB_PIDLOCK 1
252 #ifdef MDB_USE_POSIX_SEM
254 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
255 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
256 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
257 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
260 mdb_sem_wait(sem_t *sem)
263 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
268 /** Lock the reader mutex.
270 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
271 /** Unlock the reader mutex.
273 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
275 /** Lock the writer mutex.
276 * Only a single write transaction is allowed at a time. Other writers
277 * will block waiting for this mutex.
279 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
280 /** Unlock the writer mutex.
282 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
283 #endif /* MDB_USE_POSIX_SEM */
285 /** Get the error code for the last failed system function.
287 #define ErrCode() errno
289 /** An abstraction for a file handle.
290 * On POSIX systems file handles are small integers. On Windows
291 * they're opaque pointers.
295 /** A value for an invalid file handle.
296 * Mainly used to initialize file variables and signify that they are
299 #define INVALID_HANDLE_VALUE (-1)
301 /** Get the size of a memory page for the system.
302 * This is the basic size that the platform's memory manager uses, and is
303 * fundamental to the use of memory-mapped files.
305 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
308 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
311 #define MNAME_LEN (sizeof(pthread_mutex_t))
317 /** A flag for opening a file and requesting synchronous data writes.
318 * This is only used when writing a meta page. It's not strictly needed;
319 * we could just do a normal write and then immediately perform a flush.
320 * But if this flag is available it saves us an extra system call.
322 * @note If O_DSYNC is undefined but exists in /usr/include,
323 * preferably set some compiler flag to get the definition.
324 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
327 # define MDB_DSYNC O_DSYNC
331 /** Function for flushing the data of a file. Define this to fsync
332 * if fdatasync() is not supported.
334 #ifndef MDB_FDATASYNC
335 # define MDB_FDATASYNC fdatasync
339 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
350 /** A page number in the database.
351 * Note that 64 bit page numbers are overkill, since pages themselves
352 * already represent 12-13 bits of addressable memory, and the OS will
353 * always limit applications to a maximum of 63 bits of address space.
355 * @note In the #MDB_node structure, we only store 48 bits of this value,
356 * which thus limits us to only 60 bits of addressable data.
358 typedef MDB_ID pgno_t;
360 /** A transaction ID.
361 * See struct MDB_txn.mt_txnid for details.
363 typedef MDB_ID txnid_t;
365 /** @defgroup debug Debug Macros
369 /** Enable debug output. Needs variable argument macros (a C99 feature).
370 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
371 * read from and written to the database (used for free space management).
377 static int mdb_debug;
378 static txnid_t mdb_debug_start;
380 /** Print a debug message with printf formatting.
381 * Requires double parenthesis around 2 or more args.
383 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
384 # define DPRINTF0(fmt, ...) \
385 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
387 # define DPRINTF(args) ((void) 0)
389 /** Print a debug string.
390 * The string is printed literally, with no format processing.
392 #define DPUTS(arg) DPRINTF(("%s", arg))
393 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
395 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
398 /** @brief The maximum size of a database page.
400 * It is 32k or 64k, since value-PAGEBASE must fit in
401 * #MDB_page.%mp_upper.
403 * LMDB will use database pages < OS pages if needed.
404 * That causes more I/O in write transactions: The OS must
405 * know (read) the whole page before writing a partial page.
407 * Note that we don't currently support Huge pages. On Linux,
408 * regular data files cannot use Huge pages, and in general
409 * Huge pages aren't actually pageable. We rely on the OS
410 * demand-pager to read our data and page it out when memory
411 * pressure from other processes is high. So until OSs have
412 * actual paging support for Huge pages, they're not viable.
414 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
416 /** The minimum number of keys required in a database page.
417 * Setting this to a larger value will place a smaller bound on the
418 * maximum size of a data item. Data items larger than this size will
419 * be pushed into overflow pages instead of being stored directly in
420 * the B-tree node. This value used to default to 4. With a page size
421 * of 4096 bytes that meant that any item larger than 1024 bytes would
422 * go into an overflow page. That also meant that on average 2-3KB of
423 * each overflow page was wasted space. The value cannot be lower than
424 * 2 because then there would no longer be a tree structure. With this
425 * value, items larger than 2KB will go into overflow pages, and on
426 * average only 1KB will be wasted.
428 #define MDB_MINKEYS 2
430 /** A stamp that identifies a file as an LMDB file.
431 * There's nothing special about this value other than that it is easily
432 * recognizable, and it will reflect any byte order mismatches.
434 #define MDB_MAGIC 0xBEEFC0DE
436 /** The version number for a database's datafile format. */
437 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
438 /** The version number for a database's lockfile format. */
439 #define MDB_LOCK_VERSION 1
441 /** @brief The max size of a key we can write, or 0 for dynamic max.
443 * Define this as 0 to compute the max from the page size. 511
444 * is default for backwards compat: liblmdb <= 0.9.10 can break
445 * when modifying a DB with keys/dupsort data bigger than its max.
446 * #MDB_DEVEL sets the default to 0.
448 * Data items in an #MDB_DUPSORT database are also limited to
449 * this size, since they're actually keys of a sub-DB. Keys and
450 * #MDB_DUPSORT data items must fit on a node in a regular page.
452 #ifndef MDB_MAXKEYSIZE
453 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
456 /** The maximum size of a key we can write to the environment. */
458 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
460 #define ENV_MAXKEY(env) ((env)->me_maxkey)
463 /** @brief The maximum size of a data item.
465 * We only store a 32 bit value for node sizes.
467 #define MAXDATASIZE 0xffffffffUL
470 /** Key size which fits in a #DKBUF.
473 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
476 * This is used for printing a hex dump of a key's contents.
478 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
479 /** Display a key in hex.
481 * Invoke a function to display a key in hex.
483 #define DKEY(x) mdb_dkey(x, kbuf)
489 /** An invalid page number.
490 * Mainly used to denote an empty tree.
492 #define P_INVALID (~(pgno_t)0)
494 /** Test if the flags \b f are set in a flag word \b w. */
495 #define F_ISSET(w, f) (((w) & (f)) == (f))
497 /** Round \b n up to an even number. */
498 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
500 /** Used for offsets within a single page.
501 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
504 typedef uint16_t indx_t;
506 /** Default size of memory map.
507 * This is certainly too small for any actual applications. Apps should always set
508 * the size explicitly using #mdb_env_set_mapsize().
510 #define DEFAULT_MAPSIZE 1048576
512 /** @defgroup readers Reader Lock Table
513 * Readers don't acquire any locks for their data access. Instead, they
514 * simply record their transaction ID in the reader table. The reader
515 * mutex is needed just to find an empty slot in the reader table. The
516 * slot's address is saved in thread-specific data so that subsequent read
517 * transactions started by the same thread need no further locking to proceed.
519 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
521 * No reader table is used if the database is on a read-only filesystem, or
522 * if #MDB_NOLOCK is set.
524 * Since the database uses multi-version concurrency control, readers don't
525 * actually need any locking. This table is used to keep track of which
526 * readers are using data from which old transactions, so that we'll know
527 * when a particular old transaction is no longer in use. Old transactions
528 * that have discarded any data pages can then have those pages reclaimed
529 * for use by a later write transaction.
531 * The lock table is constructed such that reader slots are aligned with the
532 * processor's cache line size. Any slot is only ever used by one thread.
533 * This alignment guarantees that there will be no contention or cache
534 * thrashing as threads update their own slot info, and also eliminates
535 * any need for locking when accessing a slot.
537 * A writer thread will scan every slot in the table to determine the oldest
538 * outstanding reader transaction. Any freed pages older than this will be
539 * reclaimed by the writer. The writer doesn't use any locks when scanning
540 * this table. This means that there's no guarantee that the writer will
541 * see the most up-to-date reader info, but that's not required for correct
542 * operation - all we need is to know the upper bound on the oldest reader,
543 * we don't care at all about the newest reader. So the only consequence of
544 * reading stale information here is that old pages might hang around a
545 * while longer before being reclaimed. That's actually good anyway, because
546 * the longer we delay reclaiming old pages, the more likely it is that a
547 * string of contiguous pages can be found after coalescing old pages from
548 * many old transactions together.
551 /** Number of slots in the reader table.
552 * This value was chosen somewhat arbitrarily. 126 readers plus a
553 * couple mutexes fit exactly into 8KB on my development machine.
554 * Applications should set the table size using #mdb_env_set_maxreaders().
556 #define DEFAULT_READERS 126
558 /** The size of a CPU cache line in bytes. We want our lock structures
559 * aligned to this size to avoid false cache line sharing in the
561 * This value works for most CPUs. For Itanium this should be 128.
567 /** The information we store in a single slot of the reader table.
568 * In addition to a transaction ID, we also record the process and
569 * thread ID that owns a slot, so that we can detect stale information,
570 * e.g. threads or processes that went away without cleaning up.
571 * @note We currently don't check for stale records. We simply re-init
572 * the table when we know that we're the only process opening the
575 typedef struct MDB_rxbody {
576 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
577 * Multiple readers that start at the same time will probably have the
578 * same ID here. Again, it's not important to exclude them from
579 * anything; all we need to know is which version of the DB they
580 * started from so we can avoid overwriting any data used in that
581 * particular version.
584 /** The process ID of the process owning this reader txn. */
586 /** The thread ID of the thread owning this txn. */
590 /** The actual reader record, with cacheline padding. */
591 typedef struct MDB_reader {
594 /** shorthand for mrb_txnid */
595 #define mr_txnid mru.mrx.mrb_txnid
596 #define mr_pid mru.mrx.mrb_pid
597 #define mr_tid mru.mrx.mrb_tid
598 /** cache line alignment */
599 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
603 /** The header for the reader table.
604 * The table resides in a memory-mapped file. (This is a different file
605 * than is used for the main database.)
607 * For POSIX the actual mutexes reside in the shared memory of this
608 * mapped file. On Windows, mutexes are named objects allocated by the
609 * kernel; we store the mutex names in this mapped file so that other
610 * processes can grab them. This same approach is also used on
611 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
612 * process-shared POSIX mutexes. For these cases where a named object
613 * is used, the object name is derived from a 64 bit FNV hash of the
614 * environment pathname. As such, naming collisions are extremely
615 * unlikely. If a collision occurs, the results are unpredictable.
617 typedef struct MDB_txbody {
618 /** Stamp identifying this as an LMDB file. It must be set
621 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
623 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
624 char mtb_rmname[MNAME_LEN];
626 /** Mutex protecting access to this table.
627 * This is the reader lock that #LOCK_MUTEX_R acquires.
629 pthread_mutex_t mtb_mutex;
631 /** The ID of the last transaction committed to the database.
632 * This is recorded here only for convenience; the value can always
633 * be determined by reading the main database meta pages.
636 /** The number of slots that have been used in the reader table.
637 * This always records the maximum count, it is not decremented
638 * when readers release their slots.
640 unsigned mtb_numreaders;
643 /** The actual reader table definition. */
644 typedef struct MDB_txninfo {
647 #define mti_magic mt1.mtb.mtb_magic
648 #define mti_format mt1.mtb.mtb_format
649 #define mti_mutex mt1.mtb.mtb_mutex
650 #define mti_rmname mt1.mtb.mtb_rmname
651 #define mti_txnid mt1.mtb.mtb_txnid
652 #define mti_numreaders mt1.mtb.mtb_numreaders
653 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
656 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
657 char mt2_wmname[MNAME_LEN];
658 #define mti_wmname mt2.mt2_wmname
660 pthread_mutex_t mt2_wmutex;
661 #define mti_wmutex mt2.mt2_wmutex
663 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
665 MDB_reader mti_readers[1];
668 /** Lockfile format signature: version, features and field layout */
669 #define MDB_LOCK_FORMAT \
671 ((MDB_LOCK_VERSION) \
672 /* Flags which describe functionality */ \
673 + (((MDB_PIDLOCK) != 0) << 16)))
676 /** Common header for all page types.
677 * Overflow records occupy a number of contiguous pages with no
678 * headers on any page after the first.
680 typedef struct MDB_page {
681 #define mp_pgno mp_p.p_pgno
682 #define mp_next mp_p.p_next
684 pgno_t p_pgno; /**< page number */
685 struct MDB_page *p_next; /**< for in-memory list of freed pages */
688 /** @defgroup mdb_page Page Flags
690 * Flags for the page headers.
693 #define P_BRANCH 0x01 /**< branch page */
694 #define P_LEAF 0x02 /**< leaf page */
695 #define P_OVERFLOW 0x04 /**< overflow page */
696 #define P_META 0x08 /**< meta page */
697 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
698 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
699 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
700 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
701 #define P_KEEP 0x8000 /**< leave this page alone during spill */
703 uint16_t mp_flags; /**< @ref mdb_page */
704 #define mp_lower mp_pb.pb.pb_lower
705 #define mp_upper mp_pb.pb.pb_upper
706 #define mp_pages mp_pb.pb_pages
709 indx_t pb_lower; /**< lower bound of free space */
710 indx_t pb_upper; /**< upper bound of free space */
712 uint32_t pb_pages; /**< number of overflow pages */
714 indx_t mp_ptrs[1]; /**< dynamic size */
717 /** Size of the page header, excluding dynamic data at the end */
718 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
720 /** Address of first usable data byte in a page, after the header */
721 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
723 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
724 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
726 /** Number of nodes on a page */
727 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
729 /** The amount of space remaining in the page */
730 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
732 /** The percentage of space used in the page, in tenths of a percent. */
733 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
734 ((env)->me_psize - PAGEHDRSZ))
735 /** The minimum page fill factor, in tenths of a percent.
736 * Pages emptier than this are candidates for merging.
738 #define FILL_THRESHOLD 250
740 /** Test if a page is a leaf page */
741 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
742 /** Test if a page is a LEAF2 page */
743 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
744 /** Test if a page is a branch page */
745 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
746 /** Test if a page is an overflow page */
747 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
748 /** Test if a page is a sub page */
749 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
751 /** The number of overflow pages needed to store the given size. */
752 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
754 /** Link in #MDB_txn.%mt_loose_pgs list */
755 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
757 /** Header for a single key/data pair within a page.
758 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
759 * We guarantee 2-byte alignment for 'MDB_node's.
761 typedef struct MDB_node {
762 /** lo and hi are used for data size on leaf nodes and for
763 * child pgno on branch nodes. On 64 bit platforms, flags
764 * is also used for pgno. (Branch nodes have no flags).
765 * They are in host byte order in case that lets some
766 * accesses be optimized into a 32-bit word access.
768 #if BYTE_ORDER == LITTLE_ENDIAN
769 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
771 unsigned short mn_hi, mn_lo;
773 /** @defgroup mdb_node Node Flags
775 * Flags for node headers.
778 #define F_BIGDATA 0x01 /**< data put on overflow page */
779 #define F_SUBDATA 0x02 /**< data is a sub-database */
780 #define F_DUPDATA 0x04 /**< data has duplicates */
782 /** valid flags for #mdb_node_add() */
783 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
786 unsigned short mn_flags; /**< @ref mdb_node */
787 unsigned short mn_ksize; /**< key size */
788 char mn_data[1]; /**< key and data are appended here */
791 /** Size of the node header, excluding dynamic data at the end */
792 #define NODESIZE offsetof(MDB_node, mn_data)
794 /** Bit position of top word in page number, for shifting mn_flags */
795 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
797 /** Size of a node in a branch page with a given key.
798 * This is just the node header plus the key, there is no data.
800 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
802 /** Size of a node in a leaf page with a given key and data.
803 * This is node header plus key plus data size.
805 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
807 /** Address of node \b i in page \b p */
808 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
810 /** Address of the key for the node */
811 #define NODEKEY(node) (void *)((node)->mn_data)
813 /** Address of the data for a node */
814 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
816 /** Get the page number pointed to by a branch node */
817 #define NODEPGNO(node) \
818 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
819 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
820 /** Set the page number in a branch node */
821 #define SETPGNO(node,pgno) do { \
822 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
823 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
825 /** Get the size of the data in a leaf node */
826 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
827 /** Set the size of the data for a leaf node */
828 #define SETDSZ(node,size) do { \
829 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
830 /** The size of a key in a node */
831 #define NODEKSZ(node) ((node)->mn_ksize)
833 /** Copy a page number from src to dst */
835 #define COPY_PGNO(dst,src) dst = src
837 #if SIZE_MAX > 4294967295UL
838 #define COPY_PGNO(dst,src) do { \
839 unsigned short *s, *d; \
840 s = (unsigned short *)&(src); \
841 d = (unsigned short *)&(dst); \
848 #define COPY_PGNO(dst,src) do { \
849 unsigned short *s, *d; \
850 s = (unsigned short *)&(src); \
851 d = (unsigned short *)&(dst); \
857 /** The address of a key in a LEAF2 page.
858 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
859 * There are no node headers, keys are stored contiguously.
861 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
863 /** Set the \b node's key into \b keyptr, if requested. */
864 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
865 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
867 /** Set the \b node's key into \b key. */
868 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
870 /** Information about a single database in the environment. */
871 typedef struct MDB_db {
872 uint32_t md_pad; /**< also ksize for LEAF2 pages */
873 uint16_t md_flags; /**< @ref mdb_dbi_open */
874 uint16_t md_depth; /**< depth of this tree */
875 pgno_t md_branch_pages; /**< number of internal pages */
876 pgno_t md_leaf_pages; /**< number of leaf pages */
877 pgno_t md_overflow_pages; /**< number of overflow pages */
878 size_t md_entries; /**< number of data items */
879 pgno_t md_root; /**< the root page of this tree */
882 /** mdb_dbi_open flags */
883 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
884 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
885 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
886 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
888 /** Handle for the DB used to track free pages. */
890 /** Handle for the default DB. */
893 /** Meta page content.
894 * A meta page is the start point for accessing a database snapshot.
895 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
897 typedef struct MDB_meta {
898 /** Stamp identifying this as an LMDB file. It must be set
901 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
903 void *mm_address; /**< address for fixed mapping */
904 size_t mm_mapsize; /**< size of mmap region */
905 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
906 /** The size of pages used in this DB */
907 #define mm_psize mm_dbs[0].md_pad
908 /** Any persistent environment flags. @ref mdb_env */
909 #define mm_flags mm_dbs[0].md_flags
910 pgno_t mm_last_pg; /**< last used page in file */
911 txnid_t mm_txnid; /**< txnid that committed this page */
914 /** Buffer for a stack-allocated meta page.
915 * The members define size and alignment, and silence type
916 * aliasing warnings. They are not used directly; that could
917 * mean incorrectly using several union members in parallel.
919 typedef union MDB_metabuf {
922 char mm_pad[PAGEHDRSZ];
927 /** Auxiliary DB info.
928 * The information here is mostly static/read-only. There is
929 * only a single copy of this record in the environment.
931 typedef struct MDB_dbx {
932 MDB_val md_name; /**< name of the database */
933 MDB_cmp_func *md_cmp; /**< function for comparing keys */
934 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
935 MDB_rel_func *md_rel; /**< user relocate function */
936 void *md_relctx; /**< user-provided context for md_rel */
939 /** A database transaction.
940 * Every operation requires a transaction handle.
943 MDB_txn *mt_parent; /**< parent of a nested txn */
944 MDB_txn *mt_child; /**< nested txn under this txn */
945 pgno_t mt_next_pgno; /**< next unallocated page */
946 /** The ID of this transaction. IDs are integers incrementing from 1.
947 * Only committed write transactions increment the ID. If a transaction
948 * aborts, the ID may be re-used by the next writer.
951 MDB_env *mt_env; /**< the DB environment */
952 /** The list of pages that became unused during this transaction.
955 /** The list of loose pages that became unused and may be reused
956 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
958 MDB_page *mt_loose_pgs;
959 /* #Number of loose pages (#mt_loose_pgs) */
961 /** The sorted list of dirty pages we temporarily wrote to disk
962 * because the dirty list was full. page numbers in here are
963 * shifted left by 1, deleted slots have the LSB set.
965 MDB_IDL mt_spill_pgs;
967 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
969 /** For read txns: This thread/txn's reader table slot, or NULL. */
972 /** Array of records for each DB known in the environment. */
974 /** Array of MDB_db records for each known DB */
976 /** Array of sequence numbers for each DB handle */
977 unsigned int *mt_dbiseqs;
978 /** @defgroup mt_dbflag Transaction DB Flags
982 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
983 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
984 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
985 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
987 /** In write txns, array of cursors for each DB */
988 MDB_cursor **mt_cursors;
989 /** Array of flags for each DB */
990 unsigned char *mt_dbflags;
991 /** Number of DB records in use. This number only ever increments;
992 * we don't decrement it when individual DB handles are closed.
996 /** @defgroup mdb_txn Transaction Flags
1000 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
1001 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1002 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1003 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1005 unsigned int mt_flags; /**< @ref mdb_txn */
1006 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1007 * Includes ancestor txns' dirty pages not hidden by other txns'
1008 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1009 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1011 unsigned int mt_dirty_room;
1014 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1015 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1016 * raise this on a 64 bit machine.
1018 #define CURSOR_STACK 32
1022 /** Cursors are used for all DB operations.
1023 * A cursor holds a path of (page pointer, key index) from the DB
1024 * root to a position in the DB, plus other state. #MDB_DUPSORT
1025 * cursors include an xcursor to the current data item. Write txns
1026 * track their cursors and keep them up to date when data moves.
1027 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1028 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1031 /** Next cursor on this DB in this txn */
1032 MDB_cursor *mc_next;
1033 /** Backup of the original cursor if this cursor is a shadow */
1034 MDB_cursor *mc_backup;
1035 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1036 struct MDB_xcursor *mc_xcursor;
1037 /** The transaction that owns this cursor */
1039 /** The database handle this cursor operates on */
1041 /** The database record for this cursor */
1043 /** The database auxiliary record for this cursor */
1045 /** The @ref mt_dbflag for this database */
1046 unsigned char *mc_dbflag;
1047 unsigned short mc_snum; /**< number of pushed pages */
1048 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1049 /** @defgroup mdb_cursor Cursor Flags
1051 * Cursor state flags.
1054 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1055 #define C_EOF 0x02 /**< No more data */
1056 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1057 #define C_DEL 0x08 /**< last op was a cursor_del */
1058 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
1059 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1061 unsigned int mc_flags; /**< @ref mdb_cursor */
1062 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1063 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1066 /** Context for sorted-dup records.
1067 * We could have gone to a fully recursive design, with arbitrarily
1068 * deep nesting of sub-databases. But for now we only handle these
1069 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1071 typedef struct MDB_xcursor {
1072 /** A sub-cursor for traversing the Dup DB */
1073 MDB_cursor mx_cursor;
1074 /** The database record for this Dup DB */
1076 /** The auxiliary DB record for this Dup DB */
1078 /** The @ref mt_dbflag for this Dup DB */
1079 unsigned char mx_dbflag;
1082 /** State of FreeDB old pages, stored in the MDB_env */
1083 typedef struct MDB_pgstate {
1084 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1085 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1088 /** The database environment. */
1090 HANDLE me_fd; /**< The main data file */
1091 HANDLE me_lfd; /**< The lock file */
1092 HANDLE me_mfd; /**< just for writing the meta pages */
1093 /** Failed to update the meta page. Probably an I/O error. */
1094 #define MDB_FATAL_ERROR 0x80000000U
1095 /** Some fields are initialized. */
1096 #define MDB_ENV_ACTIVE 0x20000000U
1097 /** me_txkey is set */
1098 #define MDB_ENV_TXKEY 0x10000000U
1099 uint32_t me_flags; /**< @ref mdb_env */
1100 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1101 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1102 unsigned int me_maxreaders; /**< size of the reader table */
1103 unsigned int me_numreaders; /**< max numreaders set by this env */
1104 MDB_dbi me_numdbs; /**< number of DBs opened */
1105 MDB_dbi me_maxdbs; /**< size of the DB table */
1106 MDB_PID_T me_pid; /**< process ID of this env */
1107 char *me_path; /**< path to the DB files */
1108 char *me_map; /**< the memory map of the data file */
1109 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1110 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
1111 void *me_pbuf; /**< scratch area for DUPSORT put() */
1112 MDB_txn *me_txn; /**< current write transaction */
1113 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1114 size_t me_mapsize; /**< size of the data memory map */
1115 off_t me_size; /**< current file size */
1116 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1117 MDB_dbx *me_dbxs; /**< array of static DB info */
1118 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1119 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1120 pthread_key_t me_txkey; /**< thread-key for readers */
1121 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1122 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1123 # define me_pglast me_pgstate.mf_pglast
1124 # define me_pghead me_pgstate.mf_pghead
1125 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1126 /** IDL of pages that became unused in a write txn */
1127 MDB_IDL me_free_pgs;
1128 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1129 MDB_ID2L me_dirty_list;
1130 /** Max number of freelist items that can fit in a single overflow page */
1132 /** Max size of a node on a page */
1133 unsigned int me_nodemax;
1134 #if !(MDB_MAXKEYSIZE)
1135 unsigned int me_maxkey; /**< max size of a key */
1137 int me_live_reader; /**< have liveness lock in reader table */
1139 int me_pidquery; /**< Used in OpenProcess */
1140 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
1142 #elif defined(MDB_USE_POSIX_SEM)
1143 sem_t *me_rmutex; /* Shared mutexes are not supported */
1147 int me_fsynconly; /**< fdatasync is unreliable */
1149 void *me_userctx; /**< User-settable context */
1150 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1153 /** Nested transaction */
1154 typedef struct MDB_ntxn {
1155 MDB_txn mnt_txn; /**< the transaction */
1156 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1159 /** max number of pages to commit in one writev() call */
1160 #define MDB_COMMIT_PAGES 64
1161 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1162 #undef MDB_COMMIT_PAGES
1163 #define MDB_COMMIT_PAGES IOV_MAX
1166 /** max bytes to write in one call */
1167 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1169 /** Check \b txn and \b dbi arguments to a function */
1170 #define TXN_DBI_EXIST(txn, dbi) \
1171 ((txn) && (dbi) < (txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & DB_VALID))
1173 /** Check for misused \b dbi handles */
1174 #define TXN_DBI_CHANGED(txn, dbi) \
1175 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1177 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1178 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1179 static int mdb_page_touch(MDB_cursor *mc);
1181 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1182 static int mdb_page_search_root(MDB_cursor *mc,
1183 MDB_val *key, int modify);
1184 #define MDB_PS_MODIFY 1
1185 #define MDB_PS_ROOTONLY 2
1186 #define MDB_PS_FIRST 4
1187 #define MDB_PS_LAST 8
1188 static int mdb_page_search(MDB_cursor *mc,
1189 MDB_val *key, int flags);
1190 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1192 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1193 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1194 pgno_t newpgno, unsigned int nflags);
1196 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1197 static int mdb_env_pick_meta(const MDB_env *env);
1198 static int mdb_env_write_meta(MDB_txn *txn);
1199 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1200 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1202 static void mdb_env_close0(MDB_env *env, int excl);
1204 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1205 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1206 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1207 static void mdb_node_del(MDB_cursor *mc, int ksize);
1208 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1209 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1210 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1211 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1212 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1214 static int mdb_rebalance(MDB_cursor *mc);
1215 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1217 static void mdb_cursor_pop(MDB_cursor *mc);
1218 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1220 static int mdb_cursor_del0(MDB_cursor *mc);
1221 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1222 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1223 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1224 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1225 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1227 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1228 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1230 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1231 static void mdb_xcursor_init0(MDB_cursor *mc);
1232 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1234 static int mdb_drop0(MDB_cursor *mc, int subs);
1235 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1238 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1242 static SECURITY_DESCRIPTOR mdb_null_sd;
1243 static SECURITY_ATTRIBUTES mdb_all_sa;
1244 static int mdb_sec_inited;
1247 /** Return the library version info. */
1249 mdb_version(int *major, int *minor, int *patch)
1251 if (major) *major = MDB_VERSION_MAJOR;
1252 if (minor) *minor = MDB_VERSION_MINOR;
1253 if (patch) *patch = MDB_VERSION_PATCH;
1254 return MDB_VERSION_STRING;
1257 /** Table of descriptions for LMDB @ref errors */
1258 static char *const mdb_errstr[] = {
1259 "MDB_KEYEXIST: Key/data pair already exists",
1260 "MDB_NOTFOUND: No matching key/data pair found",
1261 "MDB_PAGE_NOTFOUND: Requested page not found",
1262 "MDB_CORRUPTED: Located page was wrong type",
1263 "MDB_PANIC: Update of meta page failed",
1264 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1265 "MDB_INVALID: File is not an LMDB file",
1266 "MDB_MAP_FULL: Environment mapsize limit reached",
1267 "MDB_DBS_FULL: Environment maxdbs limit reached",
1268 "MDB_READERS_FULL: Environment maxreaders limit reached",
1269 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1270 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1271 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1272 "MDB_PAGE_FULL: Internal error - page has no more space",
1273 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1274 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1275 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1276 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1277 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1278 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1282 mdb_strerror(int err)
1285 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1286 * This works as long as no function between the call to mdb_strerror
1287 * and the actual use of the message uses more than 4K of stack.
1290 char buf[1024], *ptr = buf;
1294 return ("Successful return: 0");
1296 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1297 i = err - MDB_KEYEXIST;
1298 return mdb_errstr[i];
1302 /* These are the C-runtime error codes we use. The comment indicates
1303 * their numeric value, and the Win32 error they would correspond to
1304 * if the error actually came from a Win32 API. A major mess, we should
1305 * have used LMDB-specific error codes for everything.
1308 case ENOENT: /* 2, FILE_NOT_FOUND */
1309 case EIO: /* 5, ACCESS_DENIED */
1310 case ENOMEM: /* 12, INVALID_ACCESS */
1311 case EACCES: /* 13, INVALID_DATA */
1312 case EBUSY: /* 16, CURRENT_DIRECTORY */
1313 case EINVAL: /* 22, BAD_COMMAND */
1314 case ENOSPC: /* 28, OUT_OF_PAPER */
1315 return strerror(err);
1320 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1321 FORMAT_MESSAGE_IGNORE_INSERTS,
1322 NULL, err, 0, ptr, sizeof(buf), (va_list *)pad);
1325 return strerror(err);
1329 /** assert(3) variant in cursor context */
1330 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1331 /** assert(3) variant in transaction context */
1332 #define mdb_tassert(mc, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1333 /** assert(3) variant in environment context */
1334 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1337 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1338 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1341 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1342 const char *func, const char *file, int line)
1345 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1346 file, line, expr_txt, func);
1347 if (env->me_assert_func)
1348 env->me_assert_func(env, buf);
1349 fprintf(stderr, "%s\n", buf);
1353 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1357 /** Return the page number of \b mp which may be sub-page, for debug output */
1359 mdb_dbg_pgno(MDB_page *mp)
1362 COPY_PGNO(ret, mp->mp_pgno);
1366 /** Display a key in hexadecimal and return the address of the result.
1367 * @param[in] key the key to display
1368 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1369 * @return The key in hexadecimal form.
1372 mdb_dkey(MDB_val *key, char *buf)
1375 unsigned char *c = key->mv_data;
1381 if (key->mv_size > DKBUF_MAXKEYSIZE)
1382 return "MDB_MAXKEYSIZE";
1383 /* may want to make this a dynamic check: if the key is mostly
1384 * printable characters, print it as-is instead of converting to hex.
1388 for (i=0; i<key->mv_size; i++)
1389 ptr += sprintf(ptr, "%02x", *c++);
1391 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1397 mdb_leafnode_type(MDB_node *n)
1399 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1400 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1401 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1404 /** Display all the keys in the page. */
1406 mdb_page_list(MDB_page *mp)
1408 pgno_t pgno = mdb_dbg_pgno(mp);
1409 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1411 unsigned int i, nkeys, nsize, total = 0;
1415 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1416 case P_BRANCH: type = "Branch page"; break;
1417 case P_LEAF: type = "Leaf page"; break;
1418 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1419 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1420 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1422 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1423 pgno, mp->mp_pages, state);
1426 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1427 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1430 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1434 nkeys = NUMKEYS(mp);
1435 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1437 for (i=0; i<nkeys; i++) {
1438 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1439 key.mv_size = nsize = mp->mp_pad;
1440 key.mv_data = LEAF2KEY(mp, i, nsize);
1442 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1445 node = NODEPTR(mp, i);
1446 key.mv_size = node->mn_ksize;
1447 key.mv_data = node->mn_data;
1448 nsize = NODESIZE + key.mv_size;
1449 if (IS_BRANCH(mp)) {
1450 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1454 if (F_ISSET(node->mn_flags, F_BIGDATA))
1455 nsize += sizeof(pgno_t);
1457 nsize += NODEDSZ(node);
1459 nsize += sizeof(indx_t);
1460 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1461 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1463 total = EVEN(total);
1465 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1466 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1470 mdb_cursor_chk(MDB_cursor *mc)
1476 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1477 for (i=0; i<mc->mc_top; i++) {
1479 node = NODEPTR(mp, mc->mc_ki[i]);
1480 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1483 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1489 /** Count all the pages in each DB and in the freelist
1490 * and make sure it matches the actual number of pages
1492 * All named DBs must be open for a correct count.
1494 static void mdb_audit(MDB_txn *txn)
1498 MDB_ID freecount, count;
1503 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1504 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1505 freecount += *(MDB_ID *)data.mv_data;
1506 mdb_tassert(txn, rc == MDB_NOTFOUND);
1509 for (i = 0; i<txn->mt_numdbs; i++) {
1511 if (!(txn->mt_dbflags[i] & DB_VALID))
1513 mdb_cursor_init(&mc, txn, i, &mx);
1514 if (txn->mt_dbs[i].md_root == P_INVALID)
1516 count += txn->mt_dbs[i].md_branch_pages +
1517 txn->mt_dbs[i].md_leaf_pages +
1518 txn->mt_dbs[i].md_overflow_pages;
1519 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1520 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1521 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1524 mp = mc.mc_pg[mc.mc_top];
1525 for (j=0; j<NUMKEYS(mp); j++) {
1526 MDB_node *leaf = NODEPTR(mp, j);
1527 if (leaf->mn_flags & F_SUBDATA) {
1529 memcpy(&db, NODEDATA(leaf), sizeof(db));
1530 count += db.md_branch_pages + db.md_leaf_pages +
1531 db.md_overflow_pages;
1535 mdb_tassert(txn, rc == MDB_NOTFOUND);
1538 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1539 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1540 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1546 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1548 return txn->mt_dbxs[dbi].md_cmp(a, b);
1552 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1554 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1557 /** Allocate memory for a page.
1558 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1561 mdb_page_malloc(MDB_txn *txn, unsigned num)
1563 MDB_env *env = txn->mt_env;
1564 MDB_page *ret = env->me_dpages;
1565 size_t psize = env->me_psize, sz = psize, off;
1566 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1567 * For a single page alloc, we init everything after the page header.
1568 * For multi-page, we init the final page; if the caller needed that
1569 * many pages they will be filling in at least up to the last page.
1573 VGMEMP_ALLOC(env, ret, sz);
1574 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1575 env->me_dpages = ret->mp_next;
1578 psize -= off = PAGEHDRSZ;
1583 if ((ret = malloc(sz)) != NULL) {
1584 VGMEMP_ALLOC(env, ret, sz);
1585 if (!(env->me_flags & MDB_NOMEMINIT)) {
1586 memset((char *)ret + off, 0, psize);
1590 txn->mt_flags |= MDB_TXN_ERROR;
1594 /** Free a single page.
1595 * Saves single pages to a list, for future reuse.
1596 * (This is not used for multi-page overflow pages.)
1599 mdb_page_free(MDB_env *env, MDB_page *mp)
1601 mp->mp_next = env->me_dpages;
1602 VGMEMP_FREE(env, mp);
1603 env->me_dpages = mp;
1606 /** Free a dirty page */
1608 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1610 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1611 mdb_page_free(env, dp);
1613 /* large pages just get freed directly */
1614 VGMEMP_FREE(env, dp);
1619 /** Return all dirty pages to dpage list */
1621 mdb_dlist_free(MDB_txn *txn)
1623 MDB_env *env = txn->mt_env;
1624 MDB_ID2L dl = txn->mt_u.dirty_list;
1625 unsigned i, n = dl[0].mid;
1627 for (i = 1; i <= n; i++) {
1628 mdb_dpage_free(env, dl[i].mptr);
1633 /** Loosen or free a single page.
1634 * Saves single pages to a list for future reuse
1635 * in this same txn. It has been pulled from the freeDB
1636 * and already resides on the dirty list, but has been
1637 * deleted. Use these pages first before pulling again
1640 * If the page wasn't dirtied in this txn, just add it
1641 * to this txn's free list.
1644 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1647 pgno_t pgno = mp->mp_pgno;
1648 MDB_txn *txn = mc->mc_txn;
1650 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1651 if (txn->mt_parent) {
1652 MDB_ID2 *dl = txn->mt_u.dirty_list;
1653 /* If txn has a parent, make sure the page is in our
1657 unsigned x = mdb_mid2l_search(dl, pgno);
1658 if (x <= dl[0].mid && dl[x].mid == pgno) {
1659 if (mp != dl[x].mptr) { /* bad cursor? */
1660 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1661 txn->mt_flags |= MDB_TXN_ERROR;
1662 return MDB_CORRUPTED;
1669 /* no parent txn, so it's just ours */
1674 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1676 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1677 txn->mt_loose_pgs = mp;
1678 txn->mt_loose_count++;
1679 mp->mp_flags |= P_LOOSE;
1681 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1689 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1690 * @param[in] mc A cursor handle for the current operation.
1691 * @param[in] pflags Flags of the pages to update:
1692 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1693 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1694 * @return 0 on success, non-zero on failure.
1697 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1699 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1700 MDB_txn *txn = mc->mc_txn;
1706 int rc = MDB_SUCCESS, level;
1708 /* Mark pages seen by cursors */
1709 if (mc->mc_flags & C_UNTRACK)
1710 mc = NULL; /* will find mc in mt_cursors */
1711 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1712 for (; mc; mc=mc->mc_next) {
1713 if (!(mc->mc_flags & C_INITIALIZED))
1715 for (m3 = mc;; m3 = &mx->mx_cursor) {
1717 for (j=0; j<m3->mc_snum; j++) {
1719 if ((mp->mp_flags & Mask) == pflags)
1720 mp->mp_flags ^= P_KEEP;
1722 mx = m3->mc_xcursor;
1723 /* Proceed to mx if it is at a sub-database */
1724 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1726 if (! (mp && (mp->mp_flags & P_LEAF)))
1728 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1729 if (!(leaf->mn_flags & F_SUBDATA))
1738 /* Mark dirty root pages */
1739 for (i=0; i<txn->mt_numdbs; i++) {
1740 if (txn->mt_dbflags[i] & DB_DIRTY) {
1741 pgno_t pgno = txn->mt_dbs[i].md_root;
1742 if (pgno == P_INVALID)
1744 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1746 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1747 dp->mp_flags ^= P_KEEP;
1755 static int mdb_page_flush(MDB_txn *txn, int keep);
1757 /** Spill pages from the dirty list back to disk.
1758 * This is intended to prevent running into #MDB_TXN_FULL situations,
1759 * but note that they may still occur in a few cases:
1760 * 1) our estimate of the txn size could be too small. Currently this
1761 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1762 * 2) child txns may run out of space if their parents dirtied a
1763 * lot of pages and never spilled them. TODO: we probably should do
1764 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1765 * the parent's dirty_room is below a given threshold.
1767 * Otherwise, if not using nested txns, it is expected that apps will
1768 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1769 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1770 * If the txn never references them again, they can be left alone.
1771 * If the txn only reads them, they can be used without any fuss.
1772 * If the txn writes them again, they can be dirtied immediately without
1773 * going thru all of the work of #mdb_page_touch(). Such references are
1774 * handled by #mdb_page_unspill().
1776 * Also note, we never spill DB root pages, nor pages of active cursors,
1777 * because we'll need these back again soon anyway. And in nested txns,
1778 * we can't spill a page in a child txn if it was already spilled in a
1779 * parent txn. That would alter the parent txns' data even though
1780 * the child hasn't committed yet, and we'd have no way to undo it if
1781 * the child aborted.
1783 * @param[in] m0 cursor A cursor handle identifying the transaction and
1784 * database for which we are checking space.
1785 * @param[in] key For a put operation, the key being stored.
1786 * @param[in] data For a put operation, the data being stored.
1787 * @return 0 on success, non-zero on failure.
1790 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1792 MDB_txn *txn = m0->mc_txn;
1794 MDB_ID2L dl = txn->mt_u.dirty_list;
1795 unsigned int i, j, need;
1798 if (m0->mc_flags & C_SUB)
1801 /* Estimate how much space this op will take */
1802 i = m0->mc_db->md_depth;
1803 /* Named DBs also dirty the main DB */
1804 if (m0->mc_dbi > MAIN_DBI)
1805 i += txn->mt_dbs[MAIN_DBI].md_depth;
1806 /* For puts, roughly factor in the key+data size */
1808 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1809 i += i; /* double it for good measure */
1812 if (txn->mt_dirty_room > i)
1815 if (!txn->mt_spill_pgs) {
1816 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1817 if (!txn->mt_spill_pgs)
1820 /* purge deleted slots */
1821 MDB_IDL sl = txn->mt_spill_pgs;
1822 unsigned int num = sl[0];
1824 for (i=1; i<=num; i++) {
1831 /* Preserve pages which may soon be dirtied again */
1832 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1835 /* Less aggressive spill - we originally spilled the entire dirty list,
1836 * with a few exceptions for cursor pages and DB root pages. But this
1837 * turns out to be a lot of wasted effort because in a large txn many
1838 * of those pages will need to be used again. So now we spill only 1/8th
1839 * of the dirty pages. Testing revealed this to be a good tradeoff,
1840 * better than 1/2, 1/4, or 1/10.
1842 if (need < MDB_IDL_UM_MAX / 8)
1843 need = MDB_IDL_UM_MAX / 8;
1845 /* Save the page IDs of all the pages we're flushing */
1846 /* flush from the tail forward, this saves a lot of shifting later on. */
1847 for (i=dl[0].mid; i && need; i--) {
1848 MDB_ID pn = dl[i].mid << 1;
1850 if (dp->mp_flags & (P_LOOSE|P_KEEP))
1852 /* Can't spill twice, make sure it's not already in a parent's
1855 if (txn->mt_parent) {
1857 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1858 if (tx2->mt_spill_pgs) {
1859 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1860 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1861 dp->mp_flags |= P_KEEP;
1869 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1873 mdb_midl_sort(txn->mt_spill_pgs);
1875 /* Flush the spilled part of dirty list */
1876 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1879 /* Reset any dirty pages we kept that page_flush didn't see */
1880 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1883 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1887 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1889 mdb_find_oldest(MDB_txn *txn)
1892 txnid_t mr, oldest = txn->mt_txnid - 1;
1893 if (txn->mt_env->me_txns) {
1894 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1895 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1906 /** Add a page to the txn's dirty list */
1908 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1911 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
1913 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1914 insert = mdb_mid2l_append;
1916 insert = mdb_mid2l_insert;
1918 mid.mid = mp->mp_pgno;
1920 rc = insert(txn->mt_u.dirty_list, &mid);
1921 mdb_tassert(txn, rc == 0);
1922 txn->mt_dirty_room--;
1925 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1926 * me_pghead and mt_next_pgno.
1928 * If there are free pages available from older transactions, they
1929 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1930 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1931 * and move me_pglast to say which records were consumed. Only this
1932 * function can create me_pghead and move me_pglast/mt_next_pgno.
1933 * @param[in] mc cursor A cursor handle identifying the transaction and
1934 * database for which we are allocating.
1935 * @param[in] num the number of pages to allocate.
1936 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1937 * will always be satisfied by a single contiguous chunk of memory.
1938 * @return 0 on success, non-zero on failure.
1941 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1943 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1944 /* Get at most <Max_retries> more freeDB records once me_pghead
1945 * has enough pages. If not enough, use new pages from the map.
1946 * If <Paranoid> and mc is updating the freeDB, only get new
1947 * records if me_pghead is empty. Then the freelist cannot play
1948 * catch-up with itself by growing while trying to save it.
1950 enum { Paranoid = 1, Max_retries = 500 };
1952 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1954 int rc, retry = num * 60;
1955 MDB_txn *txn = mc->mc_txn;
1956 MDB_env *env = txn->mt_env;
1957 pgno_t pgno, *mop = env->me_pghead;
1958 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
1960 txnid_t oldest = 0, last;
1965 /* If there are any loose pages, just use them */
1966 if (num == 1 && txn->mt_loose_pgs) {
1967 np = txn->mt_loose_pgs;
1968 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
1969 txn->mt_loose_count--;
1970 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
1978 /* If our dirty list is already full, we can't do anything */
1979 if (txn->mt_dirty_room == 0) {
1984 for (op = MDB_FIRST;; op = MDB_NEXT) {
1989 /* Seek a big enough contiguous page range. Prefer
1990 * pages at the tail, just truncating the list.
1996 if (mop[i-n2] == pgno+n2)
2003 if (op == MDB_FIRST) { /* 1st iteration */
2004 /* Prepare to fetch more and coalesce */
2005 last = env->me_pglast;
2006 oldest = env->me_pgoldest;
2007 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2010 key.mv_data = &last; /* will look up last+1 */
2011 key.mv_size = sizeof(last);
2013 if (Paranoid && mc->mc_dbi == FREE_DBI)
2016 if (Paranoid && retry < 0 && mop_len)
2020 /* Do not fetch more if the record will be too recent */
2021 if (oldest <= last) {
2023 oldest = mdb_find_oldest(txn);
2024 env->me_pgoldest = oldest;
2030 rc = mdb_cursor_get(&m2, &key, NULL, op);
2032 if (rc == MDB_NOTFOUND)
2036 last = *(txnid_t*)key.mv_data;
2037 if (oldest <= last) {
2039 oldest = mdb_find_oldest(txn);
2040 env->me_pgoldest = oldest;
2046 np = m2.mc_pg[m2.mc_top];
2047 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2048 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
2051 idl = (MDB_ID *) data.mv_data;
2054 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2059 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2061 mop = env->me_pghead;
2063 env->me_pglast = last;
2065 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2066 last, txn->mt_dbs[FREE_DBI].md_root, i));
2068 DPRINTF(("IDL %"Z"u", idl[j]));
2070 /* Merge in descending sorted order */
2071 mdb_midl_xmerge(mop, idl);
2075 /* Use new pages from the map when nothing suitable in the freeDB */
2077 pgno = txn->mt_next_pgno;
2078 if (pgno + num >= env->me_maxpg) {
2079 DPUTS("DB size maxed out");
2085 if (env->me_flags & MDB_WRITEMAP) {
2086 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2088 if (!(np = mdb_page_malloc(txn, num))) {
2094 mop[0] = mop_len -= num;
2095 /* Move any stragglers down */
2096 for (j = i-num; j < mop_len; )
2097 mop[++j] = mop[++i];
2099 txn->mt_next_pgno = pgno + num;
2102 mdb_page_dirty(txn, np);
2108 txn->mt_flags |= MDB_TXN_ERROR;
2112 /** Copy the used portions of a non-overflow page.
2113 * @param[in] dst page to copy into
2114 * @param[in] src page to copy from
2115 * @param[in] psize size of a page
2118 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2120 enum { Align = sizeof(pgno_t) };
2121 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2123 /* If page isn't full, just copy the used portion. Adjust
2124 * alignment so memcpy may copy words instead of bytes.
2126 if ((unused &= -Align) && !IS_LEAF2(src)) {
2127 upper = (upper + PAGEBASE) & -Align;
2128 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2129 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2132 memcpy(dst, src, psize - unused);
2136 /** Pull a page off the txn's spill list, if present.
2137 * If a page being referenced was spilled to disk in this txn, bring
2138 * it back and make it dirty/writable again.
2139 * @param[in] txn the transaction handle.
2140 * @param[in] mp the page being referenced. It must not be dirty.
2141 * @param[out] ret the writable page, if any. ret is unchanged if
2142 * mp wasn't spilled.
2145 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2147 MDB_env *env = txn->mt_env;
2150 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2152 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2153 if (!tx2->mt_spill_pgs)
2155 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2156 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2159 if (txn->mt_dirty_room == 0)
2160 return MDB_TXN_FULL;
2161 if (IS_OVERFLOW(mp))
2165 if (env->me_flags & MDB_WRITEMAP) {
2168 np = mdb_page_malloc(txn, num);
2172 memcpy(np, mp, num * env->me_psize);
2174 mdb_page_copy(np, mp, env->me_psize);
2177 /* If in current txn, this page is no longer spilled.
2178 * If it happens to be the last page, truncate the spill list.
2179 * Otherwise mark it as deleted by setting the LSB.
2181 if (x == txn->mt_spill_pgs[0])
2182 txn->mt_spill_pgs[0]--;
2184 txn->mt_spill_pgs[x] |= 1;
2185 } /* otherwise, if belonging to a parent txn, the
2186 * page remains spilled until child commits
2189 mdb_page_dirty(txn, np);
2190 np->mp_flags |= P_DIRTY;
2198 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2199 * @param[in] mc cursor pointing to the page to be touched
2200 * @return 0 on success, non-zero on failure.
2203 mdb_page_touch(MDB_cursor *mc)
2205 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2206 MDB_txn *txn = mc->mc_txn;
2207 MDB_cursor *m2, *m3;
2211 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2212 if (txn->mt_flags & MDB_TXN_SPILLS) {
2214 rc = mdb_page_unspill(txn, mp, &np);
2220 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2221 (rc = mdb_page_alloc(mc, 1, &np)))
2224 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2225 mp->mp_pgno, pgno));
2226 mdb_cassert(mc, mp->mp_pgno != pgno);
2227 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2228 /* Update the parent page, if any, to point to the new page */
2230 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2231 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2232 SETPGNO(node, pgno);
2234 mc->mc_db->md_root = pgno;
2236 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2237 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2239 /* If txn has a parent, make sure the page is in our
2243 unsigned x = mdb_mid2l_search(dl, pgno);
2244 if (x <= dl[0].mid && dl[x].mid == pgno) {
2245 if (mp != dl[x].mptr) { /* bad cursor? */
2246 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2247 txn->mt_flags |= MDB_TXN_ERROR;
2248 return MDB_CORRUPTED;
2253 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2255 np = mdb_page_malloc(txn, 1);
2260 rc = mdb_mid2l_insert(dl, &mid);
2261 mdb_cassert(mc, rc == 0);
2266 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2268 np->mp_flags |= P_DIRTY;
2271 /* Adjust cursors pointing to mp */
2272 mc->mc_pg[mc->mc_top] = np;
2273 m2 = txn->mt_cursors[mc->mc_dbi];
2274 if (mc->mc_flags & C_SUB) {
2275 for (; m2; m2=m2->mc_next) {
2276 m3 = &m2->mc_xcursor->mx_cursor;
2277 if (m3->mc_snum < mc->mc_snum) continue;
2278 if (m3->mc_pg[mc->mc_top] == mp)
2279 m3->mc_pg[mc->mc_top] = np;
2282 for (; m2; m2=m2->mc_next) {
2283 if (m2->mc_snum < mc->mc_snum) continue;
2284 if (m2->mc_pg[mc->mc_top] == mp) {
2285 m2->mc_pg[mc->mc_top] = np;
2286 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2288 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2290 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2291 if (!(leaf->mn_flags & F_SUBDATA))
2292 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2300 txn->mt_flags |= MDB_TXN_ERROR;
2305 mdb_env_sync(MDB_env *env, int force)
2308 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2309 if (env->me_flags & MDB_WRITEMAP) {
2310 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2311 ? MS_ASYNC : MS_SYNC;
2312 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2315 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2320 if (env->me_fsynconly) {
2321 if (fsync(env->me_fd))
2325 if (MDB_FDATASYNC(env->me_fd))
2332 /** Back up parent txn's cursors, then grab the originals for tracking */
2334 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2336 MDB_cursor *mc, *bk;
2341 for (i = src->mt_numdbs; --i >= 0; ) {
2342 if ((mc = src->mt_cursors[i]) != NULL) {
2343 size = sizeof(MDB_cursor);
2345 size += sizeof(MDB_xcursor);
2346 for (; mc; mc = bk->mc_next) {
2352 mc->mc_db = &dst->mt_dbs[i];
2353 /* Kill pointers into src - and dst to reduce abuse: The
2354 * user may not use mc until dst ends. Otherwise we'd...
2356 mc->mc_txn = NULL; /* ...set this to dst */
2357 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2358 if ((mx = mc->mc_xcursor) != NULL) {
2359 *(MDB_xcursor *)(bk+1) = *mx;
2360 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2362 mc->mc_next = dst->mt_cursors[i];
2363 dst->mt_cursors[i] = mc;
2370 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2371 * @param[in] txn the transaction handle.
2372 * @param[in] merge true to keep changes to parent cursors, false to revert.
2373 * @return 0 on success, non-zero on failure.
2376 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2378 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2382 for (i = txn->mt_numdbs; --i >= 0; ) {
2383 for (mc = cursors[i]; mc; mc = next) {
2385 if ((bk = mc->mc_backup) != NULL) {
2387 /* Commit changes to parent txn */
2388 mc->mc_next = bk->mc_next;
2389 mc->mc_backup = bk->mc_backup;
2390 mc->mc_txn = bk->mc_txn;
2391 mc->mc_db = bk->mc_db;
2392 mc->mc_dbflag = bk->mc_dbflag;
2393 if ((mx = mc->mc_xcursor) != NULL)
2394 mx->mx_cursor.mc_txn = bk->mc_txn;
2396 /* Abort nested txn */
2398 if ((mx = mc->mc_xcursor) != NULL)
2399 *mx = *(MDB_xcursor *)(bk+1);
2403 /* Only malloced cursors are permanently tracked. */
2411 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2414 mdb_txn_reset0(MDB_txn *txn, const char *act);
2416 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2422 Pidset = F_SETLK, Pidcheck = F_GETLK
2426 /** Set or check a pid lock. Set returns 0 on success.
2427 * Check returns 0 if the process is certainly dead, nonzero if it may
2428 * be alive (the lock exists or an error happened so we do not know).
2430 * On Windows Pidset is a no-op, we merely check for the existence
2431 * of the process with the given pid. On POSIX we use a single byte
2432 * lock on the lockfile, set at an offset equal to the pid.
2435 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2437 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2440 if (op == Pidcheck) {
2441 h = OpenProcess(env->me_pidquery, FALSE, pid);
2442 /* No documented "no such process" code, but other program use this: */
2444 return ErrCode() != ERROR_INVALID_PARAMETER;
2445 /* A process exists until all handles to it close. Has it exited? */
2446 ret = WaitForSingleObject(h, 0) != 0;
2453 struct flock lock_info;
2454 memset(&lock_info, 0, sizeof(lock_info));
2455 lock_info.l_type = F_WRLCK;
2456 lock_info.l_whence = SEEK_SET;
2457 lock_info.l_start = pid;
2458 lock_info.l_len = 1;
2459 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2460 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2462 } else if ((rc = ErrCode()) == EINTR) {
2470 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2471 * @param[in] txn the transaction handle to initialize
2472 * @return 0 on success, non-zero on failure.
2475 mdb_txn_renew0(MDB_txn *txn)
2477 MDB_env *env = txn->mt_env;
2478 MDB_txninfo *ti = env->me_txns;
2482 int rc, new_notls = 0;
2484 if (txn->mt_flags & MDB_TXN_RDONLY) {
2486 txn->mt_numdbs = env->me_numdbs;
2487 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2489 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2490 txn->mt_txnid = meta->mm_txnid;
2491 txn->mt_u.reader = NULL;
2493 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2494 pthread_getspecific(env->me_txkey);
2496 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2497 return MDB_BAD_RSLOT;
2499 MDB_PID_T pid = env->me_pid;
2500 MDB_THR_T tid = pthread_self();
2502 if (!env->me_live_reader) {
2503 rc = mdb_reader_pid(env, Pidset, pid);
2506 env->me_live_reader = 1;
2510 nr = ti->mti_numreaders;
2511 for (i=0; i<nr; i++)
2512 if (ti->mti_readers[i].mr_pid == 0)
2514 if (i == env->me_maxreaders) {
2515 UNLOCK_MUTEX_R(env);
2516 return MDB_READERS_FULL;
2518 ti->mti_readers[i].mr_pid = pid;
2519 ti->mti_readers[i].mr_tid = tid;
2521 ti->mti_numreaders = ++nr;
2522 /* Save numreaders for un-mutexed mdb_env_close() */
2523 env->me_numreaders = nr;
2524 UNLOCK_MUTEX_R(env);
2526 r = &ti->mti_readers[i];
2527 new_notls = (env->me_flags & MDB_NOTLS);
2528 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2533 txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
2534 txn->mt_u.reader = r;
2535 meta = env->me_metas[txn->mt_txnid & 1];
2541 txn->mt_txnid = ti->mti_txnid;
2542 meta = env->me_metas[txn->mt_txnid & 1];
2544 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2545 txn->mt_txnid = meta->mm_txnid;
2548 txn->mt_numdbs = env->me_numdbs;
2551 if (txn->mt_txnid == mdb_debug_start)
2555 txn->mt_child = NULL;
2556 txn->mt_loose_pgs = NULL;
2557 txn->mt_loose_count = 0;
2558 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2559 txn->mt_u.dirty_list = env->me_dirty_list;
2560 txn->mt_u.dirty_list[0].mid = 0;
2561 txn->mt_free_pgs = env->me_free_pgs;
2562 txn->mt_free_pgs[0] = 0;
2563 txn->mt_spill_pgs = NULL;
2565 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2568 /* Copy the DB info and flags */
2569 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2571 /* Moved to here to avoid a data race in read TXNs */
2572 txn->mt_next_pgno = meta->mm_last_pg+1;
2574 for (i=2; i<txn->mt_numdbs; i++) {
2575 x = env->me_dbflags[i];
2576 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2577 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2579 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2581 if (env->me_maxpg < txn->mt_next_pgno) {
2582 mdb_txn_reset0(txn, "renew0-mapfail");
2584 txn->mt_u.reader->mr_pid = 0;
2585 txn->mt_u.reader = NULL;
2587 return MDB_MAP_RESIZED;
2594 mdb_txn_renew(MDB_txn *txn)
2598 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2601 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2602 DPUTS("environment had fatal error, must shutdown!");
2606 rc = mdb_txn_renew0(txn);
2607 if (rc == MDB_SUCCESS) {
2608 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2609 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2610 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2616 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2620 int rc, size, tsize = sizeof(MDB_txn);
2622 if (env->me_flags & MDB_FATAL_ERROR) {
2623 DPUTS("environment had fatal error, must shutdown!");
2626 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2629 /* Nested transactions: Max 1 child, write txns only, no writemap */
2630 if (parent->mt_child ||
2631 (flags & MDB_RDONLY) ||
2632 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2633 (env->me_flags & MDB_WRITEMAP))
2635 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2637 tsize = sizeof(MDB_ntxn);
2640 if (!(flags & MDB_RDONLY)) {
2642 txn = env->me_txn0; /* just reuse preallocated write txn */
2645 /* child txns use own copy of cursors */
2646 size += env->me_maxdbs * sizeof(MDB_cursor *);
2648 size += env->me_maxdbs * (sizeof(MDB_db)+1);
2650 if ((txn = calloc(1, size)) == NULL) {
2651 DPRINTF(("calloc: %s", strerror(errno)));
2654 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2655 if (flags & MDB_RDONLY) {
2656 txn->mt_flags |= MDB_TXN_RDONLY;
2657 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2658 txn->mt_dbiseqs = env->me_dbiseqs;
2660 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2662 txn->mt_dbiseqs = parent->mt_dbiseqs;
2663 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2665 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
2666 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
2674 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2675 if (!txn->mt_u.dirty_list ||
2676 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2678 free(txn->mt_u.dirty_list);
2682 txn->mt_txnid = parent->mt_txnid;
2683 txn->mt_dirty_room = parent->mt_dirty_room;
2684 txn->mt_u.dirty_list[0].mid = 0;
2685 txn->mt_spill_pgs = NULL;
2686 txn->mt_next_pgno = parent->mt_next_pgno;
2687 parent->mt_child = txn;
2688 txn->mt_parent = parent;
2689 txn->mt_numdbs = parent->mt_numdbs;
2690 txn->mt_flags = parent->mt_flags;
2691 txn->mt_dbxs = parent->mt_dbxs;
2692 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2693 /* Copy parent's mt_dbflags, but clear DB_NEW */
2694 for (i=0; i<txn->mt_numdbs; i++)
2695 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2697 ntxn = (MDB_ntxn *)txn;
2698 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2699 if (env->me_pghead) {
2700 size = MDB_IDL_SIZEOF(env->me_pghead);
2701 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2703 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2708 rc = mdb_cursor_shadow(parent, txn);
2710 mdb_txn_reset0(txn, "beginchild-fail");
2712 rc = mdb_txn_renew0(txn);
2715 if (txn != env->me_txn0)
2719 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2720 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2721 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2728 mdb_txn_env(MDB_txn *txn)
2730 if(!txn) return NULL;
2734 /** Export or close DBI handles opened in this txn. */
2736 mdb_dbis_update(MDB_txn *txn, int keep)
2739 MDB_dbi n = txn->mt_numdbs;
2740 MDB_env *env = txn->mt_env;
2741 unsigned char *tdbflags = txn->mt_dbflags;
2743 for (i = n; --i >= 2;) {
2744 if (tdbflags[i] & DB_NEW) {
2746 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2748 char *ptr = env->me_dbxs[i].md_name.mv_data;
2750 env->me_dbxs[i].md_name.mv_data = NULL;
2751 env->me_dbxs[i].md_name.mv_size = 0;
2752 env->me_dbflags[i] = 0;
2753 env->me_dbiseqs[i]++;
2759 if (keep && env->me_numdbs < n)
2763 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2764 * May be called twice for readonly txns: First reset it, then abort.
2765 * @param[in] txn the transaction handle to reset
2766 * @param[in] act why the transaction is being reset
2769 mdb_txn_reset0(MDB_txn *txn, const char *act)
2771 MDB_env *env = txn->mt_env;
2773 /* Close any DBI handles opened in this txn */
2774 mdb_dbis_update(txn, 0);
2776 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2777 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2778 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2780 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2781 if (txn->mt_u.reader) {
2782 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2783 if (!(env->me_flags & MDB_NOTLS))
2784 txn->mt_u.reader = NULL; /* txn does not own reader */
2786 txn->mt_numdbs = 0; /* close nothing if called again */
2787 txn->mt_dbxs = NULL; /* mark txn as reset */
2789 pgno_t *pghead = env->me_pghead;
2791 mdb_cursors_close(txn, 0);
2792 if (!(env->me_flags & MDB_WRITEMAP)) {
2793 mdb_dlist_free(txn);
2796 if (!txn->mt_parent) {
2797 if (mdb_midl_shrink(&txn->mt_free_pgs))
2798 env->me_free_pgs = txn->mt_free_pgs;
2800 env->me_pghead = NULL;
2804 /* The writer mutex was locked in mdb_txn_begin. */
2806 UNLOCK_MUTEX_W(env);
2808 txn->mt_parent->mt_child = NULL;
2809 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2810 mdb_midl_free(txn->mt_free_pgs);
2811 mdb_midl_free(txn->mt_spill_pgs);
2812 free(txn->mt_u.dirty_list);
2815 mdb_midl_free(pghead);
2820 mdb_txn_reset(MDB_txn *txn)
2825 /* This call is only valid for read-only txns */
2826 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2829 mdb_txn_reset0(txn, "reset");
2833 mdb_txn_abort(MDB_txn *txn)
2839 mdb_txn_abort(txn->mt_child);
2841 mdb_txn_reset0(txn, "abort");
2842 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2843 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2844 txn->mt_u.reader->mr_pid = 0;
2846 if (txn != txn->mt_env->me_txn0)
2850 /** Save the freelist as of this transaction to the freeDB.
2851 * This changes the freelist. Keep trying until it stabilizes.
2854 mdb_freelist_save(MDB_txn *txn)
2856 /* env->me_pghead[] can grow and shrink during this call.
2857 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2858 * Page numbers cannot disappear from txn->mt_free_pgs[].
2861 MDB_env *env = txn->mt_env;
2862 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2863 txnid_t pglast = 0, head_id = 0;
2864 pgno_t freecnt = 0, *free_pgs, *mop;
2865 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2867 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2869 if (env->me_pghead) {
2870 /* Make sure first page of freeDB is touched and on freelist */
2871 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2872 if (rc && rc != MDB_NOTFOUND)
2876 if (!env->me_pghead && txn->mt_loose_pgs) {
2877 /* Put loose page numbers in mt_free_pgs, since
2878 * we may be unable to return them to me_pghead.
2880 MDB_page *mp = txn->mt_loose_pgs;
2881 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
2883 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
2884 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2885 txn->mt_loose_pgs = NULL;
2886 txn->mt_loose_count = 0;
2889 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2890 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2891 ? SSIZE_MAX : maxfree_1pg;
2894 /* Come back here after each Put() in case freelist changed */
2899 /* If using records from freeDB which we have not yet
2900 * deleted, delete them and any we reserved for me_pghead.
2902 while (pglast < env->me_pglast) {
2903 rc = mdb_cursor_first(&mc, &key, NULL);
2906 pglast = head_id = *(txnid_t *)key.mv_data;
2907 total_room = head_room = 0;
2908 mdb_tassert(txn, pglast <= env->me_pglast);
2909 rc = mdb_cursor_del(&mc, 0);
2914 /* Save the IDL of pages freed by this txn, to a single record */
2915 if (freecnt < txn->mt_free_pgs[0]) {
2917 /* Make sure last page of freeDB is touched and on freelist */
2918 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2919 if (rc && rc != MDB_NOTFOUND)
2922 free_pgs = txn->mt_free_pgs;
2923 /* Write to last page of freeDB */
2924 key.mv_size = sizeof(txn->mt_txnid);
2925 key.mv_data = &txn->mt_txnid;
2927 freecnt = free_pgs[0];
2928 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2929 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2932 /* Retry if mt_free_pgs[] grew during the Put() */
2933 free_pgs = txn->mt_free_pgs;
2934 } while (freecnt < free_pgs[0]);
2935 mdb_midl_sort(free_pgs);
2936 memcpy(data.mv_data, free_pgs, data.mv_size);
2939 unsigned int i = free_pgs[0];
2940 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2941 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2943 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2949 mop = env->me_pghead;
2950 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
2952 /* Reserve records for me_pghead[]. Split it if multi-page,
2953 * to avoid searching freeDB for a page range. Use keys in
2954 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2956 if (total_room >= mop_len) {
2957 if (total_room == mop_len || --more < 0)
2959 } else if (head_room >= maxfree_1pg && head_id > 1) {
2960 /* Keep current record (overflow page), add a new one */
2964 /* (Re)write {key = head_id, IDL length = head_room} */
2965 total_room -= head_room;
2966 head_room = mop_len - total_room;
2967 if (head_room > maxfree_1pg && head_id > 1) {
2968 /* Overflow multi-page for part of me_pghead */
2969 head_room /= head_id; /* amortize page sizes */
2970 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2971 } else if (head_room < 0) {
2972 /* Rare case, not bothering to delete this record */
2975 key.mv_size = sizeof(head_id);
2976 key.mv_data = &head_id;
2977 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2978 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2981 /* IDL is initially empty, zero out at least the length */
2982 pgs = (pgno_t *)data.mv_data;
2983 j = head_room > clean_limit ? head_room : 0;
2987 total_room += head_room;
2990 /* Return loose page numbers to me_pghead, though usually none are
2991 * left at this point. The pages themselves remain in dirty_list.
2993 if (txn->mt_loose_pgs) {
2994 MDB_page *mp = txn->mt_loose_pgs;
2995 unsigned count = txn->mt_loose_count;
2997 /* Room for loose pages + temp IDL with same */
2998 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3000 mop = env->me_pghead;
3001 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3002 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3003 loose[ ++count ] = mp->mp_pgno;
3005 mdb_midl_sort(loose);
3006 mdb_midl_xmerge(mop, loose);
3007 txn->mt_loose_pgs = NULL;
3008 txn->mt_loose_count = 0;
3012 /* Fill in the reserved me_pghead records */
3018 rc = mdb_cursor_first(&mc, &key, &data);
3019 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3020 txnid_t id = *(txnid_t *)key.mv_data;
3021 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3024 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3026 if (len > mop_len) {
3028 data.mv_size = (len + 1) * sizeof(MDB_ID);
3030 data.mv_data = mop -= len;
3033 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3035 if (rc || !(mop_len -= len))
3042 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3043 * @param[in] txn the transaction that's being committed
3044 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3045 * @return 0 on success, non-zero on failure.
3048 mdb_page_flush(MDB_txn *txn, int keep)
3050 MDB_env *env = txn->mt_env;
3051 MDB_ID2L dl = txn->mt_u.dirty_list;
3052 unsigned psize = env->me_psize, j;
3053 int i, pagecount = dl[0].mid, rc;
3054 size_t size = 0, pos = 0;
3056 MDB_page *dp = NULL;
3060 struct iovec iov[MDB_COMMIT_PAGES];
3061 ssize_t wpos = 0, wsize = 0, wres;
3062 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3068 if (env->me_flags & MDB_WRITEMAP) {
3069 /* Clear dirty flags */
3070 while (++i <= pagecount) {
3072 /* Don't flush this page yet */
3073 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3074 dp->mp_flags &= ~P_KEEP;
3078 dp->mp_flags &= ~P_DIRTY;
3083 /* Write the pages */
3085 if (++i <= pagecount) {
3087 /* Don't flush this page yet */
3088 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3089 dp->mp_flags &= ~P_KEEP;
3094 /* clear dirty flag */
3095 dp->mp_flags &= ~P_DIRTY;
3098 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3103 /* Windows actually supports scatter/gather I/O, but only on
3104 * unbuffered file handles. Since we're relying on the OS page
3105 * cache for all our data, that's self-defeating. So we just
3106 * write pages one at a time. We use the ov structure to set
3107 * the write offset, to at least save the overhead of a Seek
3110 DPRINTF(("committing page %"Z"u", pgno));
3111 memset(&ov, 0, sizeof(ov));
3112 ov.Offset = pos & 0xffffffff;
3113 ov.OffsetHigh = pos >> 16 >> 16;
3114 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3116 DPRINTF(("WriteFile: %d", rc));
3120 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3121 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3123 /* Write previous page(s) */
3124 #ifdef MDB_USE_PWRITEV
3125 wres = pwritev(env->me_fd, iov, n, wpos);
3128 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3130 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3132 DPRINTF(("lseek: %s", strerror(rc)));
3135 wres = writev(env->me_fd, iov, n);
3138 if (wres != wsize) {
3141 DPRINTF(("Write error: %s", strerror(rc)));
3143 rc = EIO; /* TODO: Use which error code? */
3144 DPUTS("short write, filesystem full?");
3155 DPRINTF(("committing page %"Z"u", pgno));
3156 next_pos = pos + size;
3157 iov[n].iov_len = size;
3158 iov[n].iov_base = (char *)dp;
3164 /* MIPS has cache coherency issues, this is a no-op everywhere else
3165 * Note: for any size >= on-chip cache size, entire on-chip cache is
3168 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3170 for (i = keep; ++i <= pagecount; ) {
3172 /* This is a page we skipped above */
3175 dl[j].mid = dp->mp_pgno;
3178 mdb_dpage_free(env, dp);
3183 txn->mt_dirty_room += i - j;
3189 mdb_txn_commit(MDB_txn *txn)
3195 if (txn == NULL || txn->mt_env == NULL)
3198 if (txn->mt_child) {
3199 rc = mdb_txn_commit(txn->mt_child);
3200 txn->mt_child = NULL;
3207 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3208 mdb_dbis_update(txn, 1);
3209 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
3214 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
3215 DPUTS("error flag is set, can't commit");
3217 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3222 if (txn->mt_parent) {
3223 MDB_txn *parent = txn->mt_parent;
3227 unsigned x, y, len, ps_len;
3229 /* Append our free list to parent's */
3230 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3233 mdb_midl_free(txn->mt_free_pgs);
3234 /* Failures after this must either undo the changes
3235 * to the parent or set MDB_TXN_ERROR in the parent.
3238 parent->mt_next_pgno = txn->mt_next_pgno;
3239 parent->mt_flags = txn->mt_flags;
3241 /* Merge our cursors into parent's and close them */
3242 mdb_cursors_close(txn, 1);
3244 /* Update parent's DB table. */
3245 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3246 parent->mt_numdbs = txn->mt_numdbs;
3247 parent->mt_dbflags[0] = txn->mt_dbflags[0];
3248 parent->mt_dbflags[1] = txn->mt_dbflags[1];
3249 for (i=2; i<txn->mt_numdbs; i++) {
3250 /* preserve parent's DB_NEW status */
3251 x = parent->mt_dbflags[i] & DB_NEW;
3252 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3255 dst = parent->mt_u.dirty_list;
3256 src = txn->mt_u.dirty_list;
3257 /* Remove anything in our dirty list from parent's spill list */
3258 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3260 pspill[0] = (pgno_t)-1;
3261 /* Mark our dirty pages as deleted in parent spill list */
3262 for (i=0, len=src[0].mid; ++i <= len; ) {
3263 MDB_ID pn = src[i].mid << 1;
3264 while (pn > pspill[x])
3266 if (pn == pspill[x]) {
3271 /* Squash deleted pagenums if we deleted any */
3272 for (x=y; ++x <= ps_len; )
3273 if (!(pspill[x] & 1))
3274 pspill[++y] = pspill[x];
3278 /* Find len = length of merging our dirty list with parent's */
3280 dst[0].mid = 0; /* simplify loops */
3281 if (parent->mt_parent) {
3282 len = x + src[0].mid;
3283 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3284 for (i = x; y && i; y--) {
3285 pgno_t yp = src[y].mid;
3286 while (yp < dst[i].mid)
3288 if (yp == dst[i].mid) {
3293 } else { /* Simplify the above for single-ancestor case */
3294 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3296 /* Merge our dirty list with parent's */
3298 for (i = len; y; dst[i--] = src[y--]) {
3299 pgno_t yp = src[y].mid;
3300 while (yp < dst[x].mid)
3301 dst[i--] = dst[x--];
3302 if (yp == dst[x].mid)
3303 free(dst[x--].mptr);
3305 mdb_tassert(txn, i == x);
3307 free(txn->mt_u.dirty_list);
3308 parent->mt_dirty_room = txn->mt_dirty_room;
3309 if (txn->mt_spill_pgs) {
3310 if (parent->mt_spill_pgs) {
3311 /* TODO: Prevent failure here, so parent does not fail */
3312 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3314 parent->mt_flags |= MDB_TXN_ERROR;
3315 mdb_midl_free(txn->mt_spill_pgs);
3316 mdb_midl_sort(parent->mt_spill_pgs);
3318 parent->mt_spill_pgs = txn->mt_spill_pgs;
3322 /* Append our loose page list to parent's */
3323 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(lp))
3325 *lp = txn->mt_loose_pgs;
3326 parent->mt_loose_count += txn->mt_loose_count;
3328 parent->mt_child = NULL;
3329 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3334 if (txn != env->me_txn) {
3335 DPUTS("attempt to commit unknown transaction");
3340 mdb_cursors_close(txn, 0);
3342 if (!txn->mt_u.dirty_list[0].mid &&
3343 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3346 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3347 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3349 /* Update DB root pointers */
3350 if (txn->mt_numdbs > 2) {
3354 data.mv_size = sizeof(MDB_db);
3356 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3357 for (i = 2; i < txn->mt_numdbs; i++) {
3358 if (txn->mt_dbflags[i] & DB_DIRTY) {
3359 if (TXN_DBI_CHANGED(txn, i)) {
3363 data.mv_data = &txn->mt_dbs[i];
3364 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
3371 rc = mdb_freelist_save(txn);
3375 mdb_midl_free(env->me_pghead);
3376 env->me_pghead = NULL;
3377 if (mdb_midl_shrink(&txn->mt_free_pgs))
3378 env->me_free_pgs = txn->mt_free_pgs;
3384 if ((rc = mdb_page_flush(txn, 0)) ||
3385 (rc = mdb_env_sync(env, 0)) ||
3386 (rc = mdb_env_write_meta(txn)))
3389 /* Free P_LOOSE pages left behind in dirty_list */
3390 if (!(env->me_flags & MDB_WRITEMAP))
3391 mdb_dlist_free(txn);
3396 mdb_dbis_update(txn, 1);
3399 UNLOCK_MUTEX_W(env);
3400 if (txn != env->me_txn0)
3410 /** Read the environment parameters of a DB environment before
3411 * mapping it into memory.
3412 * @param[in] env the environment handle
3413 * @param[out] meta address of where to store the meta information
3414 * @return 0 on success, non-zero on failure.
3417 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3423 enum { Size = sizeof(pbuf) };
3425 /* We don't know the page size yet, so use a minimum value.
3426 * Read both meta pages so we can use the latest one.
3429 for (i=off=0; i<2; i++, off = meta->mm_psize) {
3433 memset(&ov, 0, sizeof(ov));
3435 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3436 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3439 rc = pread(env->me_fd, &pbuf, Size, off);
3442 if (rc == 0 && off == 0)
3444 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3445 DPRINTF(("read: %s", mdb_strerror(rc)));
3449 p = (MDB_page *)&pbuf;
3451 if (!F_ISSET(p->mp_flags, P_META)) {
3452 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3457 if (m->mm_magic != MDB_MAGIC) {
3458 DPUTS("meta has invalid magic");
3462 if (m->mm_version != MDB_DATA_VERSION) {
3463 DPRINTF(("database is version %u, expected version %u",
3464 m->mm_version, MDB_DATA_VERSION));
3465 return MDB_VERSION_MISMATCH;
3468 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3475 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3477 meta->mm_magic = MDB_MAGIC;
3478 meta->mm_version = MDB_DATA_VERSION;
3479 meta->mm_mapsize = env->me_mapsize;
3480 meta->mm_psize = env->me_psize;
3481 meta->mm_last_pg = 1;
3482 meta->mm_flags = env->me_flags & 0xffff;
3483 meta->mm_flags |= MDB_INTEGERKEY;
3484 meta->mm_dbs[0].md_root = P_INVALID;
3485 meta->mm_dbs[1].md_root = P_INVALID;
3488 /** Write the environment parameters of a freshly created DB environment.
3489 * @param[in] env the environment handle
3490 * @param[out] meta address of where to store the meta information
3491 * @return 0 on success, non-zero on failure.
3494 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3502 memset(&ov, 0, sizeof(ov));
3503 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3505 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3508 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3509 len = pwrite(fd, ptr, size, pos); \
3510 rc = (len >= 0); } while(0)
3513 DPUTS("writing new meta page");
3515 psize = env->me_psize;
3517 mdb_env_init_meta0(env, meta);
3519 p = calloc(2, psize);
3521 p->mp_flags = P_META;
3522 *(MDB_meta *)METADATA(p) = *meta;
3524 q = (MDB_page *)((char *)p + psize);
3526 q->mp_flags = P_META;
3527 *(MDB_meta *)METADATA(q) = *meta;
3529 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3532 else if ((unsigned) len == psize * 2)
3540 /** Update the environment info to commit a transaction.
3541 * @param[in] txn the transaction that's being committed
3542 * @return 0 on success, non-zero on failure.
3545 mdb_env_write_meta(MDB_txn *txn)
3548 MDB_meta meta, metab, *mp;
3551 int rc, len, toggle;
3560 toggle = txn->mt_txnid & 1;
3561 DPRINTF(("writing meta page %d for root page %"Z"u",
3562 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3565 mp = env->me_metas[toggle];
3566 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3567 /* Persist any increases of mapsize config */
3568 if (mapsize < env->me_mapsize)
3569 mapsize = env->me_mapsize;
3571 if (env->me_flags & MDB_WRITEMAP) {
3572 mp->mm_mapsize = mapsize;
3573 mp->mm_dbs[0] = txn->mt_dbs[0];
3574 mp->mm_dbs[1] = txn->mt_dbs[1];
3575 mp->mm_last_pg = txn->mt_next_pgno - 1;
3576 mp->mm_txnid = txn->mt_txnid;
3577 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3578 unsigned meta_size = env->me_psize;
3579 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3582 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3583 if (meta_size < env->me_os_psize)
3584 meta_size += meta_size;
3589 if (MDB_MSYNC(ptr, meta_size, rc)) {
3596 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3597 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3599 meta.mm_mapsize = mapsize;
3600 meta.mm_dbs[0] = txn->mt_dbs[0];
3601 meta.mm_dbs[1] = txn->mt_dbs[1];
3602 meta.mm_last_pg = txn->mt_next_pgno - 1;
3603 meta.mm_txnid = txn->mt_txnid;
3605 off = offsetof(MDB_meta, mm_mapsize);
3606 ptr = (char *)&meta + off;
3607 len = sizeof(MDB_meta) - off;
3609 off += env->me_psize;
3612 /* Write to the SYNC fd */
3613 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3614 env->me_fd : env->me_mfd;
3617 memset(&ov, 0, sizeof(ov));
3619 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3623 rc = pwrite(mfd, ptr, len, off);
3626 rc = rc < 0 ? ErrCode() : EIO;
3627 DPUTS("write failed, disk error?");
3628 /* On a failure, the pagecache still contains the new data.
3629 * Write some old data back, to prevent it from being used.
3630 * Use the non-SYNC fd; we know it will fail anyway.
3632 meta.mm_last_pg = metab.mm_last_pg;
3633 meta.mm_txnid = metab.mm_txnid;
3635 memset(&ov, 0, sizeof(ov));
3637 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3639 r2 = pwrite(env->me_fd, ptr, len, off);
3640 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3643 env->me_flags |= MDB_FATAL_ERROR;
3646 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3647 CACHEFLUSH(env->me_map + off, len, DCACHE);
3649 /* Memory ordering issues are irrelevant; since the entire writer
3650 * is wrapped by wmutex, all of these changes will become visible
3651 * after the wmutex is unlocked. Since the DB is multi-version,
3652 * readers will get consistent data regardless of how fresh or
3653 * how stale their view of these values is.
3656 env->me_txns->mti_txnid = txn->mt_txnid;
3661 /** Check both meta pages to see which one is newer.
3662 * @param[in] env the environment handle
3663 * @return meta toggle (0 or 1).
3666 mdb_env_pick_meta(const MDB_env *env)
3668 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3672 mdb_env_create(MDB_env **env)
3676 e = calloc(1, sizeof(MDB_env));
3680 e->me_maxreaders = DEFAULT_READERS;
3681 e->me_maxdbs = e->me_numdbs = 2;
3682 e->me_fd = INVALID_HANDLE_VALUE;
3683 e->me_lfd = INVALID_HANDLE_VALUE;
3684 e->me_mfd = INVALID_HANDLE_VALUE;
3685 #ifdef MDB_USE_POSIX_SEM
3686 e->me_rmutex = SEM_FAILED;
3687 e->me_wmutex = SEM_FAILED;
3689 e->me_pid = getpid();
3690 GET_PAGESIZE(e->me_os_psize);
3691 VGMEMP_CREATE(e,0,0);
3697 mdb_env_map(MDB_env *env, void *addr)
3700 unsigned int flags = env->me_flags;
3704 LONG sizelo, sizehi;
3707 if (flags & MDB_RDONLY) {
3708 /* Don't set explicit map size, use whatever exists */
3713 msize = env->me_mapsize;
3714 sizelo = msize & 0xffffffff;
3715 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3717 /* Windows won't create mappings for zero length files.
3718 * and won't map more than the file size.
3719 * Just set the maxsize right now.
3721 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3722 || !SetEndOfFile(env->me_fd)
3723 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3727 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3728 PAGE_READWRITE : PAGE_READONLY,
3729 sizehi, sizelo, NULL);
3732 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3733 FILE_MAP_WRITE : FILE_MAP_READ,
3735 rc = env->me_map ? 0 : ErrCode();
3740 int prot = PROT_READ;
3741 if (flags & MDB_WRITEMAP) {
3743 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3746 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3748 if (env->me_map == MAP_FAILED) {
3753 if (flags & MDB_NORDAHEAD) {
3754 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3756 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3758 #ifdef POSIX_MADV_RANDOM
3759 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3760 #endif /* POSIX_MADV_RANDOM */
3761 #endif /* MADV_RANDOM */
3765 /* Can happen because the address argument to mmap() is just a
3766 * hint. mmap() can pick another, e.g. if the range is in use.
3767 * The MAP_FIXED flag would prevent that, but then mmap could
3768 * instead unmap existing pages to make room for the new map.
3770 if (addr && env->me_map != addr)
3771 return EBUSY; /* TODO: Make a new MDB_* error code? */
3773 p = (MDB_page *)env->me_map;
3774 env->me_metas[0] = METADATA(p);
3775 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3781 mdb_env_set_mapsize(MDB_env *env, size_t size)
3783 /* If env is already open, caller is responsible for making
3784 * sure there are no active txns.
3792 size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3793 else if (size < env->me_mapsize) {
3794 /* If the configured size is smaller, make sure it's
3795 * still big enough. Silently round up to minimum if not.
3797 size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3801 munmap(env->me_map, env->me_mapsize);
3802 env->me_mapsize = size;
3803 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3804 rc = mdb_env_map(env, old);
3808 env->me_mapsize = size;
3810 env->me_maxpg = env->me_mapsize / env->me_psize;
3815 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3819 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3824 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3826 if (env->me_map || readers < 1)
3828 env->me_maxreaders = readers;
3833 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3835 if (!env || !readers)
3837 *readers = env->me_maxreaders;
3842 mdb_fsize(HANDLE fd, size_t *size)
3845 LARGE_INTEGER fsize;
3847 if (!GetFileSizeEx(fd, &fsize))
3850 *size = fsize.QuadPart;
3863 #include <sys/utsname.h>
3864 #include <sys/vfs.h>
3867 /** Further setup required for opening an LMDB environment
3870 mdb_env_open2(MDB_env *env)
3872 unsigned int flags = env->me_flags;
3873 int i, newenv = 0, rc;
3877 /* See if we should use QueryLimited */
3879 if ((rc & 0xff) > 5)
3880 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3882 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3885 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
3886 * https://lkml.org/lkml/2012/9/3/83
3887 * Kernels after 3.6-rc6 are known good.
3888 * https://lkml.org/lkml/2012/9/10/556
3889 * See if the DB is on ext3/ext4, then check for new enough kernel
3890 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
3895 fstatfs(env->me_fd, &st);
3896 while (st.f_type == 0xEF53) {
3900 if (uts.release[0] < '3') {
3901 if (!strncmp(uts.release, "2.6.32.", 7)) {
3902 i = atoi(uts.release+7);
3904 break; /* 2.6.32.60 and newer is OK */
3905 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
3906 i = atoi(uts.release+7);
3908 break; /* 2.6.34.15 and newer is OK */
3910 } else if (uts.release[0] == '3') {
3911 i = atoi(uts.release+2);
3913 break; /* 3.6 and newer is OK */
3915 i = atoi(uts.release+4);
3917 break; /* 3.5.4 and newer is OK */
3918 } else if (i == 2) {
3919 i = atoi(uts.release+4);
3921 break; /* 3.2.30 and newer is OK */
3923 } else { /* 4.x and newer is OK */
3926 env->me_fsynconly = 1;
3932 memset(&meta, 0, sizeof(meta));
3934 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3937 DPUTS("new mdbenv");
3939 env->me_psize = env->me_os_psize;
3940 if (env->me_psize > MAX_PAGESIZE)
3941 env->me_psize = MAX_PAGESIZE;
3943 env->me_psize = meta.mm_psize;
3946 /* Was a mapsize configured? */
3947 if (!env->me_mapsize) {
3948 /* If this is a new environment, take the default,
3949 * else use the size recorded in the existing env.
3951 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3952 } else if (env->me_mapsize < meta.mm_mapsize) {
3953 /* If the configured size is smaller, make sure it's
3954 * still big enough. Silently round up to minimum if not.
3956 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3957 if (env->me_mapsize < minsize)
3958 env->me_mapsize = minsize;
3961 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
3966 if (flags & MDB_FIXEDMAP)
3967 meta.mm_address = env->me_map;
3968 i = mdb_env_init_meta(env, &meta);
3969 if (i != MDB_SUCCESS) {
3974 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3975 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
3977 #if !(MDB_MAXKEYSIZE)
3978 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
3980 env->me_maxpg = env->me_mapsize / env->me_psize;
3984 int toggle = mdb_env_pick_meta(env);
3985 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3987 DPRINTF(("opened database version %u, pagesize %u",
3988 env->me_metas[0]->mm_version, env->me_psize));
3989 DPRINTF(("using meta page %d", toggle));
3990 DPRINTF(("depth: %u", db->md_depth));
3991 DPRINTF(("entries: %"Z"u", db->md_entries));
3992 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
3993 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
3994 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3995 DPRINTF(("root: %"Z"u", db->md_root));
4003 /** Release a reader thread's slot in the reader lock table.
4004 * This function is called automatically when a thread exits.
4005 * @param[in] ptr This points to the slot in the reader lock table.
4008 mdb_env_reader_dest(void *ptr)
4010 MDB_reader *reader = ptr;
4016 /** Junk for arranging thread-specific callbacks on Windows. This is
4017 * necessarily platform and compiler-specific. Windows supports up
4018 * to 1088 keys. Let's assume nobody opens more than 64 environments
4019 * in a single process, for now. They can override this if needed.
4021 #ifndef MAX_TLS_KEYS
4022 #define MAX_TLS_KEYS 64
4024 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4025 static int mdb_tls_nkeys;
4027 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4031 case DLL_PROCESS_ATTACH: break;
4032 case DLL_THREAD_ATTACH: break;
4033 case DLL_THREAD_DETACH:
4034 for (i=0; i<mdb_tls_nkeys; i++) {
4035 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4037 mdb_env_reader_dest(r);
4041 case DLL_PROCESS_DETACH: break;
4046 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4048 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4052 /* Force some symbol references.
4053 * _tls_used forces the linker to create the TLS directory if not already done
4054 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4056 #pragma comment(linker, "/INCLUDE:_tls_used")
4057 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4058 #pragma const_seg(".CRT$XLB")
4059 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4060 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4063 #pragma comment(linker, "/INCLUDE:__tls_used")
4064 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4065 #pragma data_seg(".CRT$XLB")
4066 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4068 #endif /* WIN 32/64 */
4069 #endif /* !__GNUC__ */
4072 /** Downgrade the exclusive lock on the region back to shared */
4074 mdb_env_share_locks(MDB_env *env, int *excl)
4076 int rc = 0, toggle = mdb_env_pick_meta(env);
4078 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
4083 /* First acquire a shared lock. The Unlock will
4084 * then release the existing exclusive lock.
4086 memset(&ov, 0, sizeof(ov));
4087 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4090 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4096 struct flock lock_info;
4097 /* The shared lock replaces the existing lock */
4098 memset((void *)&lock_info, 0, sizeof(lock_info));
4099 lock_info.l_type = F_RDLCK;
4100 lock_info.l_whence = SEEK_SET;
4101 lock_info.l_start = 0;
4102 lock_info.l_len = 1;
4103 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4104 (rc = ErrCode()) == EINTR) ;
4105 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4112 /** Try to get exclusive lock, otherwise shared.
4113 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4116 mdb_env_excl_lock(MDB_env *env, int *excl)
4120 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4124 memset(&ov, 0, sizeof(ov));
4125 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4132 struct flock lock_info;
4133 memset((void *)&lock_info, 0, sizeof(lock_info));
4134 lock_info.l_type = F_WRLCK;
4135 lock_info.l_whence = SEEK_SET;
4136 lock_info.l_start = 0;
4137 lock_info.l_len = 1;
4138 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4139 (rc = ErrCode()) == EINTR) ;
4143 # ifdef MDB_USE_POSIX_SEM
4144 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
4147 lock_info.l_type = F_RDLCK;
4148 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4149 (rc = ErrCode()) == EINTR) ;
4159 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4161 * @(#) $Revision: 5.1 $
4162 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4163 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4165 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4169 * Please do not copyright this code. This code is in the public domain.
4171 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4172 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4173 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4174 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4175 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4176 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4177 * PERFORMANCE OF THIS SOFTWARE.
4180 * chongo <Landon Curt Noll> /\oo/\
4181 * http://www.isthe.com/chongo/
4183 * Share and Enjoy! :-)
4186 typedef unsigned long long mdb_hash_t;
4187 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4189 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4190 * @param[in] val value to hash
4191 * @param[in] hval initial value for hash
4192 * @return 64 bit hash
4194 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4195 * hval arg on the first call.
4198 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4200 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4201 unsigned char *end = s + val->mv_size;
4203 * FNV-1a hash each octet of the string
4206 /* xor the bottom with the current octet */
4207 hval ^= (mdb_hash_t)*s++;
4209 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4210 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4211 (hval << 7) + (hval << 8) + (hval << 40);
4213 /* return our new hash value */
4217 /** Hash the string and output the encoded hash.
4218 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4219 * very short name limits. We don't care about the encoding being reversible,
4220 * we just want to preserve as many bits of the input as possible in a
4221 * small printable string.
4222 * @param[in] str string to hash
4223 * @param[out] encbuf an array of 11 chars to hold the hash
4225 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4228 mdb_pack85(unsigned long l, char *out)
4232 for (i=0; i<5; i++) {
4233 *out++ = mdb_a85[l % 85];
4239 mdb_hash_enc(MDB_val *val, char *encbuf)
4241 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4243 mdb_pack85(h, encbuf);
4244 mdb_pack85(h>>32, encbuf+5);
4249 /** Open and/or initialize the lock region for the environment.
4250 * @param[in] env The LMDB environment.
4251 * @param[in] lpath The pathname of the file used for the lock region.
4252 * @param[in] mode The Unix permissions for the file, if we create it.
4253 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4254 * @return 0 on success, non-zero on failure.
4257 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4260 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4262 # define MDB_ERRCODE_ROFS EROFS
4263 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4264 # define MDB_CLOEXEC O_CLOEXEC
4267 # define MDB_CLOEXEC 0
4274 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
4275 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4276 FILE_ATTRIBUTE_NORMAL, NULL);
4278 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4280 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4282 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4287 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4288 /* Lose record locks when exec*() */
4289 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4290 fcntl(env->me_lfd, F_SETFD, fdflags);
4293 if (!(env->me_flags & MDB_NOTLS)) {
4294 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4297 env->me_flags |= MDB_ENV_TXKEY;
4299 /* Windows TLS callbacks need help finding their TLS info. */
4300 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4304 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4308 /* Try to get exclusive lock. If we succeed, then
4309 * nobody is using the lock region and we should initialize it.
4311 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4314 size = GetFileSize(env->me_lfd, NULL);
4316 size = lseek(env->me_lfd, 0, SEEK_END);
4317 if (size == -1) goto fail_errno;
4319 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4320 if (size < rsize && *excl > 0) {
4322 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4323 || !SetEndOfFile(env->me_lfd))
4326 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4330 size = rsize - sizeof(MDB_txninfo);
4331 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4336 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4338 if (!mh) goto fail_errno;
4339 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4341 if (!env->me_txns) goto fail_errno;
4343 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4345 if (m == MAP_FAILED) goto fail_errno;
4351 BY_HANDLE_FILE_INFORMATION stbuf;
4360 if (!mdb_sec_inited) {
4361 InitializeSecurityDescriptor(&mdb_null_sd,
4362 SECURITY_DESCRIPTOR_REVISION);
4363 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4364 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4365 mdb_all_sa.bInheritHandle = FALSE;
4366 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4369 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4370 idbuf.volume = stbuf.dwVolumeSerialNumber;
4371 idbuf.nhigh = stbuf.nFileIndexHigh;
4372 idbuf.nlow = stbuf.nFileIndexLow;
4373 val.mv_data = &idbuf;
4374 val.mv_size = sizeof(idbuf);
4375 mdb_hash_enc(&val, encbuf);
4376 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4377 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4378 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4379 if (!env->me_rmutex) goto fail_errno;
4380 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4381 if (!env->me_wmutex) goto fail_errno;
4382 #elif defined(MDB_USE_POSIX_SEM)
4391 #if defined(__NetBSD__)
4392 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4394 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4395 idbuf.dev = stbuf.st_dev;
4396 idbuf.ino = stbuf.st_ino;
4397 val.mv_data = &idbuf;
4398 val.mv_size = sizeof(idbuf);
4399 mdb_hash_enc(&val, encbuf);
4400 #ifdef MDB_SHORT_SEMNAMES
4401 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4403 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4404 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4405 /* Clean up after a previous run, if needed: Try to
4406 * remove both semaphores before doing anything else.
4408 sem_unlink(env->me_txns->mti_rmname);
4409 sem_unlink(env->me_txns->mti_wmname);
4410 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4411 O_CREAT|O_EXCL, mode, 1);
4412 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4413 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4414 O_CREAT|O_EXCL, mode, 1);
4415 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4416 #else /* MDB_USE_POSIX_SEM */
4417 pthread_mutexattr_t mattr;
4419 if ((rc = pthread_mutexattr_init(&mattr))
4420 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4421 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
4422 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
4424 pthread_mutexattr_destroy(&mattr);
4425 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4427 env->me_txns->mti_magic = MDB_MAGIC;
4428 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4429 env->me_txns->mti_txnid = 0;
4430 env->me_txns->mti_numreaders = 0;
4433 if (env->me_txns->mti_magic != MDB_MAGIC) {
4434 DPUTS("lock region has invalid magic");
4438 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4439 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4440 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4441 rc = MDB_VERSION_MISMATCH;
4445 if (rc && rc != EACCES && rc != EAGAIN) {
4449 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4450 if (!env->me_rmutex) goto fail_errno;
4451 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4452 if (!env->me_wmutex) goto fail_errno;
4453 #elif defined(MDB_USE_POSIX_SEM)
4454 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4455 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4456 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4457 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4468 /** The name of the lock file in the DB environment */
4469 #define LOCKNAME "/lock.mdb"
4470 /** The name of the data file in the DB environment */
4471 #define DATANAME "/data.mdb"
4472 /** The suffix of the lock file when no subdir is used */
4473 #define LOCKSUFF "-lock"
4474 /** Only a subset of the @ref mdb_env flags can be changed
4475 * at runtime. Changing other flags requires closing the
4476 * environment and re-opening it with the new flags.
4478 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4479 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP| \
4480 MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4482 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4483 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4487 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4489 int oflags, rc, len, excl = -1;
4490 char *lpath, *dpath;
4492 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4496 if (flags & MDB_NOSUBDIR) {
4497 rc = len + sizeof(LOCKSUFF) + len + 1;
4499 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4504 if (flags & MDB_NOSUBDIR) {
4505 dpath = lpath + len + sizeof(LOCKSUFF);
4506 sprintf(lpath, "%s" LOCKSUFF, path);
4507 strcpy(dpath, path);
4509 dpath = lpath + len + sizeof(LOCKNAME);
4510 sprintf(lpath, "%s" LOCKNAME, path);
4511 sprintf(dpath, "%s" DATANAME, path);
4515 flags |= env->me_flags;
4516 if (flags & MDB_RDONLY) {
4517 /* silently ignore WRITEMAP when we're only getting read access */
4518 flags &= ~MDB_WRITEMAP;
4520 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4521 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4524 env->me_flags = flags |= MDB_ENV_ACTIVE;
4528 env->me_path = strdup(path);
4529 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4530 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4531 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4532 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4537 /* For RDONLY, get lockfile after we know datafile exists */
4538 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4539 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4545 if (F_ISSET(flags, MDB_RDONLY)) {
4546 oflags = GENERIC_READ;
4547 len = OPEN_EXISTING;
4549 oflags = GENERIC_READ|GENERIC_WRITE;
4552 mode = FILE_ATTRIBUTE_NORMAL;
4553 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4554 NULL, len, mode, NULL);
4556 if (F_ISSET(flags, MDB_RDONLY))
4559 oflags = O_RDWR | O_CREAT;
4561 env->me_fd = open(dpath, oflags, mode);
4563 if (env->me_fd == INVALID_HANDLE_VALUE) {
4568 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4569 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4574 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4575 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4576 env->me_mfd = env->me_fd;
4578 /* Synchronous fd for meta writes. Needed even with
4579 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4582 len = OPEN_EXISTING;
4583 env->me_mfd = CreateFile(dpath, oflags,
4584 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4585 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4588 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4590 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4595 DPRINTF(("opened dbenv %p", (void *) env));
4597 rc = mdb_env_share_locks(env, &excl);
4601 if (!((flags & MDB_RDONLY) ||
4602 (env->me_pbuf = calloc(1, env->me_psize))))
4604 if (!(flags & MDB_RDONLY)) {
4606 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
4607 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
4608 txn = calloc(1, size);
4610 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
4611 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
4612 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
4613 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
4615 txn->mt_dbxs = env->me_dbxs;
4625 mdb_env_close0(env, excl);
4631 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4633 mdb_env_close0(MDB_env *env, int excl)
4637 if (!(env->me_flags & MDB_ENV_ACTIVE))
4640 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4641 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4642 free(env->me_dbxs[i].md_name.mv_data);
4645 free(env->me_dbiseqs);
4646 free(env->me_dbflags);
4649 free(env->me_dirty_list);
4651 mdb_midl_free(env->me_free_pgs);
4653 if (env->me_flags & MDB_ENV_TXKEY) {
4654 pthread_key_delete(env->me_txkey);
4656 /* Delete our key from the global list */
4657 for (i=0; i<mdb_tls_nkeys; i++)
4658 if (mdb_tls_keys[i] == env->me_txkey) {
4659 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4667 munmap(env->me_map, env->me_mapsize);
4669 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4670 (void) close(env->me_mfd);
4671 if (env->me_fd != INVALID_HANDLE_VALUE)
4672 (void) close(env->me_fd);
4674 MDB_PID_T pid = env->me_pid;
4675 /* Clearing readers is done in this function because
4676 * me_txkey with its destructor must be disabled first.
4678 for (i = env->me_numreaders; --i >= 0; )
4679 if (env->me_txns->mti_readers[i].mr_pid == pid)
4680 env->me_txns->mti_readers[i].mr_pid = 0;
4682 if (env->me_rmutex) {
4683 CloseHandle(env->me_rmutex);
4684 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4686 /* Windows automatically destroys the mutexes when
4687 * the last handle closes.
4689 #elif defined(MDB_USE_POSIX_SEM)
4690 if (env->me_rmutex != SEM_FAILED) {
4691 sem_close(env->me_rmutex);
4692 if (env->me_wmutex != SEM_FAILED)
4693 sem_close(env->me_wmutex);
4694 /* If we have the filelock: If we are the
4695 * only remaining user, clean up semaphores.
4698 mdb_env_excl_lock(env, &excl);
4700 sem_unlink(env->me_txns->mti_rmname);
4701 sem_unlink(env->me_txns->mti_wmname);
4705 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4707 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4710 /* Unlock the lockfile. Windows would have unlocked it
4711 * after closing anyway, but not necessarily at once.
4713 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4716 (void) close(env->me_lfd);
4719 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4724 mdb_env_close(MDB_env *env)
4731 VGMEMP_DESTROY(env);
4732 while ((dp = env->me_dpages) != NULL) {
4733 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4734 env->me_dpages = dp->mp_next;
4738 mdb_env_close0(env, 0);
4742 /** Compare two items pointing at aligned size_t's */
4744 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4746 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4747 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4750 /** Compare two items pointing at aligned unsigned int's */
4752 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4754 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4755 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4758 /** Compare two items pointing at unsigned ints of unknown alignment.
4759 * Nodes and keys are guaranteed to be 2-byte aligned.
4762 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4764 #if BYTE_ORDER == LITTLE_ENDIAN
4765 unsigned short *u, *c;
4768 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4769 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4772 } while(!x && u > (unsigned short *)a->mv_data);
4775 unsigned short *u, *c, *end;
4778 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4779 u = (unsigned short *)a->mv_data;
4780 c = (unsigned short *)b->mv_data;
4783 } while(!x && u < end);
4788 /** Compare two items pointing at size_t's of unknown alignment. */
4789 #ifdef MISALIGNED_OK
4790 # define mdb_cmp_clong mdb_cmp_long
4792 # define mdb_cmp_clong mdb_cmp_cint
4795 /** Compare two items lexically */
4797 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4804 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4810 diff = memcmp(a->mv_data, b->mv_data, len);
4811 return diff ? diff : len_diff<0 ? -1 : len_diff;
4814 /** Compare two items in reverse byte order */
4816 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4818 const unsigned char *p1, *p2, *p1_lim;
4822 p1_lim = (const unsigned char *)a->mv_data;
4823 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4824 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4826 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4832 while (p1 > p1_lim) {
4833 diff = *--p1 - *--p2;
4837 return len_diff<0 ? -1 : len_diff;
4840 /** Search for key within a page, using binary search.
4841 * Returns the smallest entry larger or equal to the key.
4842 * If exactp is non-null, stores whether the found entry was an exact match
4843 * in *exactp (1 or 0).
4844 * Updates the cursor index with the index of the found entry.
4845 * If no entry larger or equal to the key is found, returns NULL.
4848 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4850 unsigned int i = 0, nkeys;
4853 MDB_page *mp = mc->mc_pg[mc->mc_top];
4854 MDB_node *node = NULL;
4859 nkeys = NUMKEYS(mp);
4861 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4862 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4865 low = IS_LEAF(mp) ? 0 : 1;
4867 cmp = mc->mc_dbx->md_cmp;
4869 /* Branch pages have no data, so if using integer keys,
4870 * alignment is guaranteed. Use faster mdb_cmp_int.
4872 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4873 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4880 nodekey.mv_size = mc->mc_db->md_pad;
4881 node = NODEPTR(mp, 0); /* fake */
4882 while (low <= high) {
4883 i = (low + high) >> 1;
4884 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4885 rc = cmp(key, &nodekey);
4886 DPRINTF(("found leaf index %u [%s], rc = %i",
4887 i, DKEY(&nodekey), rc));
4896 while (low <= high) {
4897 i = (low + high) >> 1;
4899 node = NODEPTR(mp, i);
4900 nodekey.mv_size = NODEKSZ(node);
4901 nodekey.mv_data = NODEKEY(node);
4903 rc = cmp(key, &nodekey);
4906 DPRINTF(("found leaf index %u [%s], rc = %i",
4907 i, DKEY(&nodekey), rc));
4909 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4910 i, DKEY(&nodekey), NODEPGNO(node), rc));
4921 if (rc > 0) { /* Found entry is less than the key. */
4922 i++; /* Skip to get the smallest entry larger than key. */
4924 node = NODEPTR(mp, i);
4927 *exactp = (rc == 0 && nkeys > 0);
4928 /* store the key index */
4929 mc->mc_ki[mc->mc_top] = i;
4931 /* There is no entry larger or equal to the key. */
4934 /* nodeptr is fake for LEAF2 */
4940 mdb_cursor_adjust(MDB_cursor *mc, func)
4944 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4945 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4952 /** Pop a page off the top of the cursor's stack. */
4954 mdb_cursor_pop(MDB_cursor *mc)
4958 MDB_page *top = mc->mc_pg[mc->mc_top];
4964 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4965 DDBI(mc), (void *) mc));
4969 /** Push a page onto the top of the cursor's stack. */
4971 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4973 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4974 DDBI(mc), (void *) mc));
4976 if (mc->mc_snum >= CURSOR_STACK) {
4977 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4978 return MDB_CURSOR_FULL;
4981 mc->mc_top = mc->mc_snum++;
4982 mc->mc_pg[mc->mc_top] = mp;
4983 mc->mc_ki[mc->mc_top] = 0;
4988 /** Find the address of the page corresponding to a given page number.
4989 * @param[in] txn the transaction for this access.
4990 * @param[in] pgno the page number for the page to retrieve.
4991 * @param[out] ret address of a pointer where the page's address will be stored.
4992 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4993 * @return 0 on success, non-zero on failure.
4996 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4998 MDB_env *env = txn->mt_env;
5002 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
5006 MDB_ID2L dl = tx2->mt_u.dirty_list;
5008 /* Spilled pages were dirtied in this txn and flushed
5009 * because the dirty list got full. Bring this page
5010 * back in from the map (but don't unspill it here,
5011 * leave that unless page_touch happens again).
5013 if (tx2->mt_spill_pgs) {
5014 MDB_ID pn = pgno << 1;
5015 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5016 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5017 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5022 unsigned x = mdb_mid2l_search(dl, pgno);
5023 if (x <= dl[0].mid && dl[x].mid == pgno) {
5029 } while ((tx2 = tx2->mt_parent) != NULL);
5032 if (pgno < txn->mt_next_pgno) {
5034 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5036 DPRINTF(("page %"Z"u not found", pgno));
5037 txn->mt_flags |= MDB_TXN_ERROR;
5038 return MDB_PAGE_NOTFOUND;
5048 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
5049 * The cursor is at the root page, set up the rest of it.
5052 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
5054 MDB_page *mp = mc->mc_pg[mc->mc_top];
5058 while (IS_BRANCH(mp)) {
5062 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
5063 mdb_cassert(mc, NUMKEYS(mp) > 1);
5064 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
5066 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
5068 if (flags & MDB_PS_LAST)
5069 i = NUMKEYS(mp) - 1;
5072 node = mdb_node_search(mc, key, &exact);
5074 i = NUMKEYS(mp) - 1;
5076 i = mc->mc_ki[mc->mc_top];
5078 mdb_cassert(mc, i > 0);
5082 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
5085 mdb_cassert(mc, i < NUMKEYS(mp));
5086 node = NODEPTR(mp, i);
5088 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5091 mc->mc_ki[mc->mc_top] = i;
5092 if ((rc = mdb_cursor_push(mc, mp)))
5095 if (flags & MDB_PS_MODIFY) {
5096 if ((rc = mdb_page_touch(mc)) != 0)
5098 mp = mc->mc_pg[mc->mc_top];
5103 DPRINTF(("internal error, index points to a %02X page!?",
5105 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5106 return MDB_CORRUPTED;
5109 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
5110 key ? DKEY(key) : "null"));
5111 mc->mc_flags |= C_INITIALIZED;
5112 mc->mc_flags &= ~C_EOF;
5117 /** Search for the lowest key under the current branch page.
5118 * This just bypasses a NUMKEYS check in the current page
5119 * before calling mdb_page_search_root(), because the callers
5120 * are all in situations where the current page is known to
5124 mdb_page_search_lowest(MDB_cursor *mc)
5126 MDB_page *mp = mc->mc_pg[mc->mc_top];
5127 MDB_node *node = NODEPTR(mp, 0);
5130 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5133 mc->mc_ki[mc->mc_top] = 0;
5134 if ((rc = mdb_cursor_push(mc, mp)))
5136 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5139 /** Search for the page a given key should be in.
5140 * Push it and its parent pages on the cursor stack.
5141 * @param[in,out] mc the cursor for this operation.
5142 * @param[in] key the key to search for, or NULL for first/last page.
5143 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5144 * are touched (updated with new page numbers).
5145 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5146 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5147 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5148 * @return 0 on success, non-zero on failure.
5151 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5156 /* Make sure the txn is still viable, then find the root from
5157 * the txn's db table and set it as the root of the cursor's stack.
5159 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
5160 DPUTS("transaction has failed, must abort");
5163 /* Make sure we're using an up-to-date root */
5164 if (*mc->mc_dbflag & DB_STALE) {
5166 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5168 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5169 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5176 MDB_node *leaf = mdb_node_search(&mc2,
5177 &mc->mc_dbx->md_name, &exact);
5179 return MDB_NOTFOUND;
5180 rc = mdb_node_read(mc->mc_txn, leaf, &data);
5183 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5185 /* The txn may not know this DBI, or another process may
5186 * have dropped and recreated the DB with other flags.
5188 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5189 return MDB_INCOMPATIBLE;
5190 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5192 *mc->mc_dbflag &= ~DB_STALE;
5194 root = mc->mc_db->md_root;
5196 if (root == P_INVALID) { /* Tree is empty. */
5197 DPUTS("tree is empty");
5198 return MDB_NOTFOUND;
5202 mdb_cassert(mc, root > 1);
5203 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5204 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
5210 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5211 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5213 if (flags & MDB_PS_MODIFY) {
5214 if ((rc = mdb_page_touch(mc)))
5218 if (flags & MDB_PS_ROOTONLY)
5221 return mdb_page_search_root(mc, key, flags);
5225 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5227 MDB_txn *txn = mc->mc_txn;
5228 pgno_t pg = mp->mp_pgno;
5229 unsigned x = 0, ovpages = mp->mp_pages;
5230 MDB_env *env = txn->mt_env;
5231 MDB_IDL sl = txn->mt_spill_pgs;
5232 MDB_ID pn = pg << 1;
5235 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5236 /* If the page is dirty or on the spill list we just acquired it,
5237 * so we should give it back to our current free list, if any.
5238 * Otherwise put it onto the list of pages we freed in this txn.
5240 * Won't create me_pghead: me_pglast must be inited along with it.
5241 * Unsupported in nested txns: They would need to hide the page
5242 * range in ancestor txns' dirty and spilled lists.
5244 if (env->me_pghead &&
5246 ((mp->mp_flags & P_DIRTY) ||
5247 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5251 MDB_ID2 *dl, ix, iy;
5252 rc = mdb_midl_need(&env->me_pghead, ovpages);
5255 if (!(mp->mp_flags & P_DIRTY)) {
5256 /* This page is no longer spilled */
5263 /* Remove from dirty list */
5264 dl = txn->mt_u.dirty_list;
5266 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5272 mdb_cassert(mc, x > 1);
5274 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5275 txn->mt_flags |= MDB_TXN_ERROR;
5276 return MDB_CORRUPTED;
5279 if (!(env->me_flags & MDB_WRITEMAP))
5280 mdb_dpage_free(env, mp);
5282 /* Insert in me_pghead */
5283 mop = env->me_pghead;
5284 j = mop[0] + ovpages;
5285 for (i = mop[0]; i && mop[i] < pg; i--)
5291 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5295 mc->mc_db->md_overflow_pages -= ovpages;
5299 /** Return the data associated with a given node.
5300 * @param[in] txn The transaction for this operation.
5301 * @param[in] leaf The node being read.
5302 * @param[out] data Updated to point to the node's data.
5303 * @return 0 on success, non-zero on failure.
5306 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5308 MDB_page *omp; /* overflow page */
5312 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5313 data->mv_size = NODEDSZ(leaf);
5314 data->mv_data = NODEDATA(leaf);
5318 /* Read overflow data.
5320 data->mv_size = NODEDSZ(leaf);
5321 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5322 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5323 DPRINTF(("read overflow page %"Z"u failed", pgno));
5326 data->mv_data = METADATA(omp);
5332 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5333 MDB_val *key, MDB_val *data)
5340 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5342 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
5345 if (txn->mt_flags & MDB_TXN_ERROR)
5348 mdb_cursor_init(&mc, txn, dbi, &mx);
5349 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5352 /** Find a sibling for a page.
5353 * Replaces the page at the top of the cursor's stack with the
5354 * specified sibling, if one exists.
5355 * @param[in] mc The cursor for this operation.
5356 * @param[in] move_right Non-zero if the right sibling is requested,
5357 * otherwise the left sibling.
5358 * @return 0 on success, non-zero on failure.
5361 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5367 if (mc->mc_snum < 2) {
5368 return MDB_NOTFOUND; /* root has no siblings */
5372 DPRINTF(("parent page is page %"Z"u, index %u",
5373 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5375 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5376 : (mc->mc_ki[mc->mc_top] == 0)) {
5377 DPRINTF(("no more keys left, moving to %s sibling",
5378 move_right ? "right" : "left"));
5379 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5380 /* undo cursor_pop before returning */
5387 mc->mc_ki[mc->mc_top]++;
5389 mc->mc_ki[mc->mc_top]--;
5390 DPRINTF(("just moving to %s index key %u",
5391 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5393 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5395 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5396 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5397 /* mc will be inconsistent if caller does mc_snum++ as above */
5398 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5402 mdb_cursor_push(mc, mp);
5404 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5409 /** Move the cursor to the next data item. */
5411 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5417 if (mc->mc_flags & C_EOF) {
5418 return MDB_NOTFOUND;
5421 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5423 mp = mc->mc_pg[mc->mc_top];
5425 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5426 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5427 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5428 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5429 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5430 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5431 if (rc == MDB_SUCCESS)
5432 MDB_GET_KEY(leaf, key);
5437 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5438 if (op == MDB_NEXT_DUP)
5439 return MDB_NOTFOUND;
5443 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5444 mdb_dbg_pgno(mp), (void *) mc));
5445 if (mc->mc_flags & C_DEL)
5448 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5449 DPUTS("=====> move to next sibling page");
5450 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5451 mc->mc_flags |= C_EOF;
5454 mp = mc->mc_pg[mc->mc_top];
5455 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5457 mc->mc_ki[mc->mc_top]++;
5460 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5461 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5464 key->mv_size = mc->mc_db->md_pad;
5465 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5469 mdb_cassert(mc, IS_LEAF(mp));
5470 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5472 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5473 mdb_xcursor_init1(mc, leaf);
5476 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5479 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5480 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5481 if (rc != MDB_SUCCESS)
5486 MDB_GET_KEY(leaf, key);
5490 /** Move the cursor to the previous data item. */
5492 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5498 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5500 mp = mc->mc_pg[mc->mc_top];
5502 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5503 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5504 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5505 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5506 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5507 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5508 if (rc == MDB_SUCCESS) {
5509 MDB_GET_KEY(leaf, key);
5510 mc->mc_flags &= ~C_EOF;
5516 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5517 if (op == MDB_PREV_DUP)
5518 return MDB_NOTFOUND;
5522 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5523 mdb_dbg_pgno(mp), (void *) mc));
5525 if (mc->mc_ki[mc->mc_top] == 0) {
5526 DPUTS("=====> move to prev sibling page");
5527 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5530 mp = mc->mc_pg[mc->mc_top];
5531 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5532 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5534 mc->mc_ki[mc->mc_top]--;
5536 mc->mc_flags &= ~C_EOF;
5538 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5539 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5542 key->mv_size = mc->mc_db->md_pad;
5543 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5547 mdb_cassert(mc, IS_LEAF(mp));
5548 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5550 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5551 mdb_xcursor_init1(mc, leaf);
5554 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5557 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5558 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5559 if (rc != MDB_SUCCESS)
5564 MDB_GET_KEY(leaf, key);
5568 /** Set the cursor on a specific data item. */
5570 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5571 MDB_cursor_op op, int *exactp)
5575 MDB_node *leaf = NULL;
5578 if (key->mv_size == 0)
5579 return MDB_BAD_VALSIZE;
5582 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5584 /* See if we're already on the right page */
5585 if (mc->mc_flags & C_INITIALIZED) {
5588 mp = mc->mc_pg[mc->mc_top];
5590 mc->mc_ki[mc->mc_top] = 0;
5591 return MDB_NOTFOUND;
5593 if (mp->mp_flags & P_LEAF2) {
5594 nodekey.mv_size = mc->mc_db->md_pad;
5595 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5597 leaf = NODEPTR(mp, 0);
5598 MDB_GET_KEY2(leaf, nodekey);
5600 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5602 /* Probably happens rarely, but first node on the page
5603 * was the one we wanted.
5605 mc->mc_ki[mc->mc_top] = 0;
5612 unsigned int nkeys = NUMKEYS(mp);
5614 if (mp->mp_flags & P_LEAF2) {
5615 nodekey.mv_data = LEAF2KEY(mp,
5616 nkeys-1, nodekey.mv_size);
5618 leaf = NODEPTR(mp, nkeys-1);
5619 MDB_GET_KEY2(leaf, nodekey);
5621 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5623 /* last node was the one we wanted */
5624 mc->mc_ki[mc->mc_top] = nkeys-1;
5630 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5631 /* This is definitely the right page, skip search_page */
5632 if (mp->mp_flags & P_LEAF2) {
5633 nodekey.mv_data = LEAF2KEY(mp,
5634 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5636 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5637 MDB_GET_KEY2(leaf, nodekey);
5639 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5641 /* current node was the one we wanted */
5651 /* If any parents have right-sibs, search.
5652 * Otherwise, there's nothing further.
5654 for (i=0; i<mc->mc_top; i++)
5656 NUMKEYS(mc->mc_pg[i])-1)
5658 if (i == mc->mc_top) {
5659 /* There are no other pages */
5660 mc->mc_ki[mc->mc_top] = nkeys;
5661 return MDB_NOTFOUND;
5665 /* There are no other pages */
5666 mc->mc_ki[mc->mc_top] = 0;
5667 if (op == MDB_SET_RANGE && !exactp) {
5671 return MDB_NOTFOUND;
5675 rc = mdb_page_search(mc, key, 0);
5676 if (rc != MDB_SUCCESS)
5679 mp = mc->mc_pg[mc->mc_top];
5680 mdb_cassert(mc, IS_LEAF(mp));
5683 leaf = mdb_node_search(mc, key, exactp);
5684 if (exactp != NULL && !*exactp) {
5685 /* MDB_SET specified and not an exact match. */
5686 return MDB_NOTFOUND;
5690 DPUTS("===> inexact leaf not found, goto sibling");
5691 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5692 return rc; /* no entries matched */
5693 mp = mc->mc_pg[mc->mc_top];
5694 mdb_cassert(mc, IS_LEAF(mp));
5695 leaf = NODEPTR(mp, 0);
5699 mc->mc_flags |= C_INITIALIZED;
5700 mc->mc_flags &= ~C_EOF;
5703 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5704 key->mv_size = mc->mc_db->md_pad;
5705 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5710 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5711 mdb_xcursor_init1(mc, leaf);
5714 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5715 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5716 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5719 if (op == MDB_GET_BOTH) {
5725 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5726 if (rc != MDB_SUCCESS)
5729 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5731 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5733 rc = mc->mc_dbx->md_dcmp(data, &d2);
5735 if (op == MDB_GET_BOTH || rc > 0)
5736 return MDB_NOTFOUND;
5743 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5744 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5749 /* The key already matches in all other cases */
5750 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5751 MDB_GET_KEY(leaf, key);
5752 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5757 /** Move the cursor to the first item in the database. */
5759 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5765 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5767 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5768 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5769 if (rc != MDB_SUCCESS)
5772 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5774 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5775 mc->mc_flags |= C_INITIALIZED;
5776 mc->mc_flags &= ~C_EOF;
5778 mc->mc_ki[mc->mc_top] = 0;
5780 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5781 key->mv_size = mc->mc_db->md_pad;
5782 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5787 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5788 mdb_xcursor_init1(mc, leaf);
5789 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5793 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5797 MDB_GET_KEY(leaf, key);
5801 /** Move the cursor to the last item in the database. */
5803 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5809 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5811 if (!(mc->mc_flags & C_EOF)) {
5813 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5814 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5815 if (rc != MDB_SUCCESS)
5818 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5821 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5822 mc->mc_flags |= C_INITIALIZED|C_EOF;
5823 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5825 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5826 key->mv_size = mc->mc_db->md_pad;
5827 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5832 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5833 mdb_xcursor_init1(mc, leaf);
5834 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5838 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5843 MDB_GET_KEY(leaf, key);
5848 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5853 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5858 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5862 case MDB_GET_CURRENT:
5863 if (!(mc->mc_flags & C_INITIALIZED)) {
5866 MDB_page *mp = mc->mc_pg[mc->mc_top];
5867 int nkeys = NUMKEYS(mp);
5868 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5869 mc->mc_ki[mc->mc_top] = nkeys;
5875 key->mv_size = mc->mc_db->md_pad;
5876 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5878 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5879 MDB_GET_KEY(leaf, key);
5881 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5882 if (mc->mc_flags & C_DEL)
5883 mdb_xcursor_init1(mc, leaf);
5884 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5886 rc = mdb_node_read(mc->mc_txn, leaf, data);
5893 case MDB_GET_BOTH_RANGE:
5898 if (mc->mc_xcursor == NULL) {
5899 rc = MDB_INCOMPATIBLE;
5909 rc = mdb_cursor_set(mc, key, data, op,
5910 op == MDB_SET_RANGE ? NULL : &exact);
5913 case MDB_GET_MULTIPLE:
5914 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5918 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5919 rc = MDB_INCOMPATIBLE;
5923 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5924 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5927 case MDB_NEXT_MULTIPLE:
5932 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5933 rc = MDB_INCOMPATIBLE;
5936 if (!(mc->mc_flags & C_INITIALIZED))
5937 rc = mdb_cursor_first(mc, key, data);
5939 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5940 if (rc == MDB_SUCCESS) {
5941 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5944 mx = &mc->mc_xcursor->mx_cursor;
5945 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5947 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5948 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5956 case MDB_NEXT_NODUP:
5957 if (!(mc->mc_flags & C_INITIALIZED))
5958 rc = mdb_cursor_first(mc, key, data);
5960 rc = mdb_cursor_next(mc, key, data, op);
5964 case MDB_PREV_NODUP:
5965 if (!(mc->mc_flags & C_INITIALIZED)) {
5966 rc = mdb_cursor_last(mc, key, data);
5969 mc->mc_flags |= C_INITIALIZED;
5970 mc->mc_ki[mc->mc_top]++;
5972 rc = mdb_cursor_prev(mc, key, data, op);
5975 rc = mdb_cursor_first(mc, key, data);
5978 mfunc = mdb_cursor_first;
5980 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5984 if (mc->mc_xcursor == NULL) {
5985 rc = MDB_INCOMPATIBLE;
5989 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5990 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5991 MDB_GET_KEY(leaf, key);
5992 rc = mdb_node_read(mc->mc_txn, leaf, data);
5996 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6000 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
6003 rc = mdb_cursor_last(mc, key, data);
6006 mfunc = mdb_cursor_last;
6009 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
6014 if (mc->mc_flags & C_DEL)
6015 mc->mc_flags ^= C_DEL;
6020 /** Touch all the pages in the cursor stack. Set mc_top.
6021 * Makes sure all the pages are writable, before attempting a write operation.
6022 * @param[in] mc The cursor to operate on.
6025 mdb_cursor_touch(MDB_cursor *mc)
6027 int rc = MDB_SUCCESS;
6029 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
6032 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6034 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
6035 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
6038 *mc->mc_dbflag |= DB_DIRTY;
6043 rc = mdb_page_touch(mc);
6044 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
6045 mc->mc_top = mc->mc_snum-1;
6050 /** Do not spill pages to disk if txn is getting full, may fail instead */
6051 #define MDB_NOSPILL 0x8000
6054 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6057 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
6059 MDB_node *leaf = NULL;
6062 MDB_val xdata, *rdata, dkey, olddata;
6064 int do_sub = 0, insert_key, insert_data;
6065 unsigned int mcount = 0, dcount = 0, nospill;
6068 unsigned int nflags;
6071 if (mc == NULL || key == NULL)
6074 env = mc->mc_txn->mt_env;
6076 /* Check this first so counter will always be zero on any
6079 if (flags & MDB_MULTIPLE) {
6080 dcount = data[1].mv_size;
6081 data[1].mv_size = 0;
6082 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
6083 return MDB_INCOMPATIBLE;
6086 nospill = flags & MDB_NOSPILL;
6087 flags &= ~MDB_NOSPILL;
6089 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6090 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6092 if (key->mv_size-1 >= ENV_MAXKEY(env))
6093 return MDB_BAD_VALSIZE;
6095 #if SIZE_MAX > MAXDATASIZE
6096 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
6097 return MDB_BAD_VALSIZE;
6099 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
6100 return MDB_BAD_VALSIZE;
6103 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
6104 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
6108 if (flags == MDB_CURRENT) {
6109 if (!(mc->mc_flags & C_INITIALIZED))
6112 } else if (mc->mc_db->md_root == P_INVALID) {
6113 /* new database, cursor has nothing to point to */
6116 mc->mc_flags &= ~C_INITIALIZED;
6121 if (flags & MDB_APPEND) {
6123 rc = mdb_cursor_last(mc, &k2, &d2);
6125 rc = mc->mc_dbx->md_cmp(key, &k2);
6128 mc->mc_ki[mc->mc_top]++;
6130 /* new key is <= last key */
6135 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6137 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6138 DPRINTF(("duplicate key [%s]", DKEY(key)));
6140 return MDB_KEYEXIST;
6142 if (rc && rc != MDB_NOTFOUND)
6146 if (mc->mc_flags & C_DEL)
6147 mc->mc_flags ^= C_DEL;
6149 /* Cursor is positioned, check for room in the dirty list */
6151 if (flags & MDB_MULTIPLE) {
6153 xdata.mv_size = data->mv_size * dcount;
6157 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6161 if (rc == MDB_NO_ROOT) {
6163 /* new database, write a root leaf page */
6164 DPUTS("allocating new root leaf page");
6165 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6168 mdb_cursor_push(mc, np);
6169 mc->mc_db->md_root = np->mp_pgno;
6170 mc->mc_db->md_depth++;
6171 *mc->mc_dbflag |= DB_DIRTY;
6172 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6174 np->mp_flags |= P_LEAF2;
6175 mc->mc_flags |= C_INITIALIZED;
6177 /* make sure all cursor pages are writable */
6178 rc2 = mdb_cursor_touch(mc);
6183 insert_key = insert_data = rc;
6185 /* The key does not exist */
6186 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6187 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6188 LEAFSIZE(key, data) > env->me_nodemax)
6190 /* Too big for a node, insert in sub-DB. Set up an empty
6191 * "old sub-page" for prep_subDB to expand to a full page.
6193 fp_flags = P_LEAF|P_DIRTY;
6195 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6196 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6197 olddata.mv_size = PAGEHDRSZ;
6201 /* there's only a key anyway, so this is a no-op */
6202 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6204 unsigned int ksize = mc->mc_db->md_pad;
6205 if (key->mv_size != ksize)
6206 return MDB_BAD_VALSIZE;
6207 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6208 memcpy(ptr, key->mv_data, ksize);
6210 /* if overwriting slot 0 of leaf, need to
6211 * update branch key if there is a parent page
6213 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6214 unsigned short top = mc->mc_top;
6216 /* slot 0 is always an empty key, find real slot */
6217 while (mc->mc_top && !mc->mc_ki[mc->mc_top])
6219 if (mc->mc_ki[mc->mc_top])
6220 rc2 = mdb_update_key(mc, key);
6231 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6232 olddata.mv_size = NODEDSZ(leaf);
6233 olddata.mv_data = NODEDATA(leaf);
6236 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6237 /* Prepare (sub-)page/sub-DB to accept the new item,
6238 * if needed. fp: old sub-page or a header faking
6239 * it. mp: new (sub-)page. offset: growth in page
6240 * size. xdata: node data with new page or DB.
6242 unsigned i, offset = 0;
6243 mp = fp = xdata.mv_data = env->me_pbuf;
6244 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6246 /* Was a single item before, must convert now */
6247 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6248 /* Just overwrite the current item */
6249 if (flags == MDB_CURRENT)
6252 #if UINT_MAX < SIZE_MAX
6253 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6254 mc->mc_dbx->md_dcmp = mdb_cmp_clong;
6256 /* does data match? */
6257 if (!mc->mc_dbx->md_dcmp(data, &olddata)) {
6258 if (flags & MDB_NODUPDATA)
6259 return MDB_KEYEXIST;
6264 /* Back up original data item */
6265 dkey.mv_size = olddata.mv_size;
6266 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6268 /* Make sub-page header for the dup items, with dummy body */
6269 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6270 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6271 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6272 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6273 fp->mp_flags |= P_LEAF2;
6274 fp->mp_pad = data->mv_size;
6275 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6277 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6278 (dkey.mv_size & 1) + (data->mv_size & 1);
6280 fp->mp_upper = xdata.mv_size - PAGEBASE;
6281 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6282 } else if (leaf->mn_flags & F_SUBDATA) {
6283 /* Data is on sub-DB, just store it */
6284 flags |= F_DUPDATA|F_SUBDATA;
6287 /* Data is on sub-page */
6288 fp = olddata.mv_data;
6291 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6292 offset = EVEN(NODESIZE + sizeof(indx_t) +
6296 offset = fp->mp_pad;
6297 if (SIZELEFT(fp) < offset) {
6298 offset *= 4; /* space for 4 more */
6301 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6303 fp->mp_flags |= P_DIRTY;
6304 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6305 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6309 xdata.mv_size = olddata.mv_size + offset;
6312 fp_flags = fp->mp_flags;
6313 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6314 /* Too big for a sub-page, convert to sub-DB */
6315 fp_flags &= ~P_SUBP;
6317 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6318 fp_flags |= P_LEAF2;
6319 dummy.md_pad = fp->mp_pad;
6320 dummy.md_flags = MDB_DUPFIXED;
6321 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6322 dummy.md_flags |= MDB_INTEGERKEY;
6328 dummy.md_branch_pages = 0;
6329 dummy.md_leaf_pages = 1;
6330 dummy.md_overflow_pages = 0;
6331 dummy.md_entries = NUMKEYS(fp);
6332 xdata.mv_size = sizeof(MDB_db);
6333 xdata.mv_data = &dummy;
6334 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6336 offset = env->me_psize - olddata.mv_size;
6337 flags |= F_DUPDATA|F_SUBDATA;
6338 dummy.md_root = mp->mp_pgno;
6341 mp->mp_flags = fp_flags | P_DIRTY;
6342 mp->mp_pad = fp->mp_pad;
6343 mp->mp_lower = fp->mp_lower;
6344 mp->mp_upper = fp->mp_upper + offset;
6345 if (fp_flags & P_LEAF2) {
6346 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6348 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6349 olddata.mv_size - fp->mp_upper - PAGEBASE);
6350 for (i=0; i<NUMKEYS(fp); i++)
6351 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6359 mdb_node_del(mc, 0);
6363 /* overflow page overwrites need special handling */
6364 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6367 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6369 memcpy(&pg, olddata.mv_data, sizeof(pg));
6370 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6372 ovpages = omp->mp_pages;
6374 /* Is the ov page large enough? */
6375 if (ovpages >= dpages) {
6376 if (!(omp->mp_flags & P_DIRTY) &&
6377 (level || (env->me_flags & MDB_WRITEMAP)))
6379 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6382 level = 0; /* dirty in this txn or clean */
6385 if (omp->mp_flags & P_DIRTY) {
6386 /* yes, overwrite it. Note in this case we don't
6387 * bother to try shrinking the page if the new data
6388 * is smaller than the overflow threshold.
6391 /* It is writable only in a parent txn */
6392 size_t sz = (size_t) env->me_psize * ovpages, off;
6393 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6399 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6400 mdb_cassert(mc, rc2 == 0);
6401 if (!(flags & MDB_RESERVE)) {
6402 /* Copy end of page, adjusting alignment so
6403 * compiler may copy words instead of bytes.
6405 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6406 memcpy((size_t *)((char *)np + off),
6407 (size_t *)((char *)omp + off), sz - off);
6410 memcpy(np, omp, sz); /* Copy beginning of page */
6413 SETDSZ(leaf, data->mv_size);
6414 if (F_ISSET(flags, MDB_RESERVE))
6415 data->mv_data = METADATA(omp);
6417 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6421 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6423 } else if (data->mv_size == olddata.mv_size) {
6424 /* same size, just replace it. Note that we could
6425 * also reuse this node if the new data is smaller,
6426 * but instead we opt to shrink the node in that case.
6428 if (F_ISSET(flags, MDB_RESERVE))
6429 data->mv_data = olddata.mv_data;
6430 else if (!(mc->mc_flags & C_SUB))
6431 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6433 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6438 mdb_node_del(mc, 0);
6444 nflags = flags & NODE_ADD_FLAGS;
6445 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6446 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6447 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6448 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6450 nflags |= MDB_SPLIT_REPLACE;
6451 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6453 /* There is room already in this leaf page. */
6454 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6455 if (rc == 0 && insert_key) {
6456 /* Adjust other cursors pointing to mp */
6457 MDB_cursor *m2, *m3;
6458 MDB_dbi dbi = mc->mc_dbi;
6459 unsigned i = mc->mc_top;
6460 MDB_page *mp = mc->mc_pg[i];
6462 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6463 if (mc->mc_flags & C_SUB)
6464 m3 = &m2->mc_xcursor->mx_cursor;
6467 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6468 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6475 if (rc == MDB_SUCCESS) {
6476 /* Now store the actual data in the child DB. Note that we're
6477 * storing the user data in the keys field, so there are strict
6478 * size limits on dupdata. The actual data fields of the child
6479 * DB are all zero size.
6487 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6488 if (flags & MDB_CURRENT) {
6489 xflags = MDB_CURRENT|MDB_NOSPILL;
6491 mdb_xcursor_init1(mc, leaf);
6492 xflags = (flags & MDB_NODUPDATA) ?
6493 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6495 /* converted, write the original data first */
6497 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6501 /* Adjust other cursors pointing to mp */
6503 unsigned i = mc->mc_top;
6504 MDB_page *mp = mc->mc_pg[i];
6506 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6507 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6508 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6509 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6510 mdb_xcursor_init1(m2, leaf);
6514 /* we've done our job */
6517 ecount = mc->mc_xcursor->mx_db.md_entries;
6518 if (flags & MDB_APPENDDUP)
6519 xflags |= MDB_APPEND;
6520 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6521 if (flags & F_SUBDATA) {
6522 void *db = NODEDATA(leaf);
6523 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6525 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6527 /* Increment count unless we just replaced an existing item. */
6529 mc->mc_db->md_entries++;
6531 /* Invalidate txn if we created an empty sub-DB */
6534 /* If we succeeded and the key didn't exist before,
6535 * make sure the cursor is marked valid.
6537 mc->mc_flags |= C_INITIALIZED;
6539 if (flags & MDB_MULTIPLE) {
6542 /* let caller know how many succeeded, if any */
6543 data[1].mv_size = mcount;
6544 if (mcount < dcount) {
6545 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6546 insert_key = insert_data = 0;
6553 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6556 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6561 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6567 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6568 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6570 if (!(mc->mc_flags & C_INITIALIZED))
6573 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6574 return MDB_NOTFOUND;
6576 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6579 rc = mdb_cursor_touch(mc);
6583 mp = mc->mc_pg[mc->mc_top];
6586 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6588 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6589 if (flags & MDB_NODUPDATA) {
6590 /* mdb_cursor_del0() will subtract the final entry */
6591 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6593 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6594 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6596 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6599 /* If sub-DB still has entries, we're done */
6600 if (mc->mc_xcursor->mx_db.md_entries) {
6601 if (leaf->mn_flags & F_SUBDATA) {
6602 /* update subDB info */
6603 void *db = NODEDATA(leaf);
6604 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6607 /* shrink fake page */
6608 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6609 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6610 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6611 /* fix other sub-DB cursors pointed at this fake page */
6612 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6613 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6614 if (m2->mc_pg[mc->mc_top] == mp &&
6615 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6616 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6619 mc->mc_db->md_entries--;
6620 mc->mc_flags |= C_DEL;
6623 /* otherwise fall thru and delete the sub-DB */
6626 if (leaf->mn_flags & F_SUBDATA) {
6627 /* add all the child DB's pages to the free list */
6628 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6634 /* add overflow pages to free list */
6635 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6639 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6640 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6641 (rc = mdb_ovpage_free(mc, omp)))
6646 return mdb_cursor_del0(mc);
6649 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6653 /** Allocate and initialize new pages for a database.
6654 * @param[in] mc a cursor on the database being added to.
6655 * @param[in] flags flags defining what type of page is being allocated.
6656 * @param[in] num the number of pages to allocate. This is usually 1,
6657 * unless allocating overflow pages for a large record.
6658 * @param[out] mp Address of a page, or NULL on failure.
6659 * @return 0 on success, non-zero on failure.
6662 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6667 if ((rc = mdb_page_alloc(mc, num, &np)))
6669 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6670 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6671 np->mp_flags = flags | P_DIRTY;
6672 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
6673 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
6676 mc->mc_db->md_branch_pages++;
6677 else if (IS_LEAF(np))
6678 mc->mc_db->md_leaf_pages++;
6679 else if (IS_OVERFLOW(np)) {
6680 mc->mc_db->md_overflow_pages += num;
6688 /** Calculate the size of a leaf node.
6689 * The size depends on the environment's page size; if a data item
6690 * is too large it will be put onto an overflow page and the node
6691 * size will only include the key and not the data. Sizes are always
6692 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6693 * of the #MDB_node headers.
6694 * @param[in] env The environment handle.
6695 * @param[in] key The key for the node.
6696 * @param[in] data The data for the node.
6697 * @return The number of bytes needed to store the node.
6700 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6704 sz = LEAFSIZE(key, data);
6705 if (sz > env->me_nodemax) {
6706 /* put on overflow page */
6707 sz -= data->mv_size - sizeof(pgno_t);
6710 return EVEN(sz + sizeof(indx_t));
6713 /** Calculate the size of a branch node.
6714 * The size should depend on the environment's page size but since
6715 * we currently don't support spilling large keys onto overflow
6716 * pages, it's simply the size of the #MDB_node header plus the
6717 * size of the key. Sizes are always rounded up to an even number
6718 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6719 * @param[in] env The environment handle.
6720 * @param[in] key The key for the node.
6721 * @return The number of bytes needed to store the node.
6724 mdb_branch_size(MDB_env *env, MDB_val *key)
6729 if (sz > env->me_nodemax) {
6730 /* put on overflow page */
6731 /* not implemented */
6732 /* sz -= key->size - sizeof(pgno_t); */
6735 return sz + sizeof(indx_t);
6738 /** Add a node to the page pointed to by the cursor.
6739 * @param[in] mc The cursor for this operation.
6740 * @param[in] indx The index on the page where the new node should be added.
6741 * @param[in] key The key for the new node.
6742 * @param[in] data The data for the new node, if any.
6743 * @param[in] pgno The page number, if adding a branch node.
6744 * @param[in] flags Flags for the node.
6745 * @return 0 on success, non-zero on failure. Possible errors are:
6747 * <li>ENOMEM - failed to allocate overflow pages for the node.
6748 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6749 * should never happen since all callers already calculate the
6750 * page's free space before calling this function.
6754 mdb_node_add(MDB_cursor *mc, indx_t indx,
6755 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6758 size_t node_size = NODESIZE;
6762 MDB_page *mp = mc->mc_pg[mc->mc_top];
6763 MDB_page *ofp = NULL; /* overflow page */
6766 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
6768 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6769 IS_LEAF(mp) ? "leaf" : "branch",
6770 IS_SUBP(mp) ? "sub-" : "",
6771 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
6772 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6775 /* Move higher keys up one slot. */
6776 int ksize = mc->mc_db->md_pad, dif;
6777 char *ptr = LEAF2KEY(mp, indx, ksize);
6778 dif = NUMKEYS(mp) - indx;
6780 memmove(ptr+ksize, ptr, dif*ksize);
6781 /* insert new key */
6782 memcpy(ptr, key->mv_data, ksize);
6784 /* Just using these for counting */
6785 mp->mp_lower += sizeof(indx_t);
6786 mp->mp_upper -= ksize - sizeof(indx_t);
6790 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6792 node_size += key->mv_size;
6794 mdb_cassert(mc, data);
6795 if (F_ISSET(flags, F_BIGDATA)) {
6796 /* Data already on overflow page. */
6797 node_size += sizeof(pgno_t);
6798 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
6799 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6801 /* Put data on overflow page. */
6802 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6803 data->mv_size, node_size+data->mv_size));
6804 node_size = EVEN(node_size + sizeof(pgno_t));
6805 if ((ssize_t)node_size > room)
6807 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6809 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6813 node_size += data->mv_size;
6816 node_size = EVEN(node_size);
6817 if ((ssize_t)node_size > room)
6821 /* Move higher pointers up one slot. */
6822 for (i = NUMKEYS(mp); i > indx; i--)
6823 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6825 /* Adjust free space offsets. */
6826 ofs = mp->mp_upper - node_size;
6827 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
6828 mp->mp_ptrs[indx] = ofs;
6830 mp->mp_lower += sizeof(indx_t);
6832 /* Write the node data. */
6833 node = NODEPTR(mp, indx);
6834 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6835 node->mn_flags = flags;
6837 SETDSZ(node,data->mv_size);
6842 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6845 mdb_cassert(mc, key);
6847 if (F_ISSET(flags, F_BIGDATA))
6848 memcpy(node->mn_data + key->mv_size, data->mv_data,
6850 else if (F_ISSET(flags, MDB_RESERVE))
6851 data->mv_data = node->mn_data + key->mv_size;
6853 memcpy(node->mn_data + key->mv_size, data->mv_data,
6856 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6858 if (F_ISSET(flags, MDB_RESERVE))
6859 data->mv_data = METADATA(ofp);
6861 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6868 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6869 mdb_dbg_pgno(mp), NUMKEYS(mp)));
6870 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6871 DPRINTF(("node size = %"Z"u", node_size));
6872 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6873 return MDB_PAGE_FULL;
6876 /** Delete the specified node from a page.
6877 * @param[in] mc Cursor pointing to the node to delete.
6878 * @param[in] ksize The size of a node. Only used if the page is
6879 * part of a #MDB_DUPFIXED database.
6882 mdb_node_del(MDB_cursor *mc, int ksize)
6884 MDB_page *mp = mc->mc_pg[mc->mc_top];
6885 indx_t indx = mc->mc_ki[mc->mc_top];
6887 indx_t i, j, numkeys, ptr;
6891 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6892 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
6893 numkeys = NUMKEYS(mp);
6894 mdb_cassert(mc, indx < numkeys);
6897 int x = numkeys - 1 - indx;
6898 base = LEAF2KEY(mp, indx, ksize);
6900 memmove(base, base + ksize, x * ksize);
6901 mp->mp_lower -= sizeof(indx_t);
6902 mp->mp_upper += ksize - sizeof(indx_t);
6906 node = NODEPTR(mp, indx);
6907 sz = NODESIZE + node->mn_ksize;
6909 if (F_ISSET(node->mn_flags, F_BIGDATA))
6910 sz += sizeof(pgno_t);
6912 sz += NODEDSZ(node);
6916 ptr = mp->mp_ptrs[indx];
6917 for (i = j = 0; i < numkeys; i++) {
6919 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6920 if (mp->mp_ptrs[i] < ptr)
6921 mp->mp_ptrs[j] += sz;
6926 base = (char *)mp + mp->mp_upper + PAGEBASE;
6927 memmove(base + sz, base, ptr - mp->mp_upper);
6929 mp->mp_lower -= sizeof(indx_t);
6933 /** Compact the main page after deleting a node on a subpage.
6934 * @param[in] mp The main page to operate on.
6935 * @param[in] indx The index of the subpage on the main page.
6938 mdb_node_shrink(MDB_page *mp, indx_t indx)
6944 indx_t i, numkeys, ptr;
6946 node = NODEPTR(mp, indx);
6947 sp = (MDB_page *)NODEDATA(node);
6948 delta = SIZELEFT(sp);
6949 xp = (MDB_page *)((char *)sp + delta);
6951 /* shift subpage upward */
6953 nsize = NUMKEYS(sp) * sp->mp_pad;
6955 return; /* do not make the node uneven-sized */
6956 memmove(METADATA(xp), METADATA(sp), nsize);
6959 numkeys = NUMKEYS(sp);
6960 for (i=numkeys-1; i>=0; i--)
6961 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6963 xp->mp_upper = sp->mp_lower;
6964 xp->mp_lower = sp->mp_lower;
6965 xp->mp_flags = sp->mp_flags;
6966 xp->mp_pad = sp->mp_pad;
6967 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6969 nsize = NODEDSZ(node) - delta;
6970 SETDSZ(node, nsize);
6972 /* shift lower nodes upward */
6973 ptr = mp->mp_ptrs[indx];
6974 numkeys = NUMKEYS(mp);
6975 for (i = 0; i < numkeys; i++) {
6976 if (mp->mp_ptrs[i] <= ptr)
6977 mp->mp_ptrs[i] += delta;
6980 base = (char *)mp + mp->mp_upper + PAGEBASE;
6981 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6982 mp->mp_upper += delta;
6985 /** Initial setup of a sorted-dups cursor.
6986 * Sorted duplicates are implemented as a sub-database for the given key.
6987 * The duplicate data items are actually keys of the sub-database.
6988 * Operations on the duplicate data items are performed using a sub-cursor
6989 * initialized when the sub-database is first accessed. This function does
6990 * the preliminary setup of the sub-cursor, filling in the fields that
6991 * depend only on the parent DB.
6992 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6995 mdb_xcursor_init0(MDB_cursor *mc)
6997 MDB_xcursor *mx = mc->mc_xcursor;
6999 mx->mx_cursor.mc_xcursor = NULL;
7000 mx->mx_cursor.mc_txn = mc->mc_txn;
7001 mx->mx_cursor.mc_db = &mx->mx_db;
7002 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
7003 mx->mx_cursor.mc_dbi = mc->mc_dbi;
7004 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
7005 mx->mx_cursor.mc_snum = 0;
7006 mx->mx_cursor.mc_top = 0;
7007 mx->mx_cursor.mc_flags = C_SUB;
7008 mx->mx_dbx.md_name.mv_size = 0;
7009 mx->mx_dbx.md_name.mv_data = NULL;
7010 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
7011 mx->mx_dbx.md_dcmp = NULL;
7012 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
7015 /** Final setup of a sorted-dups cursor.
7016 * Sets up the fields that depend on the data from the main cursor.
7017 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7018 * @param[in] node The data containing the #MDB_db record for the
7019 * sorted-dup database.
7022 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
7024 MDB_xcursor *mx = mc->mc_xcursor;
7026 if (node->mn_flags & F_SUBDATA) {
7027 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
7028 mx->mx_cursor.mc_pg[0] = 0;
7029 mx->mx_cursor.mc_snum = 0;
7030 mx->mx_cursor.mc_top = 0;
7031 mx->mx_cursor.mc_flags = C_SUB;
7033 MDB_page *fp = NODEDATA(node);
7034 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
7035 mx->mx_db.md_flags = 0;
7036 mx->mx_db.md_depth = 1;
7037 mx->mx_db.md_branch_pages = 0;
7038 mx->mx_db.md_leaf_pages = 1;
7039 mx->mx_db.md_overflow_pages = 0;
7040 mx->mx_db.md_entries = NUMKEYS(fp);
7041 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
7042 mx->mx_cursor.mc_snum = 1;
7043 mx->mx_cursor.mc_top = 0;
7044 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
7045 mx->mx_cursor.mc_pg[0] = fp;
7046 mx->mx_cursor.mc_ki[0] = 0;
7047 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7048 mx->mx_db.md_flags = MDB_DUPFIXED;
7049 mx->mx_db.md_pad = fp->mp_pad;
7050 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7051 mx->mx_db.md_flags |= MDB_INTEGERKEY;
7054 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7055 mx->mx_db.md_root));
7056 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
7057 #if UINT_MAX < SIZE_MAX
7058 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
7059 mx->mx_dbx.md_cmp = mdb_cmp_clong;
7063 /** Initialize a cursor for a given transaction and database. */
7065 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
7068 mc->mc_backup = NULL;
7071 mc->mc_db = &txn->mt_dbs[dbi];
7072 mc->mc_dbx = &txn->mt_dbxs[dbi];
7073 mc->mc_dbflag = &txn->mt_dbflags[dbi];
7078 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
7079 mdb_tassert(txn, mx != NULL);
7080 mc->mc_xcursor = mx;
7081 mdb_xcursor_init0(mc);
7083 mc->mc_xcursor = NULL;
7085 if (*mc->mc_dbflag & DB_STALE) {
7086 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
7091 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
7094 size_t size = sizeof(MDB_cursor);
7096 if (!ret || !TXN_DBI_EXIST(txn, dbi))
7099 if (txn->mt_flags & MDB_TXN_ERROR)
7102 /* Allow read access to the freelist */
7103 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7106 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
7107 size += sizeof(MDB_xcursor);
7109 if ((mc = malloc(size)) != NULL) {
7110 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
7111 if (txn->mt_cursors) {
7112 mc->mc_next = txn->mt_cursors[dbi];
7113 txn->mt_cursors[dbi] = mc;
7114 mc->mc_flags |= C_UNTRACK;
7126 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
7128 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi))
7131 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
7134 if (txn->mt_flags & MDB_TXN_ERROR)
7137 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
7141 /* Return the count of duplicate data items for the current key */
7143 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7147 if (mc == NULL || countp == NULL)
7150 if (mc->mc_xcursor == NULL)
7151 return MDB_INCOMPATIBLE;
7153 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
7156 if (!(mc->mc_flags & C_INITIALIZED))
7159 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
7160 return MDB_NOTFOUND;
7162 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7163 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7166 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7169 *countp = mc->mc_xcursor->mx_db.md_entries;
7175 mdb_cursor_close(MDB_cursor *mc)
7177 if (mc && !mc->mc_backup) {
7178 /* remove from txn, if tracked */
7179 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7180 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7181 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7183 *prev = mc->mc_next;
7190 mdb_cursor_txn(MDB_cursor *mc)
7192 if (!mc) return NULL;
7197 mdb_cursor_dbi(MDB_cursor *mc)
7202 /** Replace the key for a branch node with a new key.
7203 * @param[in] mc Cursor pointing to the node to operate on.
7204 * @param[in] key The new key to use.
7205 * @return 0 on success, non-zero on failure.
7208 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7214 int delta, ksize, oksize;
7215 indx_t ptr, i, numkeys, indx;
7218 indx = mc->mc_ki[mc->mc_top];
7219 mp = mc->mc_pg[mc->mc_top];
7220 node = NODEPTR(mp, indx);
7221 ptr = mp->mp_ptrs[indx];
7225 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7226 k2.mv_data = NODEKEY(node);
7227 k2.mv_size = node->mn_ksize;
7228 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7230 mdb_dkey(&k2, kbuf2),
7236 /* Sizes must be 2-byte aligned. */
7237 ksize = EVEN(key->mv_size);
7238 oksize = EVEN(node->mn_ksize);
7239 delta = ksize - oksize;
7241 /* Shift node contents if EVEN(key length) changed. */
7243 if (delta > 0 && SIZELEFT(mp) < delta) {
7245 /* not enough space left, do a delete and split */
7246 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7247 pgno = NODEPGNO(node);
7248 mdb_node_del(mc, 0);
7249 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7252 numkeys = NUMKEYS(mp);
7253 for (i = 0; i < numkeys; i++) {
7254 if (mp->mp_ptrs[i] <= ptr)
7255 mp->mp_ptrs[i] -= delta;
7258 base = (char *)mp + mp->mp_upper + PAGEBASE;
7259 len = ptr - mp->mp_upper + NODESIZE;
7260 memmove(base - delta, base, len);
7261 mp->mp_upper -= delta;
7263 node = NODEPTR(mp, indx);
7266 /* But even if no shift was needed, update ksize */
7267 if (node->mn_ksize != key->mv_size)
7268 node->mn_ksize = key->mv_size;
7271 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7277 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7279 /** Move a node from csrc to cdst.
7282 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
7289 unsigned short flags;
7293 /* Mark src and dst as dirty. */
7294 if ((rc = mdb_page_touch(csrc)) ||
7295 (rc = mdb_page_touch(cdst)))
7298 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7299 key.mv_size = csrc->mc_db->md_pad;
7300 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7302 data.mv_data = NULL;
7306 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7307 mdb_cassert(csrc, !((size_t)srcnode & 1));
7308 srcpg = NODEPGNO(srcnode);
7309 flags = srcnode->mn_flags;
7310 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7311 unsigned int snum = csrc->mc_snum;
7313 /* must find the lowest key below src */
7314 rc = mdb_page_search_lowest(csrc);
7317 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7318 key.mv_size = csrc->mc_db->md_pad;
7319 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7321 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7322 key.mv_size = NODEKSZ(s2);
7323 key.mv_data = NODEKEY(s2);
7325 csrc->mc_snum = snum--;
7326 csrc->mc_top = snum;
7328 key.mv_size = NODEKSZ(srcnode);
7329 key.mv_data = NODEKEY(srcnode);
7331 data.mv_size = NODEDSZ(srcnode);
7332 data.mv_data = NODEDATA(srcnode);
7334 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7335 unsigned int snum = cdst->mc_snum;
7338 /* must find the lowest key below dst */
7339 mdb_cursor_copy(cdst, &mn);
7340 rc = mdb_page_search_lowest(&mn);
7343 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7344 bkey.mv_size = mn.mc_db->md_pad;
7345 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7347 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7348 bkey.mv_size = NODEKSZ(s2);
7349 bkey.mv_data = NODEKEY(s2);
7351 mn.mc_snum = snum--;
7354 rc = mdb_update_key(&mn, &bkey);
7359 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7360 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7361 csrc->mc_ki[csrc->mc_top],
7363 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7364 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7366 /* Add the node to the destination page.
7368 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7369 if (rc != MDB_SUCCESS)
7372 /* Delete the node from the source page.
7374 mdb_node_del(csrc, key.mv_size);
7377 /* Adjust other cursors pointing to mp */
7378 MDB_cursor *m2, *m3;
7379 MDB_dbi dbi = csrc->mc_dbi;
7380 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
7382 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7383 if (csrc->mc_flags & C_SUB)
7384 m3 = &m2->mc_xcursor->mx_cursor;
7387 if (m3 == csrc) continue;
7388 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
7389 csrc->mc_ki[csrc->mc_top]) {
7390 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7391 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7396 /* Update the parent separators.
7398 if (csrc->mc_ki[csrc->mc_top] == 0) {
7399 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7400 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7401 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7403 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7404 key.mv_size = NODEKSZ(srcnode);
7405 key.mv_data = NODEKEY(srcnode);
7407 DPRINTF(("update separator for source page %"Z"u to [%s]",
7408 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7409 mdb_cursor_copy(csrc, &mn);
7412 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7415 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7417 indx_t ix = csrc->mc_ki[csrc->mc_top];
7418 nullkey.mv_size = 0;
7419 csrc->mc_ki[csrc->mc_top] = 0;
7420 rc = mdb_update_key(csrc, &nullkey);
7421 csrc->mc_ki[csrc->mc_top] = ix;
7422 mdb_cassert(csrc, rc == MDB_SUCCESS);
7426 if (cdst->mc_ki[cdst->mc_top] == 0) {
7427 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7428 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7429 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7431 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7432 key.mv_size = NODEKSZ(srcnode);
7433 key.mv_data = NODEKEY(srcnode);
7435 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7436 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7437 mdb_cursor_copy(cdst, &mn);
7440 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7443 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7445 indx_t ix = cdst->mc_ki[cdst->mc_top];
7446 nullkey.mv_size = 0;
7447 cdst->mc_ki[cdst->mc_top] = 0;
7448 rc = mdb_update_key(cdst, &nullkey);
7449 cdst->mc_ki[cdst->mc_top] = ix;
7450 mdb_cassert(csrc, rc == MDB_SUCCESS);
7457 /** Merge one page into another.
7458 * The nodes from the page pointed to by \b csrc will
7459 * be copied to the page pointed to by \b cdst and then
7460 * the \b csrc page will be freed.
7461 * @param[in] csrc Cursor pointing to the source page.
7462 * @param[in] cdst Cursor pointing to the destination page.
7463 * @return 0 on success, non-zero on failure.
7466 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7468 MDB_page *psrc, *pdst;
7475 psrc = csrc->mc_pg[csrc->mc_top];
7476 pdst = cdst->mc_pg[cdst->mc_top];
7478 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7480 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7481 mdb_cassert(csrc, cdst->mc_snum > 1);
7483 /* Mark dst as dirty. */
7484 if ((rc = mdb_page_touch(cdst)))
7487 /* Move all nodes from src to dst.
7489 j = nkeys = NUMKEYS(pdst);
7490 if (IS_LEAF2(psrc)) {
7491 key.mv_size = csrc->mc_db->md_pad;
7492 key.mv_data = METADATA(psrc);
7493 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7494 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7495 if (rc != MDB_SUCCESS)
7497 key.mv_data = (char *)key.mv_data + key.mv_size;
7500 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7501 srcnode = NODEPTR(psrc, i);
7502 if (i == 0 && IS_BRANCH(psrc)) {
7505 mdb_cursor_copy(csrc, &mn);
7506 /* must find the lowest key below src */
7507 rc = mdb_page_search_lowest(&mn);
7510 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7511 key.mv_size = mn.mc_db->md_pad;
7512 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7514 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7515 key.mv_size = NODEKSZ(s2);
7516 key.mv_data = NODEKEY(s2);
7519 key.mv_size = srcnode->mn_ksize;
7520 key.mv_data = NODEKEY(srcnode);
7523 data.mv_size = NODEDSZ(srcnode);
7524 data.mv_data = NODEDATA(srcnode);
7525 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7526 if (rc != MDB_SUCCESS)
7531 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7532 pdst->mp_pgno, NUMKEYS(pdst),
7533 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7535 /* Unlink the src page from parent and add to free list.
7538 mdb_node_del(csrc, 0);
7539 if (csrc->mc_ki[csrc->mc_top] == 0) {
7541 rc = mdb_update_key(csrc, &key);
7549 psrc = csrc->mc_pg[csrc->mc_top];
7550 /* If not operating on FreeDB, allow this page to be reused
7551 * in this txn. Otherwise just add to free list.
7553 rc = mdb_page_loose(csrc, psrc);
7557 csrc->mc_db->md_leaf_pages--;
7559 csrc->mc_db->md_branch_pages--;
7561 /* Adjust other cursors pointing to mp */
7562 MDB_cursor *m2, *m3;
7563 MDB_dbi dbi = csrc->mc_dbi;
7565 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7566 if (csrc->mc_flags & C_SUB)
7567 m3 = &m2->mc_xcursor->mx_cursor;
7570 if (m3 == csrc) continue;
7571 if (m3->mc_snum < csrc->mc_snum) continue;
7572 if (m3->mc_pg[csrc->mc_top] == psrc) {
7573 m3->mc_pg[csrc->mc_top] = pdst;
7574 m3->mc_ki[csrc->mc_top] += nkeys;
7579 unsigned int snum = cdst->mc_snum;
7580 uint16_t depth = cdst->mc_db->md_depth;
7581 mdb_cursor_pop(cdst);
7582 rc = mdb_rebalance(cdst);
7583 /* Did the tree shrink? */
7584 if (depth > cdst->mc_db->md_depth)
7586 cdst->mc_snum = snum;
7587 cdst->mc_top = snum-1;
7592 /** Copy the contents of a cursor.
7593 * @param[in] csrc The cursor to copy from.
7594 * @param[out] cdst The cursor to copy to.
7597 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7601 cdst->mc_txn = csrc->mc_txn;
7602 cdst->mc_dbi = csrc->mc_dbi;
7603 cdst->mc_db = csrc->mc_db;
7604 cdst->mc_dbx = csrc->mc_dbx;
7605 cdst->mc_snum = csrc->mc_snum;
7606 cdst->mc_top = csrc->mc_top;
7607 cdst->mc_flags = csrc->mc_flags;
7609 for (i=0; i<csrc->mc_snum; i++) {
7610 cdst->mc_pg[i] = csrc->mc_pg[i];
7611 cdst->mc_ki[i] = csrc->mc_ki[i];
7615 /** Rebalance the tree after a delete operation.
7616 * @param[in] mc Cursor pointing to the page where rebalancing
7618 * @return 0 on success, non-zero on failure.
7621 mdb_rebalance(MDB_cursor *mc)
7625 unsigned int ptop, minkeys;
7629 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7630 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7631 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7632 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7633 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7635 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7636 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7637 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7638 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7642 if (mc->mc_snum < 2) {
7643 MDB_page *mp = mc->mc_pg[0];
7645 DPUTS("Can't rebalance a subpage, ignoring");
7648 if (NUMKEYS(mp) == 0) {
7649 DPUTS("tree is completely empty");
7650 mc->mc_db->md_root = P_INVALID;
7651 mc->mc_db->md_depth = 0;
7652 mc->mc_db->md_leaf_pages = 0;
7653 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7656 /* Adjust cursors pointing to mp */
7659 mc->mc_flags &= ~C_INITIALIZED;
7661 MDB_cursor *m2, *m3;
7662 MDB_dbi dbi = mc->mc_dbi;
7664 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7665 if (mc->mc_flags & C_SUB)
7666 m3 = &m2->mc_xcursor->mx_cursor;
7669 if (m3->mc_snum < mc->mc_snum) continue;
7670 if (m3->mc_pg[0] == mp) {
7673 m3->mc_flags &= ~C_INITIALIZED;
7677 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7679 DPUTS("collapsing root page!");
7680 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7683 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7684 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7687 mc->mc_db->md_depth--;
7688 mc->mc_db->md_branch_pages--;
7689 mc->mc_ki[0] = mc->mc_ki[1];
7690 for (i = 1; i<mc->mc_db->md_depth; i++) {
7691 mc->mc_pg[i] = mc->mc_pg[i+1];
7692 mc->mc_ki[i] = mc->mc_ki[i+1];
7695 /* Adjust other cursors pointing to mp */
7696 MDB_cursor *m2, *m3;
7697 MDB_dbi dbi = mc->mc_dbi;
7699 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7700 if (mc->mc_flags & C_SUB)
7701 m3 = &m2->mc_xcursor->mx_cursor;
7704 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7705 if (m3->mc_pg[0] == mp) {
7708 for (i=0; i<m3->mc_snum; i++) {
7709 m3->mc_pg[i] = m3->mc_pg[i+1];
7710 m3->mc_ki[i] = m3->mc_ki[i+1];
7716 DPUTS("root page doesn't need rebalancing");
7720 /* The parent (branch page) must have at least 2 pointers,
7721 * otherwise the tree is invalid.
7723 ptop = mc->mc_top-1;
7724 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
7726 /* Leaf page fill factor is below the threshold.
7727 * Try to move keys from left or right neighbor, or
7728 * merge with a neighbor page.
7733 mdb_cursor_copy(mc, &mn);
7734 mn.mc_xcursor = NULL;
7736 oldki = mc->mc_ki[mc->mc_top];
7737 if (mc->mc_ki[ptop] == 0) {
7738 /* We're the leftmost leaf in our parent.
7740 DPUTS("reading right neighbor");
7742 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7743 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7746 mn.mc_ki[mn.mc_top] = 0;
7747 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7749 /* There is at least one neighbor to the left.
7751 DPUTS("reading left neighbor");
7753 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7754 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7757 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7758 mc->mc_ki[mc->mc_top] = 0;
7761 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7762 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7763 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7765 /* If the neighbor page is above threshold and has enough keys,
7766 * move one key from it. Otherwise we should try to merge them.
7767 * (A branch page must never have less than 2 keys.)
7769 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7770 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
7771 rc = mdb_node_move(&mn, mc);
7772 if (mc->mc_ki[ptop]) {
7776 if (mc->mc_ki[ptop] == 0) {
7777 rc = mdb_page_merge(&mn, mc);
7779 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
7780 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7781 rc = mdb_page_merge(mc, &mn);
7782 mdb_cursor_copy(&mn, mc);
7784 mc->mc_flags &= ~C_EOF;
7786 mc->mc_ki[mc->mc_top] = oldki;
7790 /** Complete a delete operation started by #mdb_cursor_del(). */
7792 mdb_cursor_del0(MDB_cursor *mc)
7799 ki = mc->mc_ki[mc->mc_top];
7800 mdb_node_del(mc, mc->mc_db->md_pad);
7801 mc->mc_db->md_entries--;
7802 rc = mdb_rebalance(mc);
7804 if (rc == MDB_SUCCESS) {
7805 MDB_cursor *m2, *m3;
7806 MDB_dbi dbi = mc->mc_dbi;
7808 mp = mc->mc_pg[mc->mc_top];
7809 nkeys = NUMKEYS(mp);
7811 /* if mc points past last node in page, find next sibling */
7812 if (mc->mc_ki[mc->mc_top] >= nkeys) {
7813 rc = mdb_cursor_sibling(mc, 1);
7814 if (rc == MDB_NOTFOUND) {
7815 mc->mc_flags |= C_EOF;
7820 /* Adjust other cursors pointing to mp */
7821 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
7822 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
7823 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7825 if (m3 == mc || m3->mc_snum < mc->mc_snum)
7827 if (m3->mc_pg[mc->mc_top] == mp) {
7828 if (m3->mc_ki[mc->mc_top] >= ki) {
7829 m3->mc_flags |= C_DEL;
7830 if (m3->mc_ki[mc->mc_top] > ki)
7831 m3->mc_ki[mc->mc_top]--;
7832 else if (mc->mc_db->md_flags & MDB_DUPSORT)
7833 m3->mc_xcursor->mx_cursor.mc_flags |= C_EOF;
7835 if (m3->mc_ki[mc->mc_top] >= nkeys) {
7836 rc = mdb_cursor_sibling(m3, 1);
7837 if (rc == MDB_NOTFOUND) {
7838 m3->mc_flags |= C_EOF;
7844 mc->mc_flags |= C_DEL;
7848 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7853 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7854 MDB_val *key, MDB_val *data)
7856 if (!key || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
7859 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7860 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7862 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7863 /* must ignore any data */
7867 return mdb_del0(txn, dbi, key, data, 0);
7871 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
7872 MDB_val *key, MDB_val *data, unsigned flags)
7877 MDB_val rdata, *xdata;
7881 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7883 mdb_cursor_init(&mc, txn, dbi, &mx);
7892 flags |= MDB_NODUPDATA;
7894 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7896 /* let mdb_page_split know about this cursor if needed:
7897 * delete will trigger a rebalance; if it needs to move
7898 * a node from one page to another, it will have to
7899 * update the parent's separator key(s). If the new sepkey
7900 * is larger than the current one, the parent page may
7901 * run out of space, triggering a split. We need this
7902 * cursor to be consistent until the end of the rebalance.
7904 mc.mc_flags |= C_UNTRACK;
7905 mc.mc_next = txn->mt_cursors[dbi];
7906 txn->mt_cursors[dbi] = &mc;
7907 rc = mdb_cursor_del(&mc, flags);
7908 txn->mt_cursors[dbi] = mc.mc_next;
7913 /** Split a page and insert a new node.
7914 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7915 * The cursor will be updated to point to the actual page and index where
7916 * the node got inserted after the split.
7917 * @param[in] newkey The key for the newly inserted node.
7918 * @param[in] newdata The data for the newly inserted node.
7919 * @param[in] newpgno The page number, if the new node is a branch node.
7920 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7921 * @return 0 on success, non-zero on failure.
7924 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7925 unsigned int nflags)
7928 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7931 int i, j, split_indx, nkeys, pmax;
7932 MDB_env *env = mc->mc_txn->mt_env;
7934 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7935 MDB_page *copy = NULL;
7936 MDB_page *mp, *rp, *pp;
7941 mp = mc->mc_pg[mc->mc_top];
7942 newindx = mc->mc_ki[mc->mc_top];
7943 nkeys = NUMKEYS(mp);
7945 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
7946 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7947 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
7949 /* Create a right sibling. */
7950 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7952 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7954 if (mc->mc_snum < 2) {
7955 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7957 /* shift current top to make room for new parent */
7958 mc->mc_pg[1] = mc->mc_pg[0];
7959 mc->mc_ki[1] = mc->mc_ki[0];
7962 mc->mc_db->md_root = pp->mp_pgno;
7963 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7964 mc->mc_db->md_depth++;
7967 /* Add left (implicit) pointer. */
7968 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7969 /* undo the pre-push */
7970 mc->mc_pg[0] = mc->mc_pg[1];
7971 mc->mc_ki[0] = mc->mc_ki[1];
7972 mc->mc_db->md_root = mp->mp_pgno;
7973 mc->mc_db->md_depth--;
7980 ptop = mc->mc_top-1;
7981 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7984 mc->mc_flags |= C_SPLITTING;
7985 mdb_cursor_copy(mc, &mn);
7986 mn.mc_pg[mn.mc_top] = rp;
7987 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7989 if (nflags & MDB_APPEND) {
7990 mn.mc_ki[mn.mc_top] = 0;
7992 split_indx = newindx;
7996 split_indx = (nkeys+1) / 2;
8001 unsigned int lsize, rsize, ksize;
8002 /* Move half of the keys to the right sibling */
8003 x = mc->mc_ki[mc->mc_top] - split_indx;
8004 ksize = mc->mc_db->md_pad;
8005 split = LEAF2KEY(mp, split_indx, ksize);
8006 rsize = (nkeys - split_indx) * ksize;
8007 lsize = (nkeys - split_indx) * sizeof(indx_t);
8008 mp->mp_lower -= lsize;
8009 rp->mp_lower += lsize;
8010 mp->mp_upper += rsize - lsize;
8011 rp->mp_upper -= rsize - lsize;
8012 sepkey.mv_size = ksize;
8013 if (newindx == split_indx) {
8014 sepkey.mv_data = newkey->mv_data;
8016 sepkey.mv_data = split;
8019 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
8020 memcpy(rp->mp_ptrs, split, rsize);
8021 sepkey.mv_data = rp->mp_ptrs;
8022 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
8023 memcpy(ins, newkey->mv_data, ksize);
8024 mp->mp_lower += sizeof(indx_t);
8025 mp->mp_upper -= ksize - sizeof(indx_t);
8028 memcpy(rp->mp_ptrs, split, x * ksize);
8029 ins = LEAF2KEY(rp, x, ksize);
8030 memcpy(ins, newkey->mv_data, ksize);
8031 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
8032 rp->mp_lower += sizeof(indx_t);
8033 rp->mp_upper -= ksize - sizeof(indx_t);
8034 mc->mc_ki[mc->mc_top] = x;
8035 mc->mc_pg[mc->mc_top] = rp;
8038 int psize, nsize, k;
8039 /* Maximum free space in an empty page */
8040 pmax = env->me_psize - PAGEHDRSZ;
8042 nsize = mdb_leaf_size(env, newkey, newdata);
8044 nsize = mdb_branch_size(env, newkey);
8045 nsize = EVEN(nsize);
8047 /* grab a page to hold a temporary copy */
8048 copy = mdb_page_malloc(mc->mc_txn, 1);
8053 copy->mp_pgno = mp->mp_pgno;
8054 copy->mp_flags = mp->mp_flags;
8055 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
8056 copy->mp_upper = env->me_psize - PAGEBASE;
8058 /* prepare to insert */
8059 for (i=0, j=0; i<nkeys; i++) {
8061 copy->mp_ptrs[j++] = 0;
8063 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
8066 /* When items are relatively large the split point needs
8067 * to be checked, because being off-by-one will make the
8068 * difference between success or failure in mdb_node_add.
8070 * It's also relevant if a page happens to be laid out
8071 * such that one half of its nodes are all "small" and
8072 * the other half of its nodes are "large." If the new
8073 * item is also "large" and falls on the half with
8074 * "large" nodes, it also may not fit.
8076 * As a final tweak, if the new item goes on the last
8077 * spot on the page (and thus, onto the new page), bias
8078 * the split so the new page is emptier than the old page.
8079 * This yields better packing during sequential inserts.
8081 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
8082 /* Find split point */
8084 if (newindx <= split_indx || newindx >= nkeys) {
8086 k = newindx >= nkeys ? nkeys : split_indx+2;
8091 for (; i!=k; i+=j) {
8096 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8097 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
8099 if (F_ISSET(node->mn_flags, F_BIGDATA))
8100 psize += sizeof(pgno_t);
8102 psize += NODEDSZ(node);
8104 psize = EVEN(psize);
8106 if (psize > pmax || i == k-j) {
8107 split_indx = i + (j<0);
8112 if (split_indx == newindx) {
8113 sepkey.mv_size = newkey->mv_size;
8114 sepkey.mv_data = newkey->mv_data;
8116 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
8117 sepkey.mv_size = node->mn_ksize;
8118 sepkey.mv_data = NODEKEY(node);
8123 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
8125 /* Copy separator key to the parent.
8127 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
8131 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
8136 if (mn.mc_snum == mc->mc_snum) {
8137 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
8138 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
8139 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
8140 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
8145 /* Right page might now have changed parent.
8146 * Check if left page also changed parent.
8148 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8149 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8150 for (i=0; i<ptop; i++) {
8151 mc->mc_pg[i] = mn.mc_pg[i];
8152 mc->mc_ki[i] = mn.mc_ki[i];
8154 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8155 if (mn.mc_ki[ptop]) {
8156 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8158 /* find right page's left sibling */
8159 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8160 mdb_cursor_sibling(mc, 0);
8165 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8168 mc->mc_flags ^= C_SPLITTING;
8169 if (rc != MDB_SUCCESS) {
8172 if (nflags & MDB_APPEND) {
8173 mc->mc_pg[mc->mc_top] = rp;
8174 mc->mc_ki[mc->mc_top] = 0;
8175 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8178 for (i=0; i<mc->mc_top; i++)
8179 mc->mc_ki[i] = mn.mc_ki[i];
8180 } else if (!IS_LEAF2(mp)) {
8182 mc->mc_pg[mc->mc_top] = rp;
8187 rkey.mv_data = newkey->mv_data;
8188 rkey.mv_size = newkey->mv_size;
8194 /* Update index for the new key. */
8195 mc->mc_ki[mc->mc_top] = j;
8197 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8198 rkey.mv_data = NODEKEY(node);
8199 rkey.mv_size = node->mn_ksize;
8201 xdata.mv_data = NODEDATA(node);
8202 xdata.mv_size = NODEDSZ(node);
8205 pgno = NODEPGNO(node);
8206 flags = node->mn_flags;
8209 if (!IS_LEAF(mp) && j == 0) {
8210 /* First branch index doesn't need key data. */
8214 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8220 mc->mc_pg[mc->mc_top] = copy;
8225 } while (i != split_indx);
8227 nkeys = NUMKEYS(copy);
8228 for (i=0; i<nkeys; i++)
8229 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8230 mp->mp_lower = copy->mp_lower;
8231 mp->mp_upper = copy->mp_upper;
8232 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8233 env->me_psize - copy->mp_upper - PAGEBASE);
8235 /* reset back to original page */
8236 if (newindx < split_indx) {
8237 mc->mc_pg[mc->mc_top] = mp;
8238 if (nflags & MDB_RESERVE) {
8239 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
8240 if (!(node->mn_flags & F_BIGDATA))
8241 newdata->mv_data = NODEDATA(node);
8244 mc->mc_pg[mc->mc_top] = rp;
8246 /* Make sure mc_ki is still valid.
8248 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8249 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8250 for (i=0; i<=ptop; i++) {
8251 mc->mc_pg[i] = mn.mc_pg[i];
8252 mc->mc_ki[i] = mn.mc_ki[i];
8259 /* Adjust other cursors pointing to mp */
8260 MDB_cursor *m2, *m3;
8261 MDB_dbi dbi = mc->mc_dbi;
8262 int fixup = NUMKEYS(mp);
8264 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8265 if (mc->mc_flags & C_SUB)
8266 m3 = &m2->mc_xcursor->mx_cursor;
8271 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8273 if (m3->mc_flags & C_SPLITTING)
8278 for (k=m3->mc_top; k>=0; k--) {
8279 m3->mc_ki[k+1] = m3->mc_ki[k];
8280 m3->mc_pg[k+1] = m3->mc_pg[k];
8282 if (m3->mc_ki[0] >= split_indx) {
8287 m3->mc_pg[0] = mc->mc_pg[0];
8291 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8292 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8293 m3->mc_ki[mc->mc_top]++;
8294 if (m3->mc_ki[mc->mc_top] >= fixup) {
8295 m3->mc_pg[mc->mc_top] = rp;
8296 m3->mc_ki[mc->mc_top] -= fixup;
8297 m3->mc_ki[ptop] = mn.mc_ki[ptop];
8299 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8300 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8305 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8308 if (copy) /* tmp page */
8309 mdb_page_free(env, copy);
8311 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8316 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8317 MDB_val *key, MDB_val *data, unsigned int flags)
8322 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8325 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
8328 mdb_cursor_init(&mc, txn, dbi, &mx);
8329 return mdb_cursor_put(&mc, key, data, flags);
8333 #define MDB_WBUF (1024*1024)
8336 /** State needed for a compacting copy. */
8337 typedef struct mdb_copy {
8338 pthread_mutex_t mc_mutex;
8339 pthread_cond_t mc_cond;
8346 pgno_t mc_next_pgno;
8349 volatile int mc_new;
8354 /** Dedicated writer thread for compacting copy. */
8355 static THREAD_RET ESECT
8356 mdb_env_copythr(void *arg)
8360 int toggle = 0, wsize, rc;
8363 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8366 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8369 pthread_mutex_lock(&my->mc_mutex);
8371 pthread_cond_signal(&my->mc_cond);
8374 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8375 if (my->mc_new < 0) {
8380 wsize = my->mc_wlen[toggle];
8381 ptr = my->mc_wbuf[toggle];
8384 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8388 } else if (len > 0) {
8402 /* If there's an overflow page tail, write it too */
8403 if (my->mc_olen[toggle]) {
8404 wsize = my->mc_olen[toggle];
8405 ptr = my->mc_over[toggle];
8406 my->mc_olen[toggle] = 0;
8409 my->mc_wlen[toggle] = 0;
8411 pthread_cond_signal(&my->mc_cond);
8413 pthread_cond_signal(&my->mc_cond);
8414 pthread_mutex_unlock(&my->mc_mutex);
8415 return (THREAD_RET)0;
8419 /** Tell the writer thread there's a buffer ready to write */
8421 mdb_env_cthr_toggle(mdb_copy *my, int st)
8423 int toggle = my->mc_toggle ^ 1;
8424 pthread_mutex_lock(&my->mc_mutex);
8425 if (my->mc_status) {
8426 pthread_mutex_unlock(&my->mc_mutex);
8427 return my->mc_status;
8429 while (my->mc_new == 1)
8430 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8432 my->mc_toggle = toggle;
8433 pthread_cond_signal(&my->mc_cond);
8434 pthread_mutex_unlock(&my->mc_mutex);
8438 /** Depth-first tree traversal for compacting copy. */
8440 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8443 MDB_txn *txn = my->mc_txn;
8445 MDB_page *mo, *mp, *leaf;
8450 /* Empty DB, nothing to do */
8451 if (*pg == P_INVALID)
8458 rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
8461 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8465 /* Make cursor pages writable */
8466 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8470 for (i=0; i<mc.mc_top; i++) {
8471 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8472 mc.mc_pg[i] = (MDB_page *)ptr;
8473 ptr += my->mc_env->me_psize;
8476 /* This is writable space for a leaf page. Usually not needed. */
8477 leaf = (MDB_page *)ptr;
8479 toggle = my->mc_toggle;
8480 while (mc.mc_snum > 0) {
8482 mp = mc.mc_pg[mc.mc_top];
8486 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8487 for (i=0; i<n; i++) {
8488 ni = NODEPTR(mp, i);
8489 if (ni->mn_flags & F_BIGDATA) {
8493 /* Need writable leaf */
8495 mc.mc_pg[mc.mc_top] = leaf;
8496 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8498 ni = NODEPTR(mp, i);
8501 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8502 rc = mdb_page_get(txn, pg, &omp, NULL);
8505 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8506 rc = mdb_env_cthr_toggle(my, 1);
8509 toggle = my->mc_toggle;
8511 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8512 memcpy(mo, omp, my->mc_env->me_psize);
8513 mo->mp_pgno = my->mc_next_pgno;
8514 my->mc_next_pgno += omp->mp_pages;
8515 my->mc_wlen[toggle] += my->mc_env->me_psize;
8516 if (omp->mp_pages > 1) {
8517 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
8518 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
8519 rc = mdb_env_cthr_toggle(my, 1);
8522 toggle = my->mc_toggle;
8524 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
8525 } else if (ni->mn_flags & F_SUBDATA) {
8528 /* Need writable leaf */
8530 mc.mc_pg[mc.mc_top] = leaf;
8531 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8533 ni = NODEPTR(mp, i);
8536 memcpy(&db, NODEDATA(ni), sizeof(db));
8537 my->mc_toggle = toggle;
8538 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
8541 toggle = my->mc_toggle;
8542 memcpy(NODEDATA(ni), &db, sizeof(db));
8547 mc.mc_ki[mc.mc_top]++;
8548 if (mc.mc_ki[mc.mc_top] < n) {
8551 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
8553 rc = mdb_page_get(txn, pg, &mp, NULL);
8558 mc.mc_ki[mc.mc_top] = 0;
8559 if (IS_BRANCH(mp)) {
8560 /* Whenever we advance to a sibling branch page,
8561 * we must proceed all the way down to its first leaf.
8563 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
8566 mc.mc_pg[mc.mc_top] = mp;
8570 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8571 rc = mdb_env_cthr_toggle(my, 1);
8574 toggle = my->mc_toggle;
8576 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8577 mdb_page_copy(mo, mp, my->mc_env->me_psize);
8578 mo->mp_pgno = my->mc_next_pgno++;
8579 my->mc_wlen[toggle] += my->mc_env->me_psize;
8581 /* Update parent if there is one */
8582 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
8583 SETPGNO(ni, mo->mp_pgno);
8584 mdb_cursor_pop(&mc);
8586 /* Otherwise we're done */
8596 /** Copy environment with compaction. */
8598 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
8603 MDB_txn *txn = NULL;
8608 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
8609 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
8610 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
8611 if (my.mc_wbuf[0] == NULL)
8614 pthread_mutex_init(&my.mc_mutex, NULL);
8615 pthread_cond_init(&my.mc_cond, NULL);
8616 #ifdef HAVE_MEMALIGN
8617 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
8618 if (my.mc_wbuf[0] == NULL)
8621 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_os_psize, MDB_WBUF*2);
8626 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
8627 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
8632 my.mc_next_pgno = 2;
8638 THREAD_CREATE(thr, mdb_env_copythr, &my);
8640 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8644 mp = (MDB_page *)my.mc_wbuf[0];
8645 memset(mp, 0, 2*env->me_psize);
8647 mp->mp_flags = P_META;
8648 mm = (MDB_meta *)METADATA(mp);
8649 mdb_env_init_meta0(env, mm);
8650 mm->mm_address = env->me_metas[0]->mm_address;
8652 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
8654 mp->mp_flags = P_META;
8655 *(MDB_meta *)METADATA(mp) = *mm;
8656 mm = (MDB_meta *)METADATA(mp);
8658 /* Count the number of free pages, subtract from lastpg to find
8659 * number of active pages
8662 MDB_ID freecount = 0;
8665 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
8666 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
8667 freecount += *(MDB_ID *)data.mv_data;
8668 freecount += txn->mt_dbs[0].md_branch_pages +
8669 txn->mt_dbs[0].md_leaf_pages +
8670 txn->mt_dbs[0].md_overflow_pages;
8672 /* Set metapage 1 */
8673 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
8674 mm->mm_dbs[1] = txn->mt_dbs[1];
8675 if (mm->mm_last_pg > 1) {
8676 mm->mm_dbs[1].md_root = mm->mm_last_pg;
8679 mm->mm_dbs[1].md_root = P_INVALID;
8682 my.mc_wlen[0] = env->me_psize * 2;
8684 pthread_mutex_lock(&my.mc_mutex);
8686 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8687 pthread_mutex_unlock(&my.mc_mutex);
8688 rc = mdb_env_cwalk(&my, &txn->mt_dbs[1].md_root, 0);
8689 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
8690 rc = mdb_env_cthr_toggle(&my, 1);
8691 mdb_env_cthr_toggle(&my, -1);
8692 pthread_mutex_lock(&my.mc_mutex);
8694 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8695 pthread_mutex_unlock(&my.mc_mutex);
8700 CloseHandle(my.mc_cond);
8701 CloseHandle(my.mc_mutex);
8702 _aligned_free(my.mc_wbuf[0]);
8704 pthread_cond_destroy(&my.mc_cond);
8705 pthread_mutex_destroy(&my.mc_mutex);
8706 free(my.mc_wbuf[0]);
8711 /** Copy environment as-is. */
8713 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
8715 MDB_txn *txn = NULL;
8721 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8725 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8728 /* Do the lock/unlock of the reader mutex before starting the
8729 * write txn. Otherwise other read txns could block writers.
8731 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8736 /* We must start the actual read txn after blocking writers */
8737 mdb_txn_reset0(txn, "reset-stage1");
8739 /* Temporarily block writers until we snapshot the meta pages */
8742 rc = mdb_txn_renew0(txn);
8744 UNLOCK_MUTEX_W(env);
8749 wsize = env->me_psize * 2;
8753 DO_WRITE(rc, fd, ptr, w2, len);
8757 } else if (len > 0) {
8763 /* Non-blocking or async handles are not supported */
8769 UNLOCK_MUTEX_W(env);
8774 w2 = txn->mt_next_pgno * env->me_psize;
8777 if ((rc = mdb_fsize(env->me_fd, &fsize)))
8784 if (wsize > MAX_WRITE)
8788 DO_WRITE(rc, fd, ptr, w2, len);
8792 } else if (len > 0) {
8809 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
8811 if (flags & MDB_CP_COMPACT)
8812 return mdb_env_copyfd1(env, fd);
8814 return mdb_env_copyfd0(env, fd);
8818 mdb_env_copyfd(MDB_env *env, HANDLE fd)
8820 return mdb_env_copyfd2(env, fd, 0);
8824 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
8828 HANDLE newfd = INVALID_HANDLE_VALUE;
8830 if (env->me_flags & MDB_NOSUBDIR) {
8831 lpath = (char *)path;
8834 len += sizeof(DATANAME);
8835 lpath = malloc(len);
8838 sprintf(lpath, "%s" DATANAME, path);
8841 /* The destination path must exist, but the destination file must not.
8842 * We don't want the OS to cache the writes, since the source data is
8843 * already in the OS cache.
8846 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
8847 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
8849 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
8851 if (newfd == INVALID_HANDLE_VALUE) {
8856 if (env->me_psize >= env->me_os_psize) {
8858 /* Set O_DIRECT if the file system supports it */
8859 if ((rc = fcntl(newfd, F_GETFL)) != -1)
8860 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
8862 #ifdef F_NOCACHE /* __APPLE__ */
8863 rc = fcntl(newfd, F_NOCACHE, 1);
8871 rc = mdb_env_copyfd2(env, newfd, flags);
8874 if (!(env->me_flags & MDB_NOSUBDIR))
8876 if (newfd != INVALID_HANDLE_VALUE)
8877 if (close(newfd) < 0 && rc == MDB_SUCCESS)
8884 mdb_env_copy(MDB_env *env, const char *path)
8886 return mdb_env_copy2(env, path, 0);
8890 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
8892 if ((flag & CHANGEABLE) != flag)
8895 env->me_flags |= flag;
8897 env->me_flags &= ~flag;
8902 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
8907 *arg = env->me_flags;
8912 mdb_env_set_userctx(MDB_env *env, void *ctx)
8916 env->me_userctx = ctx;
8921 mdb_env_get_userctx(MDB_env *env)
8923 return env ? env->me_userctx : NULL;
8927 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
8932 env->me_assert_func = func;
8938 mdb_env_get_path(MDB_env *env, const char **arg)
8943 *arg = env->me_path;
8948 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
8957 /** Common code for #mdb_stat() and #mdb_env_stat().
8958 * @param[in] env the environment to operate in.
8959 * @param[in] db the #MDB_db record containing the stats to return.
8960 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
8961 * @return 0, this function always succeeds.
8964 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
8966 arg->ms_psize = env->me_psize;
8967 arg->ms_depth = db->md_depth;
8968 arg->ms_branch_pages = db->md_branch_pages;
8969 arg->ms_leaf_pages = db->md_leaf_pages;
8970 arg->ms_overflow_pages = db->md_overflow_pages;
8971 arg->ms_entries = db->md_entries;
8977 mdb_env_stat(MDB_env *env, MDB_stat *arg)
8981 if (env == NULL || arg == NULL)
8984 toggle = mdb_env_pick_meta(env);
8986 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
8990 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
8994 if (env == NULL || arg == NULL)
8997 toggle = mdb_env_pick_meta(env);
8998 arg->me_mapaddr = env->me_metas[toggle]->mm_address;
8999 arg->me_mapsize = env->me_mapsize;
9000 arg->me_maxreaders = env->me_maxreaders;
9002 /* me_numreaders may be zero if this process never used any readers. Use
9003 * the shared numreader count if it exists.
9005 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
9007 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
9008 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
9012 /** Set the default comparison functions for a database.
9013 * Called immediately after a database is opened to set the defaults.
9014 * The user can then override them with #mdb_set_compare() or
9015 * #mdb_set_dupsort().
9016 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
9017 * @param[in] dbi A database handle returned by #mdb_dbi_open()
9020 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
9022 uint16_t f = txn->mt_dbs[dbi].md_flags;
9024 txn->mt_dbxs[dbi].md_cmp =
9025 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
9026 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
9028 txn->mt_dbxs[dbi].md_dcmp =
9029 !(f & MDB_DUPSORT) ? 0 :
9030 ((f & MDB_INTEGERDUP)
9031 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
9032 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
9035 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
9041 int rc, dbflag, exact;
9042 unsigned int unused = 0, seq;
9045 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
9046 mdb_default_cmp(txn, FREE_DBI);
9049 if ((flags & VALID_FLAGS) != flags)
9051 if (txn->mt_flags & MDB_TXN_ERROR)
9057 if (flags & PERSISTENT_FLAGS) {
9058 uint16_t f2 = flags & PERSISTENT_FLAGS;
9059 /* make sure flag changes get committed */
9060 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
9061 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
9062 txn->mt_flags |= MDB_TXN_DIRTY;
9065 mdb_default_cmp(txn, MAIN_DBI);
9069 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
9070 mdb_default_cmp(txn, MAIN_DBI);
9073 /* Is the DB already open? */
9075 for (i=2; i<txn->mt_numdbs; i++) {
9076 if (!txn->mt_dbxs[i].md_name.mv_size) {
9077 /* Remember this free slot */
9078 if (!unused) unused = i;
9081 if (len == txn->mt_dbxs[i].md_name.mv_size &&
9082 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
9088 /* If no free slot and max hit, fail */
9089 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
9090 return MDB_DBS_FULL;
9092 /* Cannot mix named databases with some mainDB flags */
9093 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
9094 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
9096 /* Find the DB info */
9097 dbflag = DB_NEW|DB_VALID;
9100 key.mv_data = (void *)name;
9101 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
9102 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
9103 if (rc == MDB_SUCCESS) {
9104 /* make sure this is actually a DB */
9105 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
9106 if (!(node->mn_flags & F_SUBDATA))
9107 return MDB_INCOMPATIBLE;
9108 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
9109 /* Create if requested */
9110 data.mv_size = sizeof(MDB_db);
9111 data.mv_data = &dummy;
9112 memset(&dummy, 0, sizeof(dummy));
9113 dummy.md_root = P_INVALID;
9114 dummy.md_flags = flags & PERSISTENT_FLAGS;
9115 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
9119 /* OK, got info, add to table */
9120 if (rc == MDB_SUCCESS) {
9121 unsigned int slot = unused ? unused : txn->mt_numdbs;
9122 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
9123 txn->mt_dbxs[slot].md_name.mv_size = len;
9124 txn->mt_dbxs[slot].md_rel = NULL;
9125 txn->mt_dbflags[slot] = dbflag;
9126 /* txn-> and env-> are the same in read txns, use
9127 * tmp variable to avoid undefined assignment
9129 seq = ++txn->mt_env->me_dbiseqs[slot];
9130 txn->mt_dbiseqs[slot] = seq;
9132 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
9134 mdb_default_cmp(txn, slot);
9143 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9145 if (!arg || !TXN_DBI_EXIST(txn, dbi))
9148 if (txn->mt_flags & MDB_TXN_ERROR)
9151 if (txn->mt_dbflags[dbi] & DB_STALE) {
9154 /* Stale, must read the DB's root. cursor_init does it for us. */
9155 mdb_cursor_init(&mc, txn, dbi, &mx);
9157 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9160 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9163 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
9165 ptr = env->me_dbxs[dbi].md_name.mv_data;
9166 /* If there was no name, this was already closed */
9168 env->me_dbxs[dbi].md_name.mv_data = NULL;
9169 env->me_dbxs[dbi].md_name.mv_size = 0;
9170 env->me_dbflags[dbi] = 0;
9171 env->me_dbiseqs[dbi]++;
9176 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9178 /* We could return the flags for the FREE_DBI too but what's the point? */
9179 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9181 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9185 /** Add all the DB's pages to the free list.
9186 * @param[in] mc Cursor on the DB to free.
9187 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9188 * @return 0 on success, non-zero on failure.
9191 mdb_drop0(MDB_cursor *mc, int subs)
9195 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9196 if (rc == MDB_SUCCESS) {
9197 MDB_txn *txn = mc->mc_txn;
9202 /* LEAF2 pages have no nodes, cannot have sub-DBs */
9203 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
9206 mdb_cursor_copy(mc, &mx);
9207 while (mc->mc_snum > 0) {
9208 MDB_page *mp = mc->mc_pg[mc->mc_top];
9209 unsigned n = NUMKEYS(mp);
9211 for (i=0; i<n; i++) {
9212 ni = NODEPTR(mp, i);
9213 if (ni->mn_flags & F_BIGDATA) {
9216 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9217 rc = mdb_page_get(txn, pg, &omp, NULL);
9220 mdb_cassert(mc, IS_OVERFLOW(omp));
9221 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9225 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9226 mdb_xcursor_init1(mc, ni);
9227 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9233 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9235 for (i=0; i<n; i++) {
9237 ni = NODEPTR(mp, i);
9240 mdb_midl_xappend(txn->mt_free_pgs, pg);
9245 mc->mc_ki[mc->mc_top] = i;
9246 rc = mdb_cursor_sibling(mc, 1);
9248 if (rc != MDB_NOTFOUND)
9250 /* no more siblings, go back to beginning
9251 * of previous level.
9255 for (i=1; i<mc->mc_snum; i++) {
9257 mc->mc_pg[i] = mx.mc_pg[i];
9262 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9265 txn->mt_flags |= MDB_TXN_ERROR;
9266 } else if (rc == MDB_NOTFOUND) {
9272 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9274 MDB_cursor *mc, *m2;
9277 if ((unsigned)del > 1 || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9280 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9283 if (dbi > MAIN_DBI && TXN_DBI_CHANGED(txn, dbi))
9286 rc = mdb_cursor_open(txn, dbi, &mc);
9290 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9291 /* Invalidate the dropped DB's cursors */
9292 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9293 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9297 /* Can't delete the main DB */
9298 if (del && dbi > MAIN_DBI) {
9299 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, 0);
9301 txn->mt_dbflags[dbi] = DB_STALE;
9302 mdb_dbi_close(txn->mt_env, dbi);
9304 txn->mt_flags |= MDB_TXN_ERROR;
9307 /* reset the DB record, mark it dirty */
9308 txn->mt_dbflags[dbi] |= DB_DIRTY;
9309 txn->mt_dbs[dbi].md_depth = 0;
9310 txn->mt_dbs[dbi].md_branch_pages = 0;
9311 txn->mt_dbs[dbi].md_leaf_pages = 0;
9312 txn->mt_dbs[dbi].md_overflow_pages = 0;
9313 txn->mt_dbs[dbi].md_entries = 0;
9314 txn->mt_dbs[dbi].md_root = P_INVALID;
9316 txn->mt_flags |= MDB_TXN_DIRTY;
9319 mdb_cursor_close(mc);
9323 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9325 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9328 txn->mt_dbxs[dbi].md_cmp = cmp;
9332 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9334 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9337 txn->mt_dbxs[dbi].md_dcmp = cmp;
9341 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9343 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9346 txn->mt_dbxs[dbi].md_rel = rel;
9350 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9352 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9355 txn->mt_dbxs[dbi].md_relctx = ctx;
9360 mdb_env_get_maxkeysize(MDB_env *env)
9362 return ENV_MAXKEY(env);
9366 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9368 unsigned int i, rdrs;
9371 int rc = 0, first = 1;
9375 if (!env->me_txns) {
9376 return func("(no reader locks)\n", ctx);
9378 rdrs = env->me_txns->mti_numreaders;
9379 mr = env->me_txns->mti_readers;
9380 for (i=0; i<rdrs; i++) {
9382 txnid_t txnid = mr[i].mr_txnid;
9383 sprintf(buf, txnid == (txnid_t)-1 ?
9384 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9385 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9388 rc = func(" pid thread txnid\n", ctx);
9392 rc = func(buf, ctx);
9398 rc = func("(no active readers)\n", ctx);
9403 /** Insert pid into list if not already present.
9404 * return -1 if already present.
9407 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9409 /* binary search of pid in list */
9411 unsigned cursor = 1;
9413 unsigned n = ids[0];
9416 unsigned pivot = n >> 1;
9417 cursor = base + pivot + 1;
9418 val = pid - ids[cursor];
9423 } else if ( val > 0 ) {
9428 /* found, so it's a duplicate */
9437 for (n = ids[0]; n > cursor; n--)
9444 mdb_reader_check(MDB_env *env, int *dead)
9446 unsigned int i, j, rdrs;
9448 MDB_PID_T *pids, pid;
9457 rdrs = env->me_txns->mti_numreaders;
9458 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
9462 mr = env->me_txns->mti_readers;
9463 for (i=0; i<rdrs; i++) {
9464 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
9466 if (mdb_pid_insert(pids, pid) == 0) {
9467 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9469 /* Recheck, a new process may have reused pid */
9470 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9471 for (j=i; j<rdrs; j++)
9472 if (mr[j].mr_pid == pid) {
9473 DPRINTF(("clear stale reader pid %u txn %"Z"d",
9474 (unsigned) pid, mr[j].mr_txnid));
9479 UNLOCK_MUTEX_R(env);