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 lock 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;
992 /** List of read-only pages */
995 /** Number of DB records in use. This number only ever increments;
996 * we don't decrement it when individual DB handles are closed.
1000 /** @defgroup mdb_txn Transaction Flags
1004 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
1005 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1006 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1007 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1009 unsigned int mt_flags; /**< @ref mdb_txn */
1010 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1011 * Includes ancestor txns' dirty pages not hidden by other txns'
1012 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1013 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1015 unsigned int mt_dirty_room;
1018 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1019 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1020 * raise this on a 64 bit machine.
1022 #define CURSOR_STACK 32
1026 /** Cursors are used for all DB operations.
1027 * A cursor holds a path of (page pointer, key index) from the DB
1028 * root to a position in the DB, plus other state. #MDB_DUPSORT
1029 * cursors include an xcursor to the current data item. Write txns
1030 * track their cursors and keep them up to date when data moves.
1031 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1032 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1035 /** Next cursor on this DB in this txn */
1036 MDB_cursor *mc_next;
1037 /** Backup of the original cursor if this cursor is a shadow */
1038 MDB_cursor *mc_backup;
1039 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1040 struct MDB_xcursor *mc_xcursor;
1041 /** The transaction that owns this cursor */
1043 /** The database handle this cursor operates on */
1045 /** The database record for this cursor */
1047 /** The database auxiliary record for this cursor */
1049 /** The @ref mt_dbflag for this database */
1050 unsigned char *mc_dbflag;
1051 unsigned short mc_snum; /**< number of pushed pages */
1052 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1053 /** @defgroup mdb_cursor Cursor Flags
1055 * Cursor state flags.
1058 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1059 #define C_EOF 0x02 /**< No more data */
1060 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1061 #define C_DEL 0x08 /**< last op was a cursor_del */
1062 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
1063 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1065 unsigned int mc_flags; /**< @ref mdb_cursor */
1066 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1067 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1070 /** Context for sorted-dup records.
1071 * We could have gone to a fully recursive design, with arbitrarily
1072 * deep nesting of sub-databases. But for now we only handle these
1073 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1075 typedef struct MDB_xcursor {
1076 /** A sub-cursor for traversing the Dup DB */
1077 MDB_cursor mx_cursor;
1078 /** The database record for this Dup DB */
1080 /** The auxiliary DB record for this Dup DB */
1082 /** The @ref mt_dbflag for this Dup DB */
1083 unsigned char mx_dbflag;
1086 /** State of FreeDB old pages, stored in the MDB_env */
1087 typedef struct MDB_pgstate {
1088 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1089 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1092 /** The database environment. */
1094 HANDLE me_fd; /**< The main data file */
1095 HANDLE me_lfd; /**< The lock file */
1096 HANDLE me_mfd; /**< just for writing the meta pages */
1097 #if defined(VL32) && defined(_WIN32)
1098 HANDLE me_fmh; /**< File Mapping handle */
1100 /** Failed to update the meta page. Probably an I/O error. */
1101 #define MDB_FATAL_ERROR 0x80000000U
1102 /** Some fields are initialized. */
1103 #define MDB_ENV_ACTIVE 0x20000000U
1104 /** me_txkey is set */
1105 #define MDB_ENV_TXKEY 0x10000000U
1106 uint32_t me_flags; /**< @ref mdb_env */
1107 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1108 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1109 unsigned int me_maxreaders; /**< size of the reader table */
1110 unsigned int me_numreaders; /**< max numreaders set by this env */
1111 MDB_dbi me_numdbs; /**< number of DBs opened */
1112 MDB_dbi me_maxdbs; /**< size of the DB table */
1113 MDB_PID_T me_pid; /**< process ID of this env */
1114 char *me_path; /**< path to the DB files */
1115 char *me_map; /**< the memory map of the data file */
1116 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1117 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
1118 void *me_pbuf; /**< scratch area for DUPSORT put() */
1119 MDB_txn *me_txn; /**< current write transaction */
1120 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1121 size_t me_mapsize; /**< size of the data memory map */
1122 off_t me_size; /**< current file size */
1123 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1124 MDB_dbx *me_dbxs; /**< array of static DB info */
1125 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1126 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1127 pthread_key_t me_txkey; /**< thread-key for readers */
1128 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1129 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1130 # define me_pglast me_pgstate.mf_pglast
1131 # define me_pghead me_pgstate.mf_pghead
1132 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1133 /** IDL of pages that became unused in a write txn */
1134 MDB_IDL me_free_pgs;
1135 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1136 MDB_ID2L me_dirty_list;
1137 /** Max number of freelist items that can fit in a single overflow page */
1139 /** Max size of a node on a page */
1140 unsigned int me_nodemax;
1141 #if !(MDB_MAXKEYSIZE)
1142 unsigned int me_maxkey; /**< max size of a key */
1144 int me_live_reader; /**< have liveness lock in reader table */
1146 int me_pidquery; /**< Used in OpenProcess */
1147 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
1149 #elif defined(MDB_USE_POSIX_SEM)
1150 sem_t *me_rmutex; /* Shared mutexes are not supported */
1153 void *me_userctx; /**< User-settable context */
1154 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1157 /** Nested transaction */
1158 typedef struct MDB_ntxn {
1159 MDB_txn mnt_txn; /**< the transaction */
1160 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1163 /** max number of pages to commit in one writev() call */
1164 #define MDB_COMMIT_PAGES 64
1165 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1166 #undef MDB_COMMIT_PAGES
1167 #define MDB_COMMIT_PAGES IOV_MAX
1170 /** max bytes to write in one call */
1171 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1173 /** Check \b txn and \b dbi arguments to a function */
1174 #define TXN_DBI_EXIST(txn, dbi) \
1175 ((txn) && (dbi) < (txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & DB_VALID))
1177 /** Check for misused \b dbi handles */
1178 #define TXN_DBI_CHANGED(txn, dbi) \
1179 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1181 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1182 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1183 static int mdb_page_touch(MDB_cursor *mc);
1185 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1186 static int mdb_page_search_root(MDB_cursor *mc,
1187 MDB_val *key, int modify);
1188 #define MDB_PS_MODIFY 1
1189 #define MDB_PS_ROOTONLY 2
1190 #define MDB_PS_FIRST 4
1191 #define MDB_PS_LAST 8
1192 static int mdb_page_search(MDB_cursor *mc,
1193 MDB_val *key, int flags);
1194 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1196 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1197 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1198 pgno_t newpgno, unsigned int nflags);
1200 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1201 static int mdb_env_pick_meta(const MDB_env *env);
1202 static int mdb_env_write_meta(MDB_txn *txn);
1203 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1204 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1206 static void mdb_env_close0(MDB_env *env, int excl);
1208 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1209 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1210 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1211 static void mdb_node_del(MDB_cursor *mc, int ksize);
1212 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1213 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1214 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1215 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1216 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1218 static int mdb_rebalance(MDB_cursor *mc);
1219 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1221 static void mdb_cursor_pop(MDB_cursor *mc);
1222 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1224 static int mdb_cursor_del0(MDB_cursor *mc);
1225 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1226 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1227 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1228 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1229 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1231 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1232 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1234 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1235 static void mdb_xcursor_init0(MDB_cursor *mc);
1236 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1238 static int mdb_drop0(MDB_cursor *mc, int subs);
1239 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1242 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1246 static SECURITY_DESCRIPTOR mdb_null_sd;
1247 static SECURITY_ATTRIBUTES mdb_all_sa;
1248 static int mdb_sec_inited;
1251 /** Return the library version info. */
1253 mdb_version(int *major, int *minor, int *patch)
1255 if (major) *major = MDB_VERSION_MAJOR;
1256 if (minor) *minor = MDB_VERSION_MINOR;
1257 if (patch) *patch = MDB_VERSION_PATCH;
1258 return MDB_VERSION_STRING;
1261 /** Table of descriptions for LMDB @ref errors */
1262 static char *const mdb_errstr[] = {
1263 "MDB_KEYEXIST: Key/data pair already exists",
1264 "MDB_NOTFOUND: No matching key/data pair found",
1265 "MDB_PAGE_NOTFOUND: Requested page not found",
1266 "MDB_CORRUPTED: Located page was wrong type",
1267 "MDB_PANIC: Update of meta page failed",
1268 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1269 "MDB_INVALID: File is not an LMDB file",
1270 "MDB_MAP_FULL: Environment mapsize limit reached",
1271 "MDB_DBS_FULL: Environment maxdbs limit reached",
1272 "MDB_READERS_FULL: Environment maxreaders limit reached",
1273 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1274 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1275 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1276 "MDB_PAGE_FULL: Internal error - page has no more space",
1277 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1278 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1279 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1280 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1281 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1282 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1286 mdb_strerror(int err)
1289 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1290 * This works as long as no function between the call to mdb_strerror
1291 * and the actual use of the message uses more than 4K of stack.
1294 char buf[1024], *ptr = buf;
1298 return ("Successful return: 0");
1300 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1301 i = err - MDB_KEYEXIST;
1302 return mdb_errstr[i];
1306 /* These are the C-runtime error codes we use. The comment indicates
1307 * their numeric value, and the Win32 error they would correspond to
1308 * if the error actually came from a Win32 API. A major mess, we should
1309 * have used LMDB-specific error codes for everything.
1312 case ENOENT: /* 2, FILE_NOT_FOUND */
1313 case EIO: /* 5, ACCESS_DENIED */
1314 case ENOMEM: /* 12, INVALID_ACCESS */
1315 case EACCES: /* 13, INVALID_DATA */
1316 case EBUSY: /* 16, CURRENT_DIRECTORY */
1317 case EINVAL: /* 22, BAD_COMMAND */
1318 case ENOSPC: /* 28, OUT_OF_PAPER */
1319 return strerror(err);
1324 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1325 FORMAT_MESSAGE_IGNORE_INSERTS,
1326 NULL, err, 0, ptr, sizeof(buf), pad);
1329 return strerror(err);
1333 /** assert(3) variant in cursor context */
1334 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1335 /** assert(3) variant in transaction context */
1336 #define mdb_tassert(mc, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1337 /** assert(3) variant in environment context */
1338 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1341 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1342 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1345 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1346 const char *func, const char *file, int line)
1349 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1350 file, line, expr_txt, func);
1351 if (env->me_assert_func)
1352 env->me_assert_func(env, buf);
1353 fprintf(stderr, "%s\n", buf);
1357 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1361 /** Return the page number of \b mp which may be sub-page, for debug output */
1363 mdb_dbg_pgno(MDB_page *mp)
1366 COPY_PGNO(ret, mp->mp_pgno);
1370 /** Display a key in hexadecimal and return the address of the result.
1371 * @param[in] key the key to display
1372 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1373 * @return The key in hexadecimal form.
1376 mdb_dkey(MDB_val *key, char *buf)
1379 unsigned char *c = key->mv_data;
1385 if (key->mv_size > DKBUF_MAXKEYSIZE)
1386 return "MDB_MAXKEYSIZE";
1387 /* may want to make this a dynamic check: if the key is mostly
1388 * printable characters, print it as-is instead of converting to hex.
1392 for (i=0; i<key->mv_size; i++)
1393 ptr += sprintf(ptr, "%02x", *c++);
1395 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1401 mdb_leafnode_type(MDB_node *n)
1403 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1404 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1405 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1408 /** Display all the keys in the page. */
1410 mdb_page_list(MDB_page *mp)
1412 pgno_t pgno = mdb_dbg_pgno(mp);
1413 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1415 unsigned int i, nkeys, nsize, total = 0;
1419 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1420 case P_BRANCH: type = "Branch page"; break;
1421 case P_LEAF: type = "Leaf page"; break;
1422 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1423 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1424 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1426 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1427 pgno, mp->mp_pages, state);
1430 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1431 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1434 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1438 nkeys = NUMKEYS(mp);
1439 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1441 for (i=0; i<nkeys; i++) {
1442 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1443 key.mv_size = nsize = mp->mp_pad;
1444 key.mv_data = LEAF2KEY(mp, i, nsize);
1446 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1449 node = NODEPTR(mp, i);
1450 key.mv_size = node->mn_ksize;
1451 key.mv_data = node->mn_data;
1452 nsize = NODESIZE + key.mv_size;
1453 if (IS_BRANCH(mp)) {
1454 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1458 if (F_ISSET(node->mn_flags, F_BIGDATA))
1459 nsize += sizeof(pgno_t);
1461 nsize += NODEDSZ(node);
1463 nsize += sizeof(indx_t);
1464 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1465 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1467 total = EVEN(total);
1469 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1470 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1474 mdb_cursor_chk(MDB_cursor *mc)
1480 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1481 for (i=0; i<mc->mc_top; i++) {
1483 node = NODEPTR(mp, mc->mc_ki[i]);
1484 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1487 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1493 /** Count all the pages in each DB and in the freelist
1494 * and make sure it matches the actual number of pages
1496 * All named DBs must be open for a correct count.
1498 static void mdb_audit(MDB_txn *txn)
1502 MDB_ID freecount, count;
1507 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1508 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1509 freecount += *(MDB_ID *)data.mv_data;
1510 mdb_tassert(txn, rc == MDB_NOTFOUND);
1513 for (i = 0; i<txn->mt_numdbs; i++) {
1515 if (!(txn->mt_dbflags[i] & DB_VALID))
1517 mdb_cursor_init(&mc, txn, i, &mx);
1518 if (txn->mt_dbs[i].md_root == P_INVALID)
1520 count += txn->mt_dbs[i].md_branch_pages +
1521 txn->mt_dbs[i].md_leaf_pages +
1522 txn->mt_dbs[i].md_overflow_pages;
1523 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1524 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1525 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1528 mp = mc.mc_pg[mc.mc_top];
1529 for (j=0; j<NUMKEYS(mp); j++) {
1530 MDB_node *leaf = NODEPTR(mp, j);
1531 if (leaf->mn_flags & F_SUBDATA) {
1533 memcpy(&db, NODEDATA(leaf), sizeof(db));
1534 count += db.md_branch_pages + db.md_leaf_pages +
1535 db.md_overflow_pages;
1539 mdb_tassert(txn, rc == MDB_NOTFOUND);
1542 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1543 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1544 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1550 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1552 return txn->mt_dbxs[dbi].md_cmp(a, b);
1556 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1558 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1561 /** Allocate memory for a page.
1562 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1565 mdb_page_malloc(MDB_txn *txn, unsigned num)
1567 MDB_env *env = txn->mt_env;
1568 MDB_page *ret = env->me_dpages;
1569 size_t psize = env->me_psize, sz = psize, off;
1570 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1571 * For a single page alloc, we init everything after the page header.
1572 * For multi-page, we init the final page; if the caller needed that
1573 * many pages they will be filling in at least up to the last page.
1577 VGMEMP_ALLOC(env, ret, sz);
1578 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1579 env->me_dpages = ret->mp_next;
1582 psize -= off = PAGEHDRSZ;
1587 if ((ret = malloc(sz)) != NULL) {
1588 VGMEMP_ALLOC(env, ret, sz);
1589 if (!(env->me_flags & MDB_NOMEMINIT)) {
1590 memset((char *)ret + off, 0, psize);
1594 txn->mt_flags |= MDB_TXN_ERROR;
1598 /** Free a single page.
1599 * Saves single pages to a list, for future reuse.
1600 * (This is not used for multi-page overflow pages.)
1603 mdb_page_free(MDB_env *env, MDB_page *mp)
1605 mp->mp_next = env->me_dpages;
1606 VGMEMP_FREE(env, mp);
1607 env->me_dpages = mp;
1610 /** Free a dirty page */
1612 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1614 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1615 mdb_page_free(env, dp);
1617 /* large pages just get freed directly */
1618 VGMEMP_FREE(env, dp);
1623 /** Return all dirty pages to dpage list */
1625 mdb_dlist_free(MDB_txn *txn)
1627 MDB_env *env = txn->mt_env;
1628 MDB_ID2L dl = txn->mt_u.dirty_list;
1629 unsigned i, n = dl[0].mid;
1631 for (i = 1; i <= n; i++) {
1632 mdb_dpage_free(env, dl[i].mptr);
1637 /** Loosen or free a single page.
1638 * Saves single pages to a list for future reuse
1639 * in this same txn. It has been pulled from the freeDB
1640 * and already resides on the dirty list, but has been
1641 * deleted. Use these pages first before pulling again
1644 * If the page wasn't dirtied in this txn, just add it
1645 * to this txn's free list.
1648 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1651 pgno_t pgno = mp->mp_pgno;
1652 MDB_txn *txn = mc->mc_txn;
1654 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1655 if (txn->mt_parent) {
1656 MDB_ID2 *dl = txn->mt_u.dirty_list;
1657 /* If txn has a parent, make sure the page is in our
1661 unsigned x = mdb_mid2l_search(dl, pgno);
1662 if (x <= dl[0].mid && dl[x].mid == pgno) {
1663 if (mp != dl[x].mptr) { /* bad cursor? */
1664 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1665 txn->mt_flags |= MDB_TXN_ERROR;
1666 return MDB_CORRUPTED;
1673 /* no parent txn, so it's just ours */
1678 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1680 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1681 txn->mt_loose_pgs = mp;
1682 txn->mt_loose_count++;
1683 mp->mp_flags |= P_LOOSE;
1685 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1693 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1694 * @param[in] mc A cursor handle for the current operation.
1695 * @param[in] pflags Flags of the pages to update:
1696 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1697 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1698 * @return 0 on success, non-zero on failure.
1701 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1703 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1704 MDB_txn *txn = mc->mc_txn;
1710 int rc = MDB_SUCCESS, level;
1712 /* Mark pages seen by cursors */
1713 if (mc->mc_flags & C_UNTRACK)
1714 mc = NULL; /* will find mc in mt_cursors */
1715 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1716 for (; mc; mc=mc->mc_next) {
1717 if (!(mc->mc_flags & C_INITIALIZED))
1719 for (m3 = mc;; m3 = &mx->mx_cursor) {
1721 for (j=0; j<m3->mc_snum; j++) {
1723 if ((mp->mp_flags & Mask) == pflags)
1724 mp->mp_flags ^= P_KEEP;
1726 mx = m3->mc_xcursor;
1727 /* Proceed to mx if it is at a sub-database */
1728 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1730 if (! (mp && (mp->mp_flags & P_LEAF)))
1732 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1733 if (!(leaf->mn_flags & F_SUBDATA))
1742 /* Mark dirty root pages */
1743 for (i=0; i<txn->mt_numdbs; i++) {
1744 if (txn->mt_dbflags[i] & DB_DIRTY) {
1745 pgno_t pgno = txn->mt_dbs[i].md_root;
1746 if (pgno == P_INVALID)
1748 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1750 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1751 dp->mp_flags ^= P_KEEP;
1759 static int mdb_page_flush(MDB_txn *txn, int keep);
1761 /** Spill pages from the dirty list back to disk.
1762 * This is intended to prevent running into #MDB_TXN_FULL situations,
1763 * but note that they may still occur in a few cases:
1764 * 1) our estimate of the txn size could be too small. Currently this
1765 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1766 * 2) child txns may run out of space if their parents dirtied a
1767 * lot of pages and never spilled them. TODO: we probably should do
1768 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1769 * the parent's dirty_room is below a given threshold.
1771 * Otherwise, if not using nested txns, it is expected that apps will
1772 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1773 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1774 * If the txn never references them again, they can be left alone.
1775 * If the txn only reads them, they can be used without any fuss.
1776 * If the txn writes them again, they can be dirtied immediately without
1777 * going thru all of the work of #mdb_page_touch(). Such references are
1778 * handled by #mdb_page_unspill().
1780 * Also note, we never spill DB root pages, nor pages of active cursors,
1781 * because we'll need these back again soon anyway. And in nested txns,
1782 * we can't spill a page in a child txn if it was already spilled in a
1783 * parent txn. That would alter the parent txns' data even though
1784 * the child hasn't committed yet, and we'd have no way to undo it if
1785 * the child aborted.
1787 * @param[in] m0 cursor A cursor handle identifying the transaction and
1788 * database for which we are checking space.
1789 * @param[in] key For a put operation, the key being stored.
1790 * @param[in] data For a put operation, the data being stored.
1791 * @return 0 on success, non-zero on failure.
1794 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1796 MDB_txn *txn = m0->mc_txn;
1798 MDB_ID2L dl = txn->mt_u.dirty_list;
1799 unsigned int i, j, need;
1802 if (m0->mc_flags & C_SUB)
1805 /* Estimate how much space this op will take */
1806 i = m0->mc_db->md_depth;
1807 /* Named DBs also dirty the main DB */
1808 if (m0->mc_dbi > MAIN_DBI)
1809 i += txn->mt_dbs[MAIN_DBI].md_depth;
1810 /* For puts, roughly factor in the key+data size */
1812 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1813 i += i; /* double it for good measure */
1816 if (txn->mt_dirty_room > i)
1819 if (!txn->mt_spill_pgs) {
1820 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1821 if (!txn->mt_spill_pgs)
1824 /* purge deleted slots */
1825 MDB_IDL sl = txn->mt_spill_pgs;
1826 unsigned int num = sl[0];
1828 for (i=1; i<=num; i++) {
1835 /* Preserve pages which may soon be dirtied again */
1836 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1839 /* Less aggressive spill - we originally spilled the entire dirty list,
1840 * with a few exceptions for cursor pages and DB root pages. But this
1841 * turns out to be a lot of wasted effort because in a large txn many
1842 * of those pages will need to be used again. So now we spill only 1/8th
1843 * of the dirty pages. Testing revealed this to be a good tradeoff,
1844 * better than 1/2, 1/4, or 1/10.
1846 if (need < MDB_IDL_UM_MAX / 8)
1847 need = MDB_IDL_UM_MAX / 8;
1849 /* Save the page IDs of all the pages we're flushing */
1850 /* flush from the tail forward, this saves a lot of shifting later on. */
1851 for (i=dl[0].mid; i && need; i--) {
1852 MDB_ID pn = dl[i].mid << 1;
1854 if (dp->mp_flags & (P_LOOSE|P_KEEP))
1856 /* Can't spill twice, make sure it's not already in a parent's
1859 if (txn->mt_parent) {
1861 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1862 if (tx2->mt_spill_pgs) {
1863 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1864 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1865 dp->mp_flags |= P_KEEP;
1873 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1877 mdb_midl_sort(txn->mt_spill_pgs);
1879 /* Flush the spilled part of dirty list */
1880 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1883 /* Reset any dirty pages we kept that page_flush didn't see */
1884 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1887 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1891 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1893 mdb_find_oldest(MDB_txn *txn)
1896 txnid_t mr, oldest = txn->mt_txnid - 1;
1897 if (txn->mt_env->me_txns) {
1898 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1899 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1910 /** Add a page to the txn's dirty list */
1912 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1915 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
1917 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1918 insert = mdb_mid2l_append;
1920 insert = mdb_mid2l_insert;
1922 mid.mid = mp->mp_pgno;
1924 rc = insert(txn->mt_u.dirty_list, &mid);
1925 mdb_tassert(txn, rc == 0);
1926 txn->mt_dirty_room--;
1929 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1930 * me_pghead and mt_next_pgno.
1932 * If there are free pages available from older transactions, they
1933 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1934 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1935 * and move me_pglast to say which records were consumed. Only this
1936 * function can create me_pghead and move me_pglast/mt_next_pgno.
1937 * @param[in] mc cursor A cursor handle identifying the transaction and
1938 * database for which we are allocating.
1939 * @param[in] num the number of pages to allocate.
1940 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1941 * will always be satisfied by a single contiguous chunk of memory.
1942 * @return 0 on success, non-zero on failure.
1945 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1947 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1948 /* Get at most <Max_retries> more freeDB records once me_pghead
1949 * has enough pages. If not enough, use new pages from the map.
1950 * If <Paranoid> and mc is updating the freeDB, only get new
1951 * records if me_pghead is empty. Then the freelist cannot play
1952 * catch-up with itself by growing while trying to save it.
1954 enum { Paranoid = 1, Max_retries = 500 };
1956 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1958 int rc, retry = num * 60;
1959 MDB_txn *txn = mc->mc_txn;
1960 MDB_env *env = txn->mt_env;
1961 pgno_t pgno, *mop = env->me_pghead;
1962 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
1964 txnid_t oldest = 0, last;
1969 /* If there are any loose pages, just use them */
1970 if (num == 1 && txn->mt_loose_pgs) {
1971 np = txn->mt_loose_pgs;
1972 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
1973 txn->mt_loose_count--;
1974 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
1982 /* If our dirty list is already full, we can't do anything */
1983 if (txn->mt_dirty_room == 0) {
1988 for (op = MDB_FIRST;; op = MDB_NEXT) {
1993 /* Seek a big enough contiguous page range. Prefer
1994 * pages at the tail, just truncating the list.
2000 if (mop[i-n2] == pgno+n2)
2007 if (op == MDB_FIRST) { /* 1st iteration */
2008 /* Prepare to fetch more and coalesce */
2009 last = env->me_pglast;
2010 oldest = env->me_pgoldest;
2011 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2014 key.mv_data = &last; /* will look up last+1 */
2015 key.mv_size = sizeof(last);
2017 if (Paranoid && mc->mc_dbi == FREE_DBI)
2020 if (Paranoid && retry < 0 && mop_len)
2024 /* Do not fetch more if the record will be too recent */
2025 if (oldest <= last) {
2027 oldest = mdb_find_oldest(txn);
2028 env->me_pgoldest = oldest;
2034 rc = mdb_cursor_get(&m2, &key, NULL, op);
2036 if (rc == MDB_NOTFOUND)
2040 last = *(txnid_t*)key.mv_data;
2041 if (oldest <= last) {
2043 oldest = mdb_find_oldest(txn);
2044 env->me_pgoldest = oldest;
2050 np = m2.mc_pg[m2.mc_top];
2051 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2052 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
2055 idl = (MDB_ID *) data.mv_data;
2058 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2063 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2065 mop = env->me_pghead;
2067 env->me_pglast = last;
2069 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2070 last, txn->mt_dbs[FREE_DBI].md_root, i));
2072 DPRINTF(("IDL %"Z"u", idl[j]));
2074 /* Merge in descending sorted order */
2075 mdb_midl_xmerge(mop, idl);
2079 /* Use new pages from the map when nothing suitable in the freeDB */
2081 pgno = txn->mt_next_pgno;
2082 if (pgno + num >= env->me_maxpg) {
2083 DPUTS("DB size maxed out");
2089 if (env->me_flags & MDB_WRITEMAP) {
2090 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2092 if (!(np = mdb_page_malloc(txn, num))) {
2098 mop[0] = mop_len -= num;
2099 /* Move any stragglers down */
2100 for (j = i-num; j < mop_len; )
2101 mop[++j] = mop[++i];
2103 txn->mt_next_pgno = pgno + num;
2106 mdb_page_dirty(txn, np);
2112 txn->mt_flags |= MDB_TXN_ERROR;
2116 /** Copy the used portions of a non-overflow page.
2117 * @param[in] dst page to copy into
2118 * @param[in] src page to copy from
2119 * @param[in] psize size of a page
2122 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2124 enum { Align = sizeof(pgno_t) };
2125 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2127 /* If page isn't full, just copy the used portion. Adjust
2128 * alignment so memcpy may copy words instead of bytes.
2130 if ((unused &= -Align) && !IS_LEAF2(src)) {
2131 upper = (upper + PAGEBASE) & -Align;
2132 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2133 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2136 memcpy(dst, src, psize - unused);
2140 /** Pull a page off the txn's spill list, if present.
2141 * If a page being referenced was spilled to disk in this txn, bring
2142 * it back and make it dirty/writable again.
2143 * @param[in] txn the transaction handle.
2144 * @param[in] mp the page being referenced. It must not be dirty.
2145 * @param[out] ret the writable page, if any. ret is unchanged if
2146 * mp wasn't spilled.
2149 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2151 MDB_env *env = txn->mt_env;
2154 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2156 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2157 if (!tx2->mt_spill_pgs)
2159 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2160 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2163 if (txn->mt_dirty_room == 0)
2164 return MDB_TXN_FULL;
2165 if (IS_OVERFLOW(mp))
2169 if (env->me_flags & MDB_WRITEMAP) {
2172 np = mdb_page_malloc(txn, num);
2176 memcpy(np, mp, num * env->me_psize);
2178 mdb_page_copy(np, mp, env->me_psize);
2181 /* If in current txn, this page is no longer spilled.
2182 * If it happens to be the last page, truncate the spill list.
2183 * Otherwise mark it as deleted by setting the LSB.
2185 if (x == txn->mt_spill_pgs[0])
2186 txn->mt_spill_pgs[0]--;
2188 txn->mt_spill_pgs[x] |= 1;
2189 } /* otherwise, if belonging to a parent txn, the
2190 * page remains spilled until child commits
2193 mdb_page_dirty(txn, np);
2194 np->mp_flags |= P_DIRTY;
2202 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2203 * @param[in] mc cursor pointing to the page to be touched
2204 * @return 0 on success, non-zero on failure.
2207 mdb_page_touch(MDB_cursor *mc)
2209 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2210 MDB_txn *txn = mc->mc_txn;
2211 MDB_cursor *m2, *m3;
2215 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2216 if (txn->mt_flags & MDB_TXN_SPILLS) {
2218 rc = mdb_page_unspill(txn, mp, &np);
2224 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2225 (rc = mdb_page_alloc(mc, 1, &np)))
2228 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2229 mp->mp_pgno, pgno));
2230 mdb_cassert(mc, mp->mp_pgno != pgno);
2231 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2232 /* Update the parent page, if any, to point to the new page */
2234 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2235 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2236 SETPGNO(node, pgno);
2238 mc->mc_db->md_root = pgno;
2240 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2241 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2243 /* If txn has a parent, make sure the page is in our
2247 unsigned x = mdb_mid2l_search(dl, pgno);
2248 if (x <= dl[0].mid && dl[x].mid == pgno) {
2249 if (mp != dl[x].mptr) { /* bad cursor? */
2250 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2251 txn->mt_flags |= MDB_TXN_ERROR;
2252 return MDB_CORRUPTED;
2257 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2259 np = mdb_page_malloc(txn, 1);
2264 rc = mdb_mid2l_insert(dl, &mid);
2265 mdb_cassert(mc, rc == 0);
2270 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2272 np->mp_flags |= P_DIRTY;
2275 /* Adjust cursors pointing to mp */
2276 mc->mc_pg[mc->mc_top] = np;
2277 m2 = txn->mt_cursors[mc->mc_dbi];
2278 if (mc->mc_flags & C_SUB) {
2279 for (; m2; m2=m2->mc_next) {
2280 m3 = &m2->mc_xcursor->mx_cursor;
2281 if (m3->mc_snum < mc->mc_snum) continue;
2282 if (m3->mc_pg[mc->mc_top] == mp)
2283 m3->mc_pg[mc->mc_top] = np;
2286 for (; m2; m2=m2->mc_next) {
2287 if (m2->mc_snum < mc->mc_snum) continue;
2288 if (m2->mc_pg[mc->mc_top] == mp) {
2289 m2->mc_pg[mc->mc_top] = np;
2290 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2292 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2294 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2295 if (!(leaf->mn_flags & F_SUBDATA))
2296 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2303 MDB_ID2L rl = mc->mc_txn->mt_rpages;
2304 unsigned x = mdb_mid2l_search(rl, mp->mp_pgno);
2305 if (x <= rl[0].mid && rl[x].mid == mp->mp_pgno) {
2306 munmap(mp, mc->mc_txn->mt_env->me_psize);
2307 while (x < rl[0].mid) {
2318 txn->mt_flags |= MDB_TXN_ERROR;
2323 mdb_env_sync(MDB_env *env, int force)
2326 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2327 if (env->me_flags & MDB_WRITEMAP) {
2328 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2329 ? MS_ASYNC : MS_SYNC;
2330 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2333 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2337 if (MDB_FDATASYNC(env->me_fd))
2344 /** Back up parent txn's cursors, then grab the originals for tracking */
2346 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2348 MDB_cursor *mc, *bk;
2353 for (i = src->mt_numdbs; --i >= 0; ) {
2354 if ((mc = src->mt_cursors[i]) != NULL) {
2355 size = sizeof(MDB_cursor);
2357 size += sizeof(MDB_xcursor);
2358 for (; mc; mc = bk->mc_next) {
2364 mc->mc_db = &dst->mt_dbs[i];
2365 /* Kill pointers into src - and dst to reduce abuse: The
2366 * user may not use mc until dst ends. Otherwise we'd...
2368 mc->mc_txn = NULL; /* ...set this to dst */
2369 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2370 if ((mx = mc->mc_xcursor) != NULL) {
2371 *(MDB_xcursor *)(bk+1) = *mx;
2372 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2374 mc->mc_next = dst->mt_cursors[i];
2375 dst->mt_cursors[i] = mc;
2382 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2383 * @param[in] txn the transaction handle.
2384 * @param[in] merge true to keep changes to parent cursors, false to revert.
2385 * @return 0 on success, non-zero on failure.
2388 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2390 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2394 for (i = txn->mt_numdbs; --i >= 0; ) {
2395 for (mc = cursors[i]; mc; mc = next) {
2397 if ((bk = mc->mc_backup) != NULL) {
2399 /* Commit changes to parent txn */
2400 mc->mc_next = bk->mc_next;
2401 mc->mc_backup = bk->mc_backup;
2402 mc->mc_txn = bk->mc_txn;
2403 mc->mc_db = bk->mc_db;
2404 mc->mc_dbflag = bk->mc_dbflag;
2405 if ((mx = mc->mc_xcursor) != NULL)
2406 mx->mx_cursor.mc_txn = bk->mc_txn;
2408 /* Abort nested txn */
2410 if ((mx = mc->mc_xcursor) != NULL)
2411 *mx = *(MDB_xcursor *)(bk+1);
2415 /* Only malloced cursors are permanently tracked. */
2423 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2426 mdb_txn_reset0(MDB_txn *txn, const char *act);
2428 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2434 Pidset = F_SETLK, Pidcheck = F_GETLK
2438 /** Set or check a pid lock. Set returns 0 on success.
2439 * Check returns 0 if the process is certainly dead, nonzero if it may
2440 * be alive (the lock exists or an error happened so we do not know).
2442 * On Windows Pidset is a no-op, we merely check for the existence
2443 * of the process with the given pid. On POSIX we use a single byte
2444 * lock on the lockfile, set at an offset equal to the pid.
2447 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2449 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2452 if (op == Pidcheck) {
2453 h = OpenProcess(env->me_pidquery, FALSE, pid);
2454 /* No documented "no such process" code, but other program use this: */
2456 return ErrCode() != ERROR_INVALID_PARAMETER;
2457 /* A process exists until all handles to it close. Has it exited? */
2458 ret = WaitForSingleObject(h, 0) != 0;
2465 struct flock lock_info;
2466 memset(&lock_info, 0, sizeof(lock_info));
2467 lock_info.l_type = F_WRLCK;
2468 lock_info.l_whence = SEEK_SET;
2469 lock_info.l_start = pid;
2470 lock_info.l_len = 1;
2471 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2472 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2474 } else if ((rc = ErrCode()) == EINTR) {
2482 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2483 * @param[in] txn the transaction handle to initialize
2484 * @return 0 on success, non-zero on failure.
2487 mdb_txn_renew0(MDB_txn *txn)
2489 MDB_env *env = txn->mt_env;
2490 MDB_txninfo *ti = env->me_txns;
2494 int rc, new_notls = 0;
2497 txn->mt_numdbs = env->me_numdbs;
2498 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2500 if (txn->mt_flags & MDB_TXN_RDONLY) {
2502 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2503 txn->mt_txnid = meta->mm_txnid;
2504 txn->mt_u.reader = NULL;
2506 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2507 pthread_getspecific(env->me_txkey);
2509 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2510 return MDB_BAD_RSLOT;
2512 MDB_PID_T pid = env->me_pid;
2513 MDB_THR_T tid = pthread_self();
2515 if (!env->me_live_reader) {
2516 rc = mdb_reader_pid(env, Pidset, pid);
2519 env->me_live_reader = 1;
2523 nr = ti->mti_numreaders;
2524 for (i=0; i<nr; i++)
2525 if (ti->mti_readers[i].mr_pid == 0)
2527 if (i == env->me_maxreaders) {
2528 UNLOCK_MUTEX_R(env);
2529 return MDB_READERS_FULL;
2531 ti->mti_readers[i].mr_pid = pid;
2532 ti->mti_readers[i].mr_tid = tid;
2534 ti->mti_numreaders = ++nr;
2535 /* Save numreaders for un-mutexed mdb_env_close() */
2536 env->me_numreaders = nr;
2537 UNLOCK_MUTEX_R(env);
2539 r = &ti->mti_readers[i];
2540 new_notls = (env->me_flags & MDB_NOTLS);
2541 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2546 txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
2547 txn->mt_u.reader = r;
2548 meta = env->me_metas[txn->mt_txnid & 1];
2554 txn->mt_txnid = ti->mti_txnid;
2555 meta = env->me_metas[txn->mt_txnid & 1];
2557 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2558 txn->mt_txnid = meta->mm_txnid;
2562 if (txn->mt_txnid == mdb_debug_start)
2565 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2566 txn->mt_u.dirty_list = env->me_dirty_list;
2567 txn->mt_u.dirty_list[0].mid = 0;
2568 txn->mt_free_pgs = env->me_free_pgs;
2569 txn->mt_free_pgs[0] = 0;
2570 txn->mt_spill_pgs = NULL;
2572 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2575 /* Copy the DB info and flags */
2576 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2578 /* Moved to here to avoid a data race in read TXNs */
2579 txn->mt_next_pgno = meta->mm_last_pg+1;
2581 for (i=2; i<txn->mt_numdbs; i++) {
2582 x = env->me_dbflags[i];
2583 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2584 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2586 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2588 if (env->me_maxpg < txn->mt_next_pgno) {
2589 mdb_txn_reset0(txn, "renew0-mapfail");
2591 txn->mt_u.reader->mr_pid = 0;
2592 txn->mt_u.reader = NULL;
2594 return MDB_MAP_RESIZED;
2601 mdb_txn_renew(MDB_txn *txn)
2605 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2608 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2609 DPUTS("environment had fatal error, must shutdown!");
2613 rc = mdb_txn_renew0(txn);
2614 if (rc == MDB_SUCCESS) {
2615 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2616 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2617 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2623 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2627 int rc, size, tsize = sizeof(MDB_txn);
2629 if (env->me_flags & MDB_FATAL_ERROR) {
2630 DPUTS("environment had fatal error, must shutdown!");
2633 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2636 /* Nested transactions: Max 1 child, write txns only, no writemap */
2637 if (parent->mt_child ||
2638 (flags & MDB_RDONLY) ||
2639 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2640 (env->me_flags & MDB_WRITEMAP))
2642 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2644 tsize = sizeof(MDB_ntxn);
2646 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2647 if (!(flags & MDB_RDONLY)) {
2653 size += env->me_maxdbs * sizeof(MDB_cursor *);
2654 /* child txns use parent's dbiseqs */
2656 size += env->me_maxdbs * sizeof(unsigned int);
2659 if ((txn = calloc(1, size)) == NULL) {
2660 DPRINTF(("calloc: %s", strerror(errno)));
2665 txn->mt_rpages = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2));
2666 if (!txn->mt_rpages) {
2672 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2673 if (flags & MDB_RDONLY) {
2674 txn->mt_flags |= MDB_TXN_RDONLY;
2675 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2676 txn->mt_dbiseqs = env->me_dbiseqs;
2678 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2680 txn->mt_dbiseqs = parent->mt_dbiseqs;
2681 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2683 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
2684 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
2692 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2693 if (!txn->mt_u.dirty_list ||
2694 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2696 free(txn->mt_u.dirty_list);
2700 txn->mt_txnid = parent->mt_txnid;
2701 txn->mt_dirty_room = parent->mt_dirty_room;
2702 txn->mt_u.dirty_list[0].mid = 0;
2703 txn->mt_spill_pgs = NULL;
2704 txn->mt_next_pgno = parent->mt_next_pgno;
2705 parent->mt_child = txn;
2706 txn->mt_parent = parent;
2707 txn->mt_numdbs = parent->mt_numdbs;
2708 txn->mt_flags = parent->mt_flags;
2709 txn->mt_dbxs = parent->mt_dbxs;
2711 txn->mt_rpages = parent->mt_rpages;
2713 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2714 /* Copy parent's mt_dbflags, but clear DB_NEW */
2715 for (i=0; i<txn->mt_numdbs; i++)
2716 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2718 ntxn = (MDB_ntxn *)txn;
2719 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2720 if (env->me_pghead) {
2721 size = MDB_IDL_SIZEOF(env->me_pghead);
2722 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2724 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2729 rc = mdb_cursor_shadow(parent, txn);
2731 mdb_txn_reset0(txn, "beginchild-fail");
2733 rc = mdb_txn_renew0(txn);
2736 if (txn != env->me_txn0)
2740 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2741 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2742 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2749 mdb_txn_env(MDB_txn *txn)
2751 if(!txn) return NULL;
2755 /** Export or close DBI handles opened in this txn. */
2757 mdb_dbis_update(MDB_txn *txn, int keep)
2760 MDB_dbi n = txn->mt_numdbs;
2761 MDB_env *env = txn->mt_env;
2762 unsigned char *tdbflags = txn->mt_dbflags;
2764 for (i = n; --i >= 2;) {
2765 if (tdbflags[i] & DB_NEW) {
2767 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2769 char *ptr = env->me_dbxs[i].md_name.mv_data;
2771 env->me_dbxs[i].md_name.mv_data = NULL;
2772 env->me_dbxs[i].md_name.mv_size = 0;
2773 env->me_dbflags[i] = 0;
2774 env->me_dbiseqs[i]++;
2780 if (keep && env->me_numdbs < n)
2784 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2785 * May be called twice for readonly txns: First reset it, then abort.
2786 * @param[in] txn the transaction handle to reset
2787 * @param[in] act why the transaction is being reset
2790 mdb_txn_reset0(MDB_txn *txn, const char *act)
2792 MDB_env *env = txn->mt_env;
2794 /* Close any DBI handles opened in this txn */
2795 mdb_dbis_update(txn, 0);
2797 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2798 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2799 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2801 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2802 if (txn->mt_u.reader) {
2803 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2804 if (!(env->me_flags & MDB_NOTLS))
2805 txn->mt_u.reader = NULL; /* txn does not own reader */
2807 txn->mt_numdbs = 0; /* close nothing if called again */
2808 txn->mt_dbxs = NULL; /* mark txn as reset */
2810 mdb_cursors_close(txn, 0);
2812 if (!(env->me_flags & MDB_WRITEMAP)) {
2813 mdb_dlist_free(txn);
2815 mdb_midl_free(env->me_pghead);
2817 if (txn->mt_parent) {
2818 txn->mt_parent->mt_child = NULL;
2819 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2820 mdb_midl_free(txn->mt_free_pgs);
2821 mdb_midl_free(txn->mt_spill_pgs);
2822 free(txn->mt_u.dirty_list);
2826 if (mdb_midl_shrink(&txn->mt_free_pgs))
2827 env->me_free_pgs = txn->mt_free_pgs;
2828 env->me_pghead = NULL;
2832 /* The writer mutex was locked in mdb_txn_begin. */
2834 UNLOCK_MUTEX_W(env);
2838 unsigned i, n = txn->mt_rpages[0].mid;
2839 for (i = 1; i <= n; i++) {
2841 UnmapViewOfFile(txn->mt_rpages[i].mptr);
2843 MDB_page *mp = txn->mt_rpages[i].mptr;
2844 int size = txn->mt_env->me_psize;
2845 if (IS_OVERFLOW(mp)) size *= mp->mp_pages;
2850 txn->mt_rpages[0].mid = 0;
2855 mdb_txn_reset(MDB_txn *txn)
2860 /* This call is only valid for read-only txns */
2861 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2864 mdb_txn_reset0(txn, "reset");
2868 mdb_txn_abort(MDB_txn *txn)
2874 mdb_txn_abort(txn->mt_child);
2876 mdb_txn_reset0(txn, "abort");
2877 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2878 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2879 txn->mt_u.reader->mr_pid = 0;
2881 if (txn != txn->mt_env->me_txn0) {
2883 free(txn->mt_rpages);
2889 /** Save the freelist as of this transaction to the freeDB.
2890 * This changes the freelist. Keep trying until it stabilizes.
2893 mdb_freelist_save(MDB_txn *txn)
2895 /* env->me_pghead[] can grow and shrink during this call.
2896 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2897 * Page numbers cannot disappear from txn->mt_free_pgs[].
2900 MDB_env *env = txn->mt_env;
2901 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2902 txnid_t pglast = 0, head_id = 0;
2903 pgno_t freecnt = 0, *free_pgs, *mop;
2904 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2906 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2908 if (env->me_pghead) {
2909 /* Make sure first page of freeDB is touched and on freelist */
2910 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2911 if (rc && rc != MDB_NOTFOUND)
2915 if (!env->me_pghead && txn->mt_loose_pgs) {
2916 /* Put loose page numbers in mt_free_pgs, since
2917 * we may be unable to return them to me_pghead.
2919 MDB_page *mp = txn->mt_loose_pgs;
2920 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
2922 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
2923 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2924 txn->mt_loose_pgs = NULL;
2925 txn->mt_loose_count = 0;
2928 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2929 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2930 ? SSIZE_MAX : maxfree_1pg;
2933 /* Come back here after each Put() in case freelist changed */
2938 /* If using records from freeDB which we have not yet
2939 * deleted, delete them and any we reserved for me_pghead.
2941 while (pglast < env->me_pglast) {
2942 rc = mdb_cursor_first(&mc, &key, NULL);
2945 pglast = head_id = *(txnid_t *)key.mv_data;
2946 total_room = head_room = 0;
2947 mdb_tassert(txn, pglast <= env->me_pglast);
2948 rc = mdb_cursor_del(&mc, 0);
2953 /* Save the IDL of pages freed by this txn, to a single record */
2954 if (freecnt < txn->mt_free_pgs[0]) {
2956 /* Make sure last page of freeDB is touched and on freelist */
2957 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2958 if (rc && rc != MDB_NOTFOUND)
2961 free_pgs = txn->mt_free_pgs;
2962 /* Write to last page of freeDB */
2963 key.mv_size = sizeof(txn->mt_txnid);
2964 key.mv_data = &txn->mt_txnid;
2966 freecnt = free_pgs[0];
2967 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2968 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2971 /* Retry if mt_free_pgs[] grew during the Put() */
2972 free_pgs = txn->mt_free_pgs;
2973 } while (freecnt < free_pgs[0]);
2974 mdb_midl_sort(free_pgs);
2975 memcpy(data.mv_data, free_pgs, data.mv_size);
2978 unsigned int i = free_pgs[0];
2979 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2980 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2982 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2988 mop = env->me_pghead;
2989 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
2991 /* Reserve records for me_pghead[]. Split it if multi-page,
2992 * to avoid searching freeDB for a page range. Use keys in
2993 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2995 if (total_room >= mop_len) {
2996 if (total_room == mop_len || --more < 0)
2998 } else if (head_room >= maxfree_1pg && head_id > 1) {
2999 /* Keep current record (overflow page), add a new one */
3003 /* (Re)write {key = head_id, IDL length = head_room} */
3004 total_room -= head_room;
3005 head_room = mop_len - total_room;
3006 if (head_room > maxfree_1pg && head_id > 1) {
3007 /* Overflow multi-page for part of me_pghead */
3008 head_room /= head_id; /* amortize page sizes */
3009 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3010 } else if (head_room < 0) {
3011 /* Rare case, not bothering to delete this record */
3014 key.mv_size = sizeof(head_id);
3015 key.mv_data = &head_id;
3016 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3017 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3020 /* IDL is initially empty, zero out at least the length */
3021 pgs = (pgno_t *)data.mv_data;
3022 j = head_room > clean_limit ? head_room : 0;
3026 total_room += head_room;
3029 /* Return loose page numbers to me_pghead, though usually none are
3030 * left at this point. The pages themselves remain in dirty_list.
3032 if (txn->mt_loose_pgs) {
3033 MDB_page *mp = txn->mt_loose_pgs;
3034 unsigned count = txn->mt_loose_count;
3036 /* Room for loose pages + temp IDL with same */
3037 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3039 mop = env->me_pghead;
3040 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3041 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3042 loose[ ++count ] = mp->mp_pgno;
3044 mdb_midl_sort(loose);
3045 mdb_midl_xmerge(mop, loose);
3046 txn->mt_loose_pgs = NULL;
3047 txn->mt_loose_count = 0;
3051 /* Fill in the reserved me_pghead records */
3057 rc = mdb_cursor_first(&mc, &key, &data);
3058 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3059 txnid_t id = *(txnid_t *)key.mv_data;
3060 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3063 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3065 if (len > mop_len) {
3067 data.mv_size = (len + 1) * sizeof(MDB_ID);
3069 data.mv_data = mop -= len;
3072 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3074 if (rc || !(mop_len -= len))
3081 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3082 * @param[in] txn the transaction that's being committed
3083 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3084 * @return 0 on success, non-zero on failure.
3087 mdb_page_flush(MDB_txn *txn, int keep)
3089 MDB_env *env = txn->mt_env;
3090 MDB_ID2L dl = txn->mt_u.dirty_list;
3091 unsigned psize = env->me_psize, j;
3092 int i, pagecount = dl[0].mid, rc;
3093 size_t size = 0, pos = 0;
3095 MDB_page *dp = NULL;
3099 struct iovec iov[MDB_COMMIT_PAGES];
3100 ssize_t wpos = 0, wsize = 0, wres;
3101 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3107 if (env->me_flags & MDB_WRITEMAP) {
3108 /* Clear dirty flags */
3109 while (++i <= pagecount) {
3111 /* Don't flush this page yet */
3112 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3113 dp->mp_flags &= ~P_KEEP;
3117 dp->mp_flags &= ~P_DIRTY;
3122 /* Write the pages */
3124 if (++i <= pagecount) {
3126 /* Don't flush this page yet */
3127 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3128 dp->mp_flags &= ~P_KEEP;
3133 /* clear dirty flag */
3134 dp->mp_flags &= ~P_DIRTY;
3137 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3142 /* Windows actually supports scatter/gather I/O, but only on
3143 * unbuffered file handles. Since we're relying on the OS page
3144 * cache for all our data, that's self-defeating. So we just
3145 * write pages one at a time. We use the ov structure to set
3146 * the write offset, to at least save the overhead of a Seek
3149 DPRINTF(("committing page %"Z"u", pgno));
3150 memset(&ov, 0, sizeof(ov));
3151 ov.Offset = pos & 0xffffffff;
3152 ov.OffsetHigh = pos >> 16 >> 16;
3153 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3155 DPRINTF(("WriteFile: %d", rc));
3159 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3160 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3162 /* Write previous page(s) */
3163 #ifdef MDB_USE_PWRITEV
3164 wres = pwritev(env->me_fd, iov, n, wpos);
3167 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3169 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3171 DPRINTF(("lseek: %s", strerror(rc)));
3174 wres = writev(env->me_fd, iov, n);
3177 if (wres != wsize) {
3180 DPRINTF(("Write error: %s", strerror(rc)));
3182 rc = EIO; /* TODO: Use which error code? */
3183 DPUTS("short write, filesystem full?");
3194 DPRINTF(("committing page %"Z"u", pgno));
3195 next_pos = pos + size;
3196 iov[n].iov_len = size;
3197 iov[n].iov_base = (char *)dp;
3203 /* MIPS has cache coherency issues, this is a no-op everywhere else
3204 * Note: for any size >= on-chip cache size, entire on-chip cache is
3207 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3209 for (i = keep; ++i <= pagecount; ) {
3211 /* This is a page we skipped above */
3214 dl[j].mid = dp->mp_pgno;
3217 mdb_dpage_free(env, dp);
3222 txn->mt_dirty_room += i - j;
3228 mdb_txn_commit(MDB_txn *txn)
3234 if (txn == NULL || txn->mt_env == NULL)
3237 if (txn->mt_child) {
3238 rc = mdb_txn_commit(txn->mt_child);
3239 txn->mt_child = NULL;
3246 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3247 mdb_dbis_update(txn, 1);
3248 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
3253 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
3254 DPUTS("error flag is set, can't commit");
3256 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3261 if (txn->mt_parent) {
3262 MDB_txn *parent = txn->mt_parent;
3266 unsigned x, y, len, ps_len;
3268 /* Append our free list to parent's */
3269 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3272 mdb_midl_free(txn->mt_free_pgs);
3273 /* Failures after this must either undo the changes
3274 * to the parent or set MDB_TXN_ERROR in the parent.
3277 parent->mt_next_pgno = txn->mt_next_pgno;
3278 parent->mt_flags = txn->mt_flags;
3280 /* Merge our cursors into parent's and close them */
3281 mdb_cursors_close(txn, 1);
3283 /* Update parent's DB table. */
3284 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3285 parent->mt_numdbs = txn->mt_numdbs;
3286 parent->mt_dbflags[0] = txn->mt_dbflags[0];
3287 parent->mt_dbflags[1] = txn->mt_dbflags[1];
3288 for (i=2; i<txn->mt_numdbs; i++) {
3289 /* preserve parent's DB_NEW status */
3290 x = parent->mt_dbflags[i] & DB_NEW;
3291 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3294 dst = parent->mt_u.dirty_list;
3295 src = txn->mt_u.dirty_list;
3296 /* Remove anything in our dirty list from parent's spill list */
3297 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3299 pspill[0] = (pgno_t)-1;
3300 /* Mark our dirty pages as deleted in parent spill list */
3301 for (i=0, len=src[0].mid; ++i <= len; ) {
3302 MDB_ID pn = src[i].mid << 1;
3303 while (pn > pspill[x])
3305 if (pn == pspill[x]) {
3310 /* Squash deleted pagenums if we deleted any */
3311 for (x=y; ++x <= ps_len; )
3312 if (!(pspill[x] & 1))
3313 pspill[++y] = pspill[x];
3317 /* Find len = length of merging our dirty list with parent's */
3319 dst[0].mid = 0; /* simplify loops */
3320 if (parent->mt_parent) {
3321 len = x + src[0].mid;
3322 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3323 for (i = x; y && i; y--) {
3324 pgno_t yp = src[y].mid;
3325 while (yp < dst[i].mid)
3327 if (yp == dst[i].mid) {
3332 } else { /* Simplify the above for single-ancestor case */
3333 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3335 /* Merge our dirty list with parent's */
3337 for (i = len; y; dst[i--] = src[y--]) {
3338 pgno_t yp = src[y].mid;
3339 while (yp < dst[x].mid)
3340 dst[i--] = dst[x--];
3341 if (yp == dst[x].mid)
3342 free(dst[x--].mptr);
3344 mdb_tassert(txn, i == x);
3346 free(txn->mt_u.dirty_list);
3347 parent->mt_dirty_room = txn->mt_dirty_room;
3348 if (txn->mt_spill_pgs) {
3349 if (parent->mt_spill_pgs) {
3350 /* TODO: Prevent failure here, so parent does not fail */
3351 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3353 parent->mt_flags |= MDB_TXN_ERROR;
3354 mdb_midl_free(txn->mt_spill_pgs);
3355 mdb_midl_sort(parent->mt_spill_pgs);
3357 parent->mt_spill_pgs = txn->mt_spill_pgs;
3361 /* Append our loose page list to parent's */
3362 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(lp))
3364 *lp = txn->mt_loose_pgs;
3365 parent->mt_loose_count += txn->mt_loose_count;
3367 parent->mt_child = NULL;
3368 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3373 if (txn != env->me_txn) {
3374 DPUTS("attempt to commit unknown transaction");
3379 mdb_cursors_close(txn, 0);
3381 if (!txn->mt_u.dirty_list[0].mid &&
3382 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3385 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3386 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3388 /* Update DB root pointers */
3389 if (txn->mt_numdbs > 2) {
3393 data.mv_size = sizeof(MDB_db);
3395 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3396 for (i = 2; i < txn->mt_numdbs; i++) {
3397 if (txn->mt_dbflags[i] & DB_DIRTY) {
3398 if (TXN_DBI_CHANGED(txn, i)) {
3402 data.mv_data = &txn->mt_dbs[i];
3403 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
3410 rc = mdb_freelist_save(txn);
3414 mdb_midl_free(env->me_pghead);
3415 env->me_pghead = NULL;
3416 if (mdb_midl_shrink(&txn->mt_free_pgs))
3417 env->me_free_pgs = txn->mt_free_pgs;
3423 if ((rc = mdb_page_flush(txn, 0)) ||
3424 (rc = mdb_env_sync(env, 0)) ||
3425 (rc = mdb_env_write_meta(txn)))
3428 /* Free P_LOOSE pages left behind in dirty_list */
3429 if (!(env->me_flags & MDB_WRITEMAP))
3430 mdb_dlist_free(txn);
3435 mdb_dbis_update(txn, 1);
3438 UNLOCK_MUTEX_W(env);
3439 if (txn != env->me_txn0)
3449 /** Read the environment parameters of a DB environment before
3450 * mapping it into memory.
3451 * @param[in] env the environment handle
3452 * @param[out] meta address of where to store the meta information
3453 * @return 0 on success, non-zero on failure.
3456 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3462 enum { Size = sizeof(pbuf) };
3464 /* We don't know the page size yet, so use a minimum value.
3465 * Read both meta pages so we can use the latest one.
3468 for (i=off=0; i<2; i++, off = meta->mm_psize) {
3472 memset(&ov, 0, sizeof(ov));
3474 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3475 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3478 rc = pread(env->me_fd, &pbuf, Size, off);
3481 if (rc == 0 && off == 0)
3483 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3484 DPRINTF(("read: %s", mdb_strerror(rc)));
3488 p = (MDB_page *)&pbuf;
3490 if (!F_ISSET(p->mp_flags, P_META)) {
3491 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3496 if (m->mm_magic != MDB_MAGIC) {
3497 DPUTS("meta has invalid magic");
3501 if (m->mm_version != MDB_DATA_VERSION) {
3502 DPRINTF(("database is version %u, expected version %u",
3503 m->mm_version, MDB_DATA_VERSION));
3504 return MDB_VERSION_MISMATCH;
3507 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3514 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3516 meta->mm_magic = MDB_MAGIC;
3517 meta->mm_version = MDB_DATA_VERSION;
3518 meta->mm_mapsize = env->me_mapsize;
3519 meta->mm_psize = env->me_psize;
3520 meta->mm_last_pg = 1;
3521 meta->mm_flags = env->me_flags & 0xffff;
3522 meta->mm_flags |= MDB_INTEGERKEY;
3523 meta->mm_dbs[0].md_root = P_INVALID;
3524 meta->mm_dbs[1].md_root = P_INVALID;
3527 /** Write the environment parameters of a freshly created DB environment.
3528 * @param[in] env the environment handle
3529 * @param[out] meta address of where to store the meta information
3530 * @return 0 on success, non-zero on failure.
3533 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3541 memset(&ov, 0, sizeof(ov));
3542 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3544 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3547 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3548 len = pwrite(fd, ptr, size, pos); \
3549 rc = (len >= 0); } while(0)
3552 DPUTS("writing new meta page");
3554 psize = env->me_psize;
3556 mdb_env_init_meta0(env, meta);
3558 p = calloc(2, psize);
3560 p->mp_flags = P_META;
3561 *(MDB_meta *)METADATA(p) = *meta;
3563 q = (MDB_page *)((char *)p + psize);
3565 q->mp_flags = P_META;
3566 *(MDB_meta *)METADATA(q) = *meta;
3568 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3571 else if ((unsigned) len == psize * 2)
3579 /** Update the environment info to commit a transaction.
3580 * @param[in] txn the transaction that's being committed
3581 * @return 0 on success, non-zero on failure.
3584 mdb_env_write_meta(MDB_txn *txn)
3587 MDB_meta meta, metab, *mp;
3590 int rc, len, toggle;
3599 toggle = txn->mt_txnid & 1;
3600 DPRINTF(("writing meta page %d for root page %"Z"u",
3601 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3604 mp = env->me_metas[toggle];
3605 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3606 /* Persist any increases of mapsize config */
3607 if (mapsize < env->me_mapsize)
3608 mapsize = env->me_mapsize;
3610 if (env->me_flags & MDB_WRITEMAP) {
3611 mp->mm_mapsize = mapsize;
3612 mp->mm_dbs[0] = txn->mt_dbs[0];
3613 mp->mm_dbs[1] = txn->mt_dbs[1];
3614 mp->mm_last_pg = txn->mt_next_pgno - 1;
3615 mp->mm_txnid = txn->mt_txnid;
3616 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3617 unsigned meta_size = env->me_psize;
3618 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3621 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3622 if (meta_size < env->me_os_psize)
3623 meta_size += meta_size;
3628 if (MDB_MSYNC(ptr, meta_size, rc)) {
3635 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3636 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3638 meta.mm_mapsize = mapsize;
3639 meta.mm_dbs[0] = txn->mt_dbs[0];
3640 meta.mm_dbs[1] = txn->mt_dbs[1];
3641 meta.mm_last_pg = txn->mt_next_pgno - 1;
3642 meta.mm_txnid = txn->mt_txnid;
3644 off = offsetof(MDB_meta, mm_mapsize);
3645 ptr = (char *)&meta + off;
3646 len = sizeof(MDB_meta) - off;
3648 off += env->me_psize;
3651 /* Write to the SYNC fd */
3652 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3653 env->me_fd : env->me_mfd;
3656 memset(&ov, 0, sizeof(ov));
3658 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3662 rc = pwrite(mfd, ptr, len, off);
3665 rc = rc < 0 ? ErrCode() : EIO;
3666 DPUTS("write failed, disk error?");
3667 /* On a failure, the pagecache still contains the new data.
3668 * Write some old data back, to prevent it from being used.
3669 * Use the non-SYNC fd; we know it will fail anyway.
3671 meta.mm_last_pg = metab.mm_last_pg;
3672 meta.mm_txnid = metab.mm_txnid;
3674 memset(&ov, 0, sizeof(ov));
3676 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3678 r2 = pwrite(env->me_fd, ptr, len, off);
3679 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3682 env->me_flags |= MDB_FATAL_ERROR;
3685 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3686 CACHEFLUSH(env->me_map + off, len, DCACHE);
3688 /* Memory ordering issues are irrelevant; since the entire writer
3689 * is wrapped by wmutex, all of these changes will become visible
3690 * after the wmutex is unlocked. Since the DB is multi-version,
3691 * readers will get consistent data regardless of how fresh or
3692 * how stale their view of these values is.
3695 env->me_txns->mti_txnid = txn->mt_txnid;
3700 /** Check both meta pages to see which one is newer.
3701 * @param[in] env the environment handle
3702 * @return meta toggle (0 or 1).
3705 mdb_env_pick_meta(const MDB_env *env)
3707 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3711 mdb_env_create(MDB_env **env)
3715 e = calloc(1, sizeof(MDB_env));
3719 e->me_maxreaders = DEFAULT_READERS;
3720 e->me_maxdbs = e->me_numdbs = 2;
3721 e->me_fd = INVALID_HANDLE_VALUE;
3722 e->me_lfd = INVALID_HANDLE_VALUE;
3723 e->me_mfd = INVALID_HANDLE_VALUE;
3724 #ifdef MDB_USE_POSIX_SEM
3725 e->me_rmutex = SEM_FAILED;
3726 e->me_wmutex = SEM_FAILED;
3728 e->me_pid = getpid();
3729 GET_PAGESIZE(e->me_os_psize);
3730 VGMEMP_CREATE(e,0,0);
3736 mdb_env_map(MDB_env *env, void *addr)
3739 unsigned int flags = env->me_flags;
3743 LONG sizelo, sizehi;
3746 if (flags & MDB_RDONLY) {
3747 /* Don't set explicit map size, use whatever exists */
3752 msize = env->me_mapsize;
3753 sizelo = msize & 0xffffffff;
3754 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3756 /* Windows won't create mappings for zero length files.
3757 * and won't map more than the file size.
3758 * Just set the maxsize right now.
3760 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3761 || !SetEndOfFile(env->me_fd)
3762 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3766 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3767 PAGE_READWRITE : PAGE_READONLY,
3768 sizehi, sizelo, NULL);
3772 msize = 2 * env->me_psize;
3774 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3775 FILE_MAP_WRITE : FILE_MAP_READ,
3777 rc = env->me_map ? 0 : ErrCode();
3788 env->me_map = mmap(addr, 2 * env->me_psize, PROT_READ, MAP_SHARED,
3790 if (env->me_map == MAP_FAILED) {
3795 int prot = PROT_READ;
3796 if (flags & MDB_WRITEMAP) {
3798 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3801 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3803 if (env->me_map == MAP_FAILED) {
3808 if (flags & MDB_NORDAHEAD) {
3809 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3811 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3813 #ifdef POSIX_MADV_RANDOM
3814 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3815 #endif /* POSIX_MADV_RANDOM */
3816 #endif /* MADV_RANDOM */
3820 /* Can happen because the address argument to mmap() is just a
3821 * hint. mmap() can pick another, e.g. if the range is in use.
3822 * The MAP_FIXED flag would prevent that, but then mmap could
3823 * instead unmap existing pages to make room for the new map.
3825 if (addr && env->me_map != addr)
3826 return EBUSY; /* TODO: Make a new MDB_* error code? */
3829 p = (MDB_page *)env->me_map;
3830 env->me_metas[0] = METADATA(p);
3831 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3837 mdb_env_set_mapsize(MDB_env *env, size_t size)
3839 /* If env is already open, caller is responsible for making
3840 * sure there are no active txns.
3848 size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3849 else if (size < env->me_mapsize) {
3850 /* If the configured size is smaller, make sure it's
3851 * still big enough. Silently round up to minimum if not.
3853 size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3857 munmap(env->me_map, env->me_mapsize);
3858 env->me_mapsize = size;
3859 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3860 rc = mdb_env_map(env, old);
3864 env->me_mapsize = size;
3866 env->me_maxpg = env->me_mapsize / env->me_psize;
3871 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3875 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3880 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3882 if (env->me_map || readers < 1)
3884 env->me_maxreaders = readers;
3889 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3891 if (!env || !readers)
3893 *readers = env->me_maxreaders;
3897 /** Further setup required for opening an LMDB environment
3900 mdb_env_open2(MDB_env *env)
3902 unsigned int flags = env->me_flags;
3903 int i, newenv = 0, rc;
3907 /* See if we should use QueryLimited */
3909 if ((rc & 0xff) > 5)
3910 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3912 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3915 memset(&meta, 0, sizeof(meta));
3917 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3920 DPUTS("new mdbenv");
3922 env->me_psize = env->me_os_psize;
3923 if (env->me_psize > MAX_PAGESIZE)
3924 env->me_psize = MAX_PAGESIZE;
3926 env->me_psize = meta.mm_psize;
3929 /* Was a mapsize configured? */
3930 if (!env->me_mapsize) {
3931 /* If this is a new environment, take the default,
3932 * else use the size recorded in the existing env.
3934 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3935 } else if (env->me_mapsize < meta.mm_mapsize) {
3936 /* If the configured size is smaller, make sure it's
3937 * still big enough. Silently round up to minimum if not.
3939 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3940 if (env->me_mapsize < minsize)
3941 env->me_mapsize = minsize;
3944 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
3949 if (flags & MDB_FIXEDMAP)
3950 meta.mm_address = env->me_map;
3951 i = mdb_env_init_meta(env, &meta);
3952 if (i != MDB_SUCCESS) {
3957 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3958 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
3960 #if !(MDB_MAXKEYSIZE)
3961 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
3963 env->me_maxpg = env->me_mapsize / env->me_psize;
3967 int toggle = mdb_env_pick_meta(env);
3968 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3970 DPRINTF(("opened database version %u, pagesize %u",
3971 env->me_metas[0]->mm_version, env->me_psize));
3972 DPRINTF(("using meta page %d", toggle));
3973 DPRINTF(("depth: %u", db->md_depth));
3974 DPRINTF(("entries: %"Z"u", db->md_entries));
3975 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
3976 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
3977 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3978 DPRINTF(("root: %"Z"u", db->md_root));
3986 /** Release a reader thread's slot in the reader lock table.
3987 * This function is called automatically when a thread exits.
3988 * @param[in] ptr This points to the slot in the reader lock table.
3991 mdb_env_reader_dest(void *ptr)
3993 MDB_reader *reader = ptr;
3999 /** Junk for arranging thread-specific callbacks on Windows. This is
4000 * necessarily platform and compiler-specific. Windows supports up
4001 * to 1088 keys. Let's assume nobody opens more than 64 environments
4002 * in a single process, for now. They can override this if needed.
4004 #ifndef MAX_TLS_KEYS
4005 #define MAX_TLS_KEYS 64
4007 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4008 static int mdb_tls_nkeys;
4010 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4014 case DLL_PROCESS_ATTACH: break;
4015 case DLL_THREAD_ATTACH: break;
4016 case DLL_THREAD_DETACH:
4017 for (i=0; i<mdb_tls_nkeys; i++) {
4018 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4020 mdb_env_reader_dest(r);
4024 case DLL_PROCESS_DETACH: break;
4029 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4031 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4035 /* Force some symbol references.
4036 * _tls_used forces the linker to create the TLS directory if not already done
4037 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4039 #pragma comment(linker, "/INCLUDE:_tls_used")
4040 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4041 #pragma const_seg(".CRT$XLB")
4042 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4043 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4046 #pragma comment(linker, "/INCLUDE:__tls_used")
4047 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4048 #pragma data_seg(".CRT$XLB")
4049 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4051 #endif /* WIN 32/64 */
4052 #endif /* !__GNUC__ */
4055 /** Downgrade the exclusive lock on the region back to shared */
4057 mdb_env_share_locks(MDB_env *env, int *excl)
4059 int rc = 0, toggle = mdb_env_pick_meta(env);
4061 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
4066 /* First acquire a shared lock. The Unlock will
4067 * then release the existing exclusive lock.
4069 memset(&ov, 0, sizeof(ov));
4070 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4073 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4079 struct flock lock_info;
4080 /* The shared lock replaces the existing lock */
4081 memset((void *)&lock_info, 0, sizeof(lock_info));
4082 lock_info.l_type = F_RDLCK;
4083 lock_info.l_whence = SEEK_SET;
4084 lock_info.l_start = 0;
4085 lock_info.l_len = 1;
4086 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4087 (rc = ErrCode()) == EINTR) ;
4088 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4095 /** Try to get exlusive lock, otherwise shared.
4096 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4099 mdb_env_excl_lock(MDB_env *env, int *excl)
4103 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4107 memset(&ov, 0, sizeof(ov));
4108 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4115 struct flock lock_info;
4116 memset((void *)&lock_info, 0, sizeof(lock_info));
4117 lock_info.l_type = F_WRLCK;
4118 lock_info.l_whence = SEEK_SET;
4119 lock_info.l_start = 0;
4120 lock_info.l_len = 1;
4121 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4122 (rc = ErrCode()) == EINTR) ;
4126 # ifdef MDB_USE_POSIX_SEM
4127 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
4130 lock_info.l_type = F_RDLCK;
4131 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4132 (rc = ErrCode()) == EINTR) ;
4142 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4144 * @(#) $Revision: 5.1 $
4145 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4146 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4148 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4152 * Please do not copyright this code. This code is in the public domain.
4154 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4155 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4156 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4157 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4158 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4159 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4160 * PERFORMANCE OF THIS SOFTWARE.
4163 * chongo <Landon Curt Noll> /\oo/\
4164 * http://www.isthe.com/chongo/
4166 * Share and Enjoy! :-)
4169 typedef unsigned long long mdb_hash_t;
4170 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4172 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4173 * @param[in] val value to hash
4174 * @param[in] hval initial value for hash
4175 * @return 64 bit hash
4177 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4178 * hval arg on the first call.
4181 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4183 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4184 unsigned char *end = s + val->mv_size;
4186 * FNV-1a hash each octet of the string
4189 /* xor the bottom with the current octet */
4190 hval ^= (mdb_hash_t)*s++;
4192 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4193 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4194 (hval << 7) + (hval << 8) + (hval << 40);
4196 /* return our new hash value */
4200 /** Hash the string and output the encoded hash.
4201 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4202 * very short name limits. We don't care about the encoding being reversible,
4203 * we just want to preserve as many bits of the input as possible in a
4204 * small printable string.
4205 * @param[in] str string to hash
4206 * @param[out] encbuf an array of 11 chars to hold the hash
4208 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4211 mdb_pack85(unsigned long l, char *out)
4215 for (i=0; i<5; i++) {
4216 *out++ = mdb_a85[l % 85];
4222 mdb_hash_enc(MDB_val *val, char *encbuf)
4224 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4226 mdb_pack85(h, encbuf);
4227 mdb_pack85(h>>32, encbuf+5);
4232 /** Open and/or initialize the lock region for the environment.
4233 * @param[in] env The LMDB environment.
4234 * @param[in] lpath The pathname of the file used for the lock region.
4235 * @param[in] mode The Unix permissions for the file, if we create it.
4236 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
4237 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4238 * @return 0 on success, non-zero on failure.
4241 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4244 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4246 # define MDB_ERRCODE_ROFS EROFS
4247 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4248 # define MDB_CLOEXEC O_CLOEXEC
4251 # define MDB_CLOEXEC 0
4258 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
4259 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4260 FILE_ATTRIBUTE_NORMAL, NULL);
4262 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4264 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4266 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4271 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4272 /* Lose record locks when exec*() */
4273 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4274 fcntl(env->me_lfd, F_SETFD, fdflags);
4277 if (!(env->me_flags & MDB_NOTLS)) {
4278 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4281 env->me_flags |= MDB_ENV_TXKEY;
4283 /* Windows TLS callbacks need help finding their TLS info. */
4284 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4288 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4292 /* Try to get exclusive lock. If we succeed, then
4293 * nobody is using the lock region and we should initialize it.
4295 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4298 size = GetFileSize(env->me_lfd, NULL);
4300 size = lseek(env->me_lfd, 0, SEEK_END);
4301 if (size == -1) goto fail_errno;
4303 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4304 if (size < rsize && *excl > 0) {
4306 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4307 || !SetEndOfFile(env->me_lfd))
4310 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4314 size = rsize - sizeof(MDB_txninfo);
4315 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4320 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4322 if (!mh) goto fail_errno;
4323 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4325 if (!env->me_txns) goto fail_errno;
4327 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4329 if (m == MAP_FAILED) goto fail_errno;
4335 BY_HANDLE_FILE_INFORMATION stbuf;
4344 if (!mdb_sec_inited) {
4345 InitializeSecurityDescriptor(&mdb_null_sd,
4346 SECURITY_DESCRIPTOR_REVISION);
4347 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4348 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4349 mdb_all_sa.bInheritHandle = FALSE;
4350 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4353 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4354 idbuf.volume = stbuf.dwVolumeSerialNumber;
4355 idbuf.nhigh = stbuf.nFileIndexHigh;
4356 idbuf.nlow = stbuf.nFileIndexLow;
4357 val.mv_data = &idbuf;
4358 val.mv_size = sizeof(idbuf);
4359 mdb_hash_enc(&val, encbuf);
4360 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4361 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4362 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4363 if (!env->me_rmutex) goto fail_errno;
4364 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4365 if (!env->me_wmutex) goto fail_errno;
4366 #elif defined(MDB_USE_POSIX_SEM)
4375 #if defined(__NetBSD__)
4376 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4378 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4379 idbuf.dev = stbuf.st_dev;
4380 idbuf.ino = stbuf.st_ino;
4381 val.mv_data = &idbuf;
4382 val.mv_size = sizeof(idbuf);
4383 mdb_hash_enc(&val, encbuf);
4384 #ifdef MDB_SHORT_SEMNAMES
4385 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4387 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4388 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4389 /* Clean up after a previous run, if needed: Try to
4390 * remove both semaphores before doing anything else.
4392 sem_unlink(env->me_txns->mti_rmname);
4393 sem_unlink(env->me_txns->mti_wmname);
4394 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4395 O_CREAT|O_EXCL, mode, 1);
4396 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4397 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4398 O_CREAT|O_EXCL, mode, 1);
4399 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4400 #else /* MDB_USE_POSIX_SEM */
4401 pthread_mutexattr_t mattr;
4403 if ((rc = pthread_mutexattr_init(&mattr))
4404 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4405 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
4406 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
4408 pthread_mutexattr_destroy(&mattr);
4409 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4411 env->me_txns->mti_magic = MDB_MAGIC;
4412 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4413 env->me_txns->mti_txnid = 0;
4414 env->me_txns->mti_numreaders = 0;
4417 if (env->me_txns->mti_magic != MDB_MAGIC) {
4418 DPUTS("lock region has invalid magic");
4422 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4423 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4424 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4425 rc = MDB_VERSION_MISMATCH;
4429 if (rc && rc != EACCES && rc != EAGAIN) {
4433 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4434 if (!env->me_rmutex) goto fail_errno;
4435 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4436 if (!env->me_wmutex) goto fail_errno;
4437 #elif defined(MDB_USE_POSIX_SEM)
4438 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4439 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4440 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4441 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4452 /** The name of the lock file in the DB environment */
4453 #define LOCKNAME "/lock.mdb"
4454 /** The name of the data file in the DB environment */
4455 #define DATANAME "/data.mdb"
4456 /** The suffix of the lock file when no subdir is used */
4457 #define LOCKSUFF "-lock"
4458 /** Only a subset of the @ref mdb_env flags can be changed
4459 * at runtime. Changing other flags requires closing the
4460 * environment and re-opening it with the new flags.
4462 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4463 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP| \
4464 MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4466 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4467 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4471 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4473 int oflags, rc, len, excl = -1;
4474 char *lpath, *dpath;
4476 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4480 if (flags & MDB_WRITEMAP) {
4481 /* silently ignore WRITEMAP in 32 bit mode */
4482 flags ^= MDB_WRITEMAP;
4484 if (flags & MDB_FIXEDMAP) {
4485 /* cannot support FIXEDMAP */
4491 if (flags & MDB_NOSUBDIR) {
4492 rc = len + sizeof(LOCKSUFF) + len + 1;
4494 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4499 if (flags & MDB_NOSUBDIR) {
4500 dpath = lpath + len + sizeof(LOCKSUFF);
4501 sprintf(lpath, "%s" LOCKSUFF, path);
4502 strcpy(dpath, path);
4504 dpath = lpath + len + sizeof(LOCKNAME);
4505 sprintf(lpath, "%s" LOCKNAME, path);
4506 sprintf(dpath, "%s" DATANAME, path);
4510 flags |= env->me_flags;
4511 if (flags & MDB_RDONLY) {
4512 /* silently ignore WRITEMAP when we're only getting read access */
4513 flags &= ~MDB_WRITEMAP;
4515 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4516 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4519 env->me_flags = flags |= MDB_ENV_ACTIVE;
4523 env->me_path = strdup(path);
4524 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4525 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4526 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4527 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4532 /* For RDONLY, get lockfile after we know datafile exists */
4533 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4534 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4540 if (F_ISSET(flags, MDB_RDONLY)) {
4541 oflags = GENERIC_READ;
4542 len = OPEN_EXISTING;
4544 oflags = GENERIC_READ|GENERIC_WRITE;
4547 mode = FILE_ATTRIBUTE_NORMAL;
4548 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4549 NULL, len, mode, NULL);
4551 if (F_ISSET(flags, MDB_RDONLY))
4554 oflags = O_RDWR | O_CREAT;
4556 env->me_fd = open(dpath, oflags, mode);
4558 if (env->me_fd == INVALID_HANDLE_VALUE) {
4563 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4564 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4569 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4570 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4571 env->me_mfd = env->me_fd;
4573 /* Synchronous fd for meta writes. Needed even with
4574 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4577 len = OPEN_EXISTING;
4578 env->me_mfd = CreateFile(dpath, oflags,
4579 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4580 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4583 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4585 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4590 DPRINTF(("opened dbenv %p", (void *) env));
4592 rc = mdb_env_share_locks(env, &excl);
4596 if (!((flags & MDB_RDONLY) ||
4597 (env->me_pbuf = calloc(1, env->me_psize))))
4599 if (!(flags & MDB_RDONLY)) {
4601 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
4602 (sizeof(MDB_db)+sizeof(MDB_cursor)+sizeof(unsigned int)+1);
4603 txn = calloc(1, size);
4605 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
4606 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
4607 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
4608 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
4611 txn->mt_rpages = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2));
4612 if (!txn->mt_rpages) {
4626 mdb_env_close0(env, excl);
4632 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4634 mdb_env_close0(MDB_env *env, int excl)
4638 if (!(env->me_flags & MDB_ENV_ACTIVE))
4641 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4642 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4643 free(env->me_dbxs[i].md_name.mv_data);
4646 free(env->me_dbiseqs);
4647 free(env->me_dbflags);
4650 free(env->me_dirty_list);
4652 mdb_midl_free(env->me_free_pgs);
4654 if (env->me_flags & MDB_ENV_TXKEY) {
4655 pthread_key_delete(env->me_txkey);
4657 /* Delete our key from the global list */
4658 for (i=0; i<mdb_tls_nkeys; i++)
4659 if (mdb_tls_keys[i] == env->me_txkey) {
4660 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4669 munmap(env->me_map, 2*env->me_psize);
4671 munmap(env->me_map, env->me_mapsize);
4674 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4675 (void) close(env->me_mfd);
4676 if (env->me_fd != INVALID_HANDLE_VALUE)
4677 (void) close(env->me_fd);
4679 MDB_PID_T pid = env->me_pid;
4680 /* Clearing readers is done in this function because
4681 * me_txkey with its destructor must be disabled first.
4683 for (i = env->me_numreaders; --i >= 0; )
4684 if (env->me_txns->mti_readers[i].mr_pid == pid)
4685 env->me_txns->mti_readers[i].mr_pid = 0;
4687 if (env->me_rmutex) {
4688 CloseHandle(env->me_rmutex);
4689 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4691 /* Windows automatically destroys the mutexes when
4692 * the last handle closes.
4694 #elif defined(MDB_USE_POSIX_SEM)
4695 if (env->me_rmutex != SEM_FAILED) {
4696 sem_close(env->me_rmutex);
4697 if (env->me_wmutex != SEM_FAILED)
4698 sem_close(env->me_wmutex);
4699 /* If we have the filelock: If we are the
4700 * only remaining user, clean up semaphores.
4703 mdb_env_excl_lock(env, &excl);
4705 sem_unlink(env->me_txns->mti_rmname);
4706 sem_unlink(env->me_txns->mti_wmname);
4710 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4712 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4715 /* Unlock the lockfile. Windows would have unlocked it
4716 * after closing anyway, but not necessarily at once.
4718 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4721 (void) close(env->me_lfd);
4724 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4729 mdb_env_close(MDB_env *env)
4736 VGMEMP_DESTROY(env);
4737 while ((dp = env->me_dpages) != NULL) {
4738 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4739 env->me_dpages = dp->mp_next;
4743 mdb_env_close0(env, 0);
4747 /** Compare two items pointing at aligned size_t's */
4749 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4751 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4752 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4755 /** Compare two items pointing at aligned unsigned int's */
4757 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4759 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4760 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4763 /** Compare two items pointing at unsigned ints of unknown alignment.
4764 * Nodes and keys are guaranteed to be 2-byte aligned.
4767 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4769 #if BYTE_ORDER == LITTLE_ENDIAN
4770 unsigned short *u, *c;
4773 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4774 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4777 } while(!x && u > (unsigned short *)a->mv_data);
4780 unsigned short *u, *c, *end;
4783 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4784 u = (unsigned short *)a->mv_data;
4785 c = (unsigned short *)b->mv_data;
4788 } while(!x && u < end);
4793 /** Compare two items pointing at size_t's of unknown alignment. */
4794 #ifdef MISALIGNED_OK
4795 # define mdb_cmp_clong mdb_cmp_long
4797 # define mdb_cmp_clong mdb_cmp_cint
4800 /** Compare two items lexically */
4802 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4809 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4815 diff = memcmp(a->mv_data, b->mv_data, len);
4816 return diff ? diff : len_diff<0 ? -1 : len_diff;
4819 /** Compare two items in reverse byte order */
4821 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4823 const unsigned char *p1, *p2, *p1_lim;
4827 p1_lim = (const unsigned char *)a->mv_data;
4828 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4829 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4831 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4837 while (p1 > p1_lim) {
4838 diff = *--p1 - *--p2;
4842 return len_diff<0 ? -1 : len_diff;
4845 /** Search for key within a page, using binary search.
4846 * Returns the smallest entry larger or equal to the key.
4847 * If exactp is non-null, stores whether the found entry was an exact match
4848 * in *exactp (1 or 0).
4849 * Updates the cursor index with the index of the found entry.
4850 * If no entry larger or equal to the key is found, returns NULL.
4853 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4855 unsigned int i = 0, nkeys;
4858 MDB_page *mp = mc->mc_pg[mc->mc_top];
4859 MDB_node *node = NULL;
4864 nkeys = NUMKEYS(mp);
4866 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4867 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4870 low = IS_LEAF(mp) ? 0 : 1;
4872 cmp = mc->mc_dbx->md_cmp;
4874 /* Branch pages have no data, so if using integer keys,
4875 * alignment is guaranteed. Use faster mdb_cmp_int.
4877 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4878 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4885 nodekey.mv_size = mc->mc_db->md_pad;
4886 node = NODEPTR(mp, 0); /* fake */
4887 while (low <= high) {
4888 i = (low + high) >> 1;
4889 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4890 rc = cmp(key, &nodekey);
4891 DPRINTF(("found leaf index %u [%s], rc = %i",
4892 i, DKEY(&nodekey), rc));
4901 while (low <= high) {
4902 i = (low + high) >> 1;
4904 node = NODEPTR(mp, i);
4905 nodekey.mv_size = NODEKSZ(node);
4906 nodekey.mv_data = NODEKEY(node);
4908 rc = cmp(key, &nodekey);
4911 DPRINTF(("found leaf index %u [%s], rc = %i",
4912 i, DKEY(&nodekey), rc));
4914 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4915 i, DKEY(&nodekey), NODEPGNO(node), rc));
4926 if (rc > 0) { /* Found entry is less than the key. */
4927 i++; /* Skip to get the smallest entry larger than key. */
4929 node = NODEPTR(mp, i);
4932 *exactp = (rc == 0 && nkeys > 0);
4933 /* store the key index */
4934 mc->mc_ki[mc->mc_top] = i;
4936 /* There is no entry larger or equal to the key. */
4939 /* nodeptr is fake for LEAF2 */
4945 mdb_cursor_adjust(MDB_cursor *mc, func)
4949 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4950 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4957 /** Pop a page off the top of the cursor's stack. */
4959 mdb_cursor_pop(MDB_cursor *mc)
4963 MDB_page *top = mc->mc_pg[mc->mc_top];
4969 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4970 DDBI(mc), (void *) mc));
4974 /** Push a page onto the top of the cursor's stack. */
4976 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4978 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4979 DDBI(mc), (void *) mc));
4981 if (mc->mc_snum >= CURSOR_STACK) {
4982 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4983 return MDB_CURSOR_FULL;
4986 mc->mc_top = mc->mc_snum++;
4987 mc->mc_pg[mc->mc_top] = mp;
4988 mc->mc_ki[mc->mc_top] = 0;
4993 /** Find the address of the page corresponding to a given page number.
4994 * @param[in] txn the transaction for this access.
4995 * @param[in] pgno the page number for the page to retrieve.
4996 * @param[out] ret address of a pointer where the page's address will be stored.
4997 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4998 * @return 0 on success, non-zero on failure.
5001 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
5003 MDB_env *env = txn->mt_env;
5007 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
5011 MDB_ID2L dl = tx2->mt_u.dirty_list;
5013 /* Spilled pages were dirtied in this txn and flushed
5014 * because the dirty list got full. Bring this page
5015 * back in from the map (but don't unspill it here,
5016 * leave that unless page_touch happens again).
5018 if (tx2->mt_spill_pgs) {
5019 MDB_ID pn = pgno << 1;
5020 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5021 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5022 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5027 unsigned x = mdb_mid2l_search(dl, pgno);
5028 if (x <= dl[0].mid && dl[x].mid == pgno) {
5034 } while ((tx2 = tx2->mt_parent) != NULL);
5037 if (pgno < txn->mt_next_pgno) {
5041 unsigned x = mdb_mid2l_search(txn->mt_rpages, pgno);
5042 if (x <= txn->mt_rpages[0].mid && txn->mt_rpages[x].mid == pgno) {
5043 p = txn->mt_rpages[x].mptr;
5046 if (txn->mt_rpages[0].mid >= MDB_IDL_UM_MAX) {
5047 /* unmap some other page */
5048 mdb_tassert(txn, 0);
5050 if (txn->mt_rpages[0].mid < MDB_IDL_UM_SIZE) {
5052 size_t len = env->me_psize;
5055 size_t off = pgno * env->me_psize;
5057 lo = off & 0xffffffff;
5058 hi = off >> 16 >> 16;
5059 p = MapViewOfFile(env->me_fmh, FILE_MAP_READ, hi, lo, len);
5062 if (IS_OVERFLOW(p)) {
5066 p = MapViewOfFile(env->me_fmh, FILE_MAP_READ, hi, lo, len);
5071 off_t off = pgno * env->me_psize;
5072 p = mmap(NULL, len, PROT_READ, MAP_SHARED, env->me_fd, off);
5073 if (p == MAP_FAILED)
5075 if (IS_OVERFLOW(p)) {
5079 p = mmap(NULL, len, PROT_READ, MAP_SHARED, env->me_fd, off);
5080 if (p == MAP_FAILED)
5086 mdb_mid2l_insert(txn->mt_rpages, &id2);
5091 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5094 DPRINTF(("page %"Z"u not found", pgno));
5095 txn->mt_flags |= MDB_TXN_ERROR;
5096 return MDB_PAGE_NOTFOUND;
5106 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
5107 * The cursor is at the root page, set up the rest of it.
5110 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
5112 MDB_page *mp = mc->mc_pg[mc->mc_top];
5116 while (IS_BRANCH(mp)) {
5120 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
5121 mdb_cassert(mc, NUMKEYS(mp) > 1);
5122 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
5124 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
5126 if (flags & MDB_PS_LAST)
5127 i = NUMKEYS(mp) - 1;
5130 node = mdb_node_search(mc, key, &exact);
5132 i = NUMKEYS(mp) - 1;
5134 i = mc->mc_ki[mc->mc_top];
5136 mdb_cassert(mc, i > 0);
5140 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
5143 mdb_cassert(mc, i < NUMKEYS(mp));
5144 node = NODEPTR(mp, i);
5146 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5149 mc->mc_ki[mc->mc_top] = i;
5150 if ((rc = mdb_cursor_push(mc, mp)))
5153 if (flags & MDB_PS_MODIFY) {
5154 if ((rc = mdb_page_touch(mc)) != 0)
5156 mp = mc->mc_pg[mc->mc_top];
5161 DPRINTF(("internal error, index points to a %02X page!?",
5163 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5164 return MDB_CORRUPTED;
5167 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
5168 key ? DKEY(key) : "null"));
5169 mc->mc_flags |= C_INITIALIZED;
5170 mc->mc_flags &= ~C_EOF;
5175 /** Search for the lowest key under the current branch page.
5176 * This just bypasses a NUMKEYS check in the current page
5177 * before calling mdb_page_search_root(), because the callers
5178 * are all in situations where the current page is known to
5182 mdb_page_search_lowest(MDB_cursor *mc)
5184 MDB_page *mp = mc->mc_pg[mc->mc_top];
5185 MDB_node *node = NODEPTR(mp, 0);
5188 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5191 mc->mc_ki[mc->mc_top] = 0;
5192 if ((rc = mdb_cursor_push(mc, mp)))
5194 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5197 /** Search for the page a given key should be in.
5198 * Push it and its parent pages on the cursor stack.
5199 * @param[in,out] mc the cursor for this operation.
5200 * @param[in] key the key to search for, or NULL for first/last page.
5201 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5202 * are touched (updated with new page numbers).
5203 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5204 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5205 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5206 * @return 0 on success, non-zero on failure.
5209 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5214 /* Make sure the txn is still viable, then find the root from
5215 * the txn's db table and set it as the root of the cursor's stack.
5217 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
5218 DPUTS("transaction has failed, must abort");
5221 /* Make sure we're using an up-to-date root */
5222 if (*mc->mc_dbflag & DB_STALE) {
5224 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5226 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5227 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5234 MDB_node *leaf = mdb_node_search(&mc2,
5235 &mc->mc_dbx->md_name, &exact);
5237 return MDB_NOTFOUND;
5238 rc = mdb_node_read(mc->mc_txn, leaf, &data);
5241 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5243 /* The txn may not know this DBI, or another process may
5244 * have dropped and recreated the DB with other flags.
5246 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5247 return MDB_INCOMPATIBLE;
5248 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5250 *mc->mc_dbflag &= ~DB_STALE;
5252 root = mc->mc_db->md_root;
5254 if (root == P_INVALID) { /* Tree is empty. */
5255 DPUTS("tree is empty");
5256 return MDB_NOTFOUND;
5260 mdb_cassert(mc, root > 1);
5261 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5262 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
5268 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5269 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5271 if (flags & MDB_PS_MODIFY) {
5272 if ((rc = mdb_page_touch(mc)))
5276 if (flags & MDB_PS_ROOTONLY)
5279 return mdb_page_search_root(mc, key, flags);
5283 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5285 MDB_txn *txn = mc->mc_txn;
5286 pgno_t pg = mp->mp_pgno;
5287 unsigned x = 0, ovpages = mp->mp_pages;
5288 MDB_env *env = txn->mt_env;
5289 MDB_IDL sl = txn->mt_spill_pgs;
5290 MDB_ID pn = pg << 1;
5293 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5294 /* If the page is dirty or on the spill list we just acquired it,
5295 * so we should give it back to our current free list, if any.
5296 * Otherwise put it onto the list of pages we freed in this txn.
5298 * Won't create me_pghead: me_pglast must be inited along with it.
5299 * Unsupported in nested txns: They would need to hide the page
5300 * range in ancestor txns' dirty and spilled lists.
5302 if (env->me_pghead &&
5304 ((mp->mp_flags & P_DIRTY) ||
5305 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5309 MDB_ID2 *dl, ix, iy;
5310 rc = mdb_midl_need(&env->me_pghead, ovpages);
5313 if (!(mp->mp_flags & P_DIRTY)) {
5314 /* This page is no longer spilled */
5321 /* Remove from dirty list */
5322 dl = txn->mt_u.dirty_list;
5324 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5330 mdb_cassert(mc, x > 1);
5332 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5333 txn->mt_flags |= MDB_TXN_ERROR;
5334 return MDB_CORRUPTED;
5337 if (!(env->me_flags & MDB_WRITEMAP))
5338 mdb_dpage_free(env, mp);
5340 /* Insert in me_pghead */
5341 mop = env->me_pghead;
5342 j = mop[0] + ovpages;
5343 for (i = mop[0]; i && mop[i] < pg; i--)
5349 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5353 mc->mc_db->md_overflow_pages -= ovpages;
5357 /** Return the data associated with a given node.
5358 * @param[in] txn The transaction for this operation.
5359 * @param[in] leaf The node being read.
5360 * @param[out] data Updated to point to the node's data.
5361 * @return 0 on success, non-zero on failure.
5364 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5366 MDB_page *omp; /* overflow page */
5370 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5371 data->mv_size = NODEDSZ(leaf);
5372 data->mv_data = NODEDATA(leaf);
5376 /* Read overflow data.
5378 data->mv_size = NODEDSZ(leaf);
5379 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5380 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5381 DPRINTF(("read overflow page %"Z"u failed", pgno));
5384 data->mv_data = METADATA(omp);
5390 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5391 MDB_val *key, MDB_val *data)
5398 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5400 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
5403 if (txn->mt_flags & MDB_TXN_ERROR)
5406 mdb_cursor_init(&mc, txn, dbi, &mx);
5407 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5410 /** Find a sibling for a page.
5411 * Replaces the page at the top of the cursor's stack with the
5412 * specified sibling, if one exists.
5413 * @param[in] mc The cursor for this operation.
5414 * @param[in] move_right Non-zero if the right sibling is requested,
5415 * otherwise the left sibling.
5416 * @return 0 on success, non-zero on failure.
5419 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5428 if (mc->mc_snum < 2) {
5429 return MDB_NOTFOUND; /* root has no siblings */
5433 op = mc->mc_pg[mc->mc_top];
5436 DPRINTF(("parent page is page %"Z"u, index %u",
5437 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5439 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5440 : (mc->mc_ki[mc->mc_top] == 0)) {
5441 DPRINTF(("no more keys left, moving to %s sibling",
5442 move_right ? "right" : "left"));
5443 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5444 /* undo cursor_pop before returning */
5451 mc->mc_ki[mc->mc_top]++;
5453 mc->mc_ki[mc->mc_top]--;
5454 DPRINTF(("just moving to %s index key %u",
5455 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5457 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5461 MDB_ID2L rl = mc->mc_txn->mt_rpages;
5462 unsigned x = mdb_mid2l_search(rl, op->mp_pgno);
5463 if (x <= rl[0].mid && rl[x].mid == op->mp_pgno) {
5464 munmap(op, mc->mc_txn->mt_env->me_psize);
5465 while (x < rl[0].mid) {
5474 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5475 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5476 /* mc will be inconsistent if caller does mc_snum++ as above */
5477 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5481 mdb_cursor_push(mc, mp);
5483 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5488 /** Move the cursor to the next data item. */
5490 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5496 if (mc->mc_flags & C_EOF) {
5497 return MDB_NOTFOUND;
5500 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5502 mp = mc->mc_pg[mc->mc_top];
5504 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5505 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5506 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5507 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5508 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5509 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5510 if (rc == MDB_SUCCESS)
5511 MDB_GET_KEY(leaf, key);
5516 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5517 if (op == MDB_NEXT_DUP)
5518 return MDB_NOTFOUND;
5522 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5523 mdb_dbg_pgno(mp), (void *) mc));
5524 if (mc->mc_flags & C_DEL)
5527 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5528 DPUTS("=====> move to next sibling page");
5529 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5530 mc->mc_flags |= C_EOF;
5533 mp = mc->mc_pg[mc->mc_top];
5534 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5536 mc->mc_ki[mc->mc_top]++;
5539 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5540 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5543 key->mv_size = mc->mc_db->md_pad;
5544 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5548 mdb_cassert(mc, IS_LEAF(mp));
5549 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5551 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5552 mdb_xcursor_init1(mc, leaf);
5555 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5558 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5559 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5560 if (rc != MDB_SUCCESS)
5565 MDB_GET_KEY(leaf, key);
5569 /** Move the cursor to the previous data item. */
5571 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5577 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5579 mp = mc->mc_pg[mc->mc_top];
5581 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5582 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5583 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5584 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5585 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5586 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5587 if (rc == MDB_SUCCESS) {
5588 MDB_GET_KEY(leaf, key);
5589 mc->mc_flags &= ~C_EOF;
5594 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5595 if (op == MDB_PREV_DUP)
5596 return MDB_NOTFOUND;
5601 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5602 mdb_dbg_pgno(mp), (void *) mc));
5604 if (mc->mc_ki[mc->mc_top] == 0) {
5605 DPUTS("=====> move to prev sibling page");
5606 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5609 mp = mc->mc_pg[mc->mc_top];
5610 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5611 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5613 mc->mc_ki[mc->mc_top]--;
5615 mc->mc_flags &= ~C_EOF;
5617 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5618 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5621 key->mv_size = mc->mc_db->md_pad;
5622 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5626 mdb_cassert(mc, IS_LEAF(mp));
5627 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5629 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5630 mdb_xcursor_init1(mc, leaf);
5633 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5636 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5637 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5638 if (rc != MDB_SUCCESS)
5643 MDB_GET_KEY(leaf, key);
5647 /** Set the cursor on a specific data item. */
5649 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5650 MDB_cursor_op op, int *exactp)
5654 MDB_node *leaf = NULL;
5657 if (key->mv_size == 0)
5658 return MDB_BAD_VALSIZE;
5661 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5663 /* See if we're already on the right page */
5664 if (mc->mc_flags & C_INITIALIZED) {
5667 mp = mc->mc_pg[mc->mc_top];
5669 mc->mc_ki[mc->mc_top] = 0;
5670 return MDB_NOTFOUND;
5672 if (mp->mp_flags & P_LEAF2) {
5673 nodekey.mv_size = mc->mc_db->md_pad;
5674 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5676 leaf = NODEPTR(mp, 0);
5677 MDB_GET_KEY2(leaf, nodekey);
5679 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5681 /* Probably happens rarely, but first node on the page
5682 * was the one we wanted.
5684 mc->mc_ki[mc->mc_top] = 0;
5691 unsigned int nkeys = NUMKEYS(mp);
5693 if (mp->mp_flags & P_LEAF2) {
5694 nodekey.mv_data = LEAF2KEY(mp,
5695 nkeys-1, nodekey.mv_size);
5697 leaf = NODEPTR(mp, nkeys-1);
5698 MDB_GET_KEY2(leaf, nodekey);
5700 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5702 /* last node was the one we wanted */
5703 mc->mc_ki[mc->mc_top] = nkeys-1;
5709 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5710 /* This is definitely the right page, skip search_page */
5711 if (mp->mp_flags & P_LEAF2) {
5712 nodekey.mv_data = LEAF2KEY(mp,
5713 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5715 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5716 MDB_GET_KEY2(leaf, nodekey);
5718 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5720 /* current node was the one we wanted */
5730 /* If any parents have right-sibs, search.
5731 * Otherwise, there's nothing further.
5733 for (i=0; i<mc->mc_top; i++)
5735 NUMKEYS(mc->mc_pg[i])-1)
5737 if (i == mc->mc_top) {
5738 /* There are no other pages */
5739 mc->mc_ki[mc->mc_top] = nkeys;
5740 return MDB_NOTFOUND;
5744 /* There are no other pages */
5745 mc->mc_ki[mc->mc_top] = 0;
5746 if (op == MDB_SET_RANGE && !exactp) {
5750 return MDB_NOTFOUND;
5754 rc = mdb_page_search(mc, key, 0);
5755 if (rc != MDB_SUCCESS)
5758 mp = mc->mc_pg[mc->mc_top];
5759 mdb_cassert(mc, IS_LEAF(mp));
5762 leaf = mdb_node_search(mc, key, exactp);
5763 if (exactp != NULL && !*exactp) {
5764 /* MDB_SET specified and not an exact match. */
5765 return MDB_NOTFOUND;
5769 DPUTS("===> inexact leaf not found, goto sibling");
5770 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5771 return rc; /* no entries matched */
5772 mp = mc->mc_pg[mc->mc_top];
5773 mdb_cassert(mc, IS_LEAF(mp));
5774 leaf = NODEPTR(mp, 0);
5778 mc->mc_flags |= C_INITIALIZED;
5779 mc->mc_flags &= ~C_EOF;
5782 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5783 key->mv_size = mc->mc_db->md_pad;
5784 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5789 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5790 mdb_xcursor_init1(mc, leaf);
5793 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5794 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5795 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5798 if (op == MDB_GET_BOTH) {
5804 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5805 if (rc != MDB_SUCCESS)
5808 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5810 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5812 rc = mc->mc_dbx->md_dcmp(data, &d2);
5814 if (op == MDB_GET_BOTH || rc > 0)
5815 return MDB_NOTFOUND;
5822 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5823 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5828 /* The key already matches in all other cases */
5829 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5830 MDB_GET_KEY(leaf, key);
5831 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5836 /** Move the cursor to the first item in the database. */
5838 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5844 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5846 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5847 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5848 if (rc != MDB_SUCCESS)
5851 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5853 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5854 mc->mc_flags |= C_INITIALIZED;
5855 mc->mc_flags &= ~C_EOF;
5857 mc->mc_ki[mc->mc_top] = 0;
5859 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5860 key->mv_size = mc->mc_db->md_pad;
5861 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5866 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5867 mdb_xcursor_init1(mc, leaf);
5868 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5872 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5876 MDB_GET_KEY(leaf, key);
5880 /** Move the cursor to the last item in the database. */
5882 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5888 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5890 if (!(mc->mc_flags & C_EOF)) {
5892 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5893 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5894 if (rc != MDB_SUCCESS)
5897 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5900 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5901 mc->mc_flags |= C_INITIALIZED|C_EOF;
5902 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5904 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5905 key->mv_size = mc->mc_db->md_pad;
5906 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5911 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5912 mdb_xcursor_init1(mc, leaf);
5913 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5917 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5922 MDB_GET_KEY(leaf, key);
5927 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5932 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5937 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5941 case MDB_GET_CURRENT:
5942 if (!(mc->mc_flags & C_INITIALIZED)) {
5945 MDB_page *mp = mc->mc_pg[mc->mc_top];
5946 int nkeys = NUMKEYS(mp);
5947 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5948 mc->mc_ki[mc->mc_top] = nkeys;
5954 key->mv_size = mc->mc_db->md_pad;
5955 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5957 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5958 MDB_GET_KEY(leaf, key);
5960 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5961 if (mc->mc_flags & C_DEL)
5962 mdb_xcursor_init1(mc, leaf);
5963 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5965 rc = mdb_node_read(mc->mc_txn, leaf, data);
5972 case MDB_GET_BOTH_RANGE:
5977 if (mc->mc_xcursor == NULL) {
5978 rc = MDB_INCOMPATIBLE;
5988 rc = mdb_cursor_set(mc, key, data, op,
5989 op == MDB_SET_RANGE ? NULL : &exact);
5992 case MDB_GET_MULTIPLE:
5993 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5997 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5998 rc = MDB_INCOMPATIBLE;
6002 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6003 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6006 case MDB_NEXT_MULTIPLE:
6011 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6012 rc = MDB_INCOMPATIBLE;
6015 if (!(mc->mc_flags & C_INITIALIZED))
6016 rc = mdb_cursor_first(mc, key, data);
6018 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6019 if (rc == MDB_SUCCESS) {
6020 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6023 mx = &mc->mc_xcursor->mx_cursor;
6024 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
6026 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
6027 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
6035 case MDB_NEXT_NODUP:
6036 if (!(mc->mc_flags & C_INITIALIZED))
6037 rc = mdb_cursor_first(mc, key, data);
6039 rc = mdb_cursor_next(mc, key, data, op);
6043 case MDB_PREV_NODUP:
6044 if (!(mc->mc_flags & C_INITIALIZED)) {
6045 rc = mdb_cursor_last(mc, key, data);
6048 mc->mc_flags |= C_INITIALIZED;
6049 mc->mc_ki[mc->mc_top]++;
6051 rc = mdb_cursor_prev(mc, key, data, op);
6054 rc = mdb_cursor_first(mc, key, data);
6057 mfunc = mdb_cursor_first;
6059 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6063 if (mc->mc_xcursor == NULL) {
6064 rc = MDB_INCOMPATIBLE;
6068 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6069 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6070 MDB_GET_KEY(leaf, key);
6071 rc = mdb_node_read(mc->mc_txn, leaf, data);
6075 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6079 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
6082 rc = mdb_cursor_last(mc, key, data);
6085 mfunc = mdb_cursor_last;
6088 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
6093 if (mc->mc_flags & C_DEL)
6094 mc->mc_flags ^= C_DEL;
6099 /** Touch all the pages in the cursor stack. Set mc_top.
6100 * Makes sure all the pages are writable, before attempting a write operation.
6101 * @param[in] mc The cursor to operate on.
6104 mdb_cursor_touch(MDB_cursor *mc)
6106 int rc = MDB_SUCCESS;
6108 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
6111 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6113 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
6114 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
6117 *mc->mc_dbflag |= DB_DIRTY;
6122 rc = mdb_page_touch(mc);
6123 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
6124 mc->mc_top = mc->mc_snum-1;
6129 /** Do not spill pages to disk if txn is getting full, may fail instead */
6130 #define MDB_NOSPILL 0x8000
6133 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6136 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
6138 MDB_node *leaf = NULL;
6141 MDB_val xdata, *rdata, dkey, olddata;
6143 int do_sub = 0, insert_key, insert_data;
6144 unsigned int mcount = 0, dcount = 0, nospill;
6147 unsigned int nflags;
6150 if (mc == NULL || key == NULL)
6153 env = mc->mc_txn->mt_env;
6155 /* Check this first so counter will always be zero on any
6158 if (flags & MDB_MULTIPLE) {
6159 dcount = data[1].mv_size;
6160 data[1].mv_size = 0;
6161 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
6162 return MDB_INCOMPATIBLE;
6165 nospill = flags & MDB_NOSPILL;
6166 flags &= ~MDB_NOSPILL;
6168 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6169 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6171 if (key->mv_size-1 >= ENV_MAXKEY(env))
6172 return MDB_BAD_VALSIZE;
6174 #if SIZE_MAX > MAXDATASIZE
6175 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
6176 return MDB_BAD_VALSIZE;
6178 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
6179 return MDB_BAD_VALSIZE;
6182 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
6183 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
6187 if (flags == MDB_CURRENT) {
6188 if (!(mc->mc_flags & C_INITIALIZED))
6191 } else if (mc->mc_db->md_root == P_INVALID) {
6192 /* new database, cursor has nothing to point to */
6195 mc->mc_flags &= ~C_INITIALIZED;
6200 if (flags & MDB_APPEND) {
6202 rc = mdb_cursor_last(mc, &k2, &d2);
6204 rc = mc->mc_dbx->md_cmp(key, &k2);
6207 mc->mc_ki[mc->mc_top]++;
6209 /* new key is <= last key */
6214 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6216 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6217 DPRINTF(("duplicate key [%s]", DKEY(key)));
6219 return MDB_KEYEXIST;
6221 if (rc && rc != MDB_NOTFOUND)
6225 if (mc->mc_flags & C_DEL)
6226 mc->mc_flags ^= C_DEL;
6228 /* Cursor is positioned, check for room in the dirty list */
6230 if (flags & MDB_MULTIPLE) {
6232 xdata.mv_size = data->mv_size * dcount;
6236 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6240 if (rc == MDB_NO_ROOT) {
6242 /* new database, write a root leaf page */
6243 DPUTS("allocating new root leaf page");
6244 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6247 mdb_cursor_push(mc, np);
6248 mc->mc_db->md_root = np->mp_pgno;
6249 mc->mc_db->md_depth++;
6250 *mc->mc_dbflag |= DB_DIRTY;
6251 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6253 np->mp_flags |= P_LEAF2;
6254 mc->mc_flags |= C_INITIALIZED;
6256 /* make sure all cursor pages are writable */
6257 rc2 = mdb_cursor_touch(mc);
6262 insert_key = insert_data = rc;
6264 /* The key does not exist */
6265 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6266 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6267 LEAFSIZE(key, data) > env->me_nodemax)
6269 /* Too big for a node, insert in sub-DB. Set up an empty
6270 * "old sub-page" for prep_subDB to expand to a full page.
6272 fp_flags = P_LEAF|P_DIRTY;
6274 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6275 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6276 olddata.mv_size = PAGEHDRSZ;
6280 /* there's only a key anyway, so this is a no-op */
6281 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6283 unsigned int ksize = mc->mc_db->md_pad;
6284 if (key->mv_size != ksize)
6285 return MDB_BAD_VALSIZE;
6286 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6287 memcpy(ptr, key->mv_data, ksize);
6289 /* if overwriting slot 0 of leaf, need to
6290 * update branch key if there is a parent page
6292 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6293 unsigned short top = mc->mc_top;
6295 /* slot 0 is always an empty key, find real slot */
6296 while (mc->mc_top && !mc->mc_ki[mc->mc_top])
6298 if (mc->mc_ki[mc->mc_top])
6299 rc2 = mdb_update_key(mc, key);
6310 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6311 olddata.mv_size = NODEDSZ(leaf);
6312 olddata.mv_data = NODEDATA(leaf);
6315 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6316 /* Prepare (sub-)page/sub-DB to accept the new item,
6317 * if needed. fp: old sub-page or a header faking
6318 * it. mp: new (sub-)page. offset: growth in page
6319 * size. xdata: node data with new page or DB.
6321 unsigned i, offset = 0;
6322 mp = fp = xdata.mv_data = env->me_pbuf;
6323 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6325 /* Was a single item before, must convert now */
6326 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6327 /* Just overwrite the current item */
6328 if (flags == MDB_CURRENT)
6331 #if UINT_MAX < SIZE_MAX
6332 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6333 mc->mc_dbx->md_dcmp = mdb_cmp_clong;
6335 /* does data match? */
6336 if (!mc->mc_dbx->md_dcmp(data, &olddata)) {
6337 if (flags & MDB_NODUPDATA)
6338 return MDB_KEYEXIST;
6343 /* Back up original data item */
6344 dkey.mv_size = olddata.mv_size;
6345 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6347 /* Make sub-page header for the dup items, with dummy body */
6348 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6349 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6350 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6351 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6352 fp->mp_flags |= P_LEAF2;
6353 fp->mp_pad = data->mv_size;
6354 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6356 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6357 (dkey.mv_size & 1) + (data->mv_size & 1);
6359 fp->mp_upper = xdata.mv_size - PAGEBASE;
6360 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6361 } else if (leaf->mn_flags & F_SUBDATA) {
6362 /* Data is on sub-DB, just store it */
6363 flags |= F_DUPDATA|F_SUBDATA;
6366 /* Data is on sub-page */
6367 fp = olddata.mv_data;
6370 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6371 offset = EVEN(NODESIZE + sizeof(indx_t) +
6375 offset = fp->mp_pad;
6376 if (SIZELEFT(fp) < offset) {
6377 offset *= 4; /* space for 4 more */
6380 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6382 fp->mp_flags |= P_DIRTY;
6383 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6384 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6388 xdata.mv_size = olddata.mv_size + offset;
6391 fp_flags = fp->mp_flags;
6392 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6393 /* Too big for a sub-page, convert to sub-DB */
6394 fp_flags &= ~P_SUBP;
6396 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6397 fp_flags |= P_LEAF2;
6398 dummy.md_pad = fp->mp_pad;
6399 dummy.md_flags = MDB_DUPFIXED;
6400 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6401 dummy.md_flags |= MDB_INTEGERKEY;
6407 dummy.md_branch_pages = 0;
6408 dummy.md_leaf_pages = 1;
6409 dummy.md_overflow_pages = 0;
6410 dummy.md_entries = NUMKEYS(fp);
6411 xdata.mv_size = sizeof(MDB_db);
6412 xdata.mv_data = &dummy;
6413 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6415 offset = env->me_psize - olddata.mv_size;
6416 flags |= F_DUPDATA|F_SUBDATA;
6417 dummy.md_root = mp->mp_pgno;
6420 mp->mp_flags = fp_flags | P_DIRTY;
6421 mp->mp_pad = fp->mp_pad;
6422 mp->mp_lower = fp->mp_lower;
6423 mp->mp_upper = fp->mp_upper + offset;
6424 if (fp_flags & P_LEAF2) {
6425 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6427 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6428 olddata.mv_size - fp->mp_upper - PAGEBASE);
6429 for (i=0; i<NUMKEYS(fp); i++)
6430 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6438 mdb_node_del(mc, 0);
6442 /* overflow page overwrites need special handling */
6443 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6446 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6448 memcpy(&pg, olddata.mv_data, sizeof(pg));
6449 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6451 ovpages = omp->mp_pages;
6453 /* Is the ov page large enough? */
6454 if (ovpages >= dpages) {
6455 if (!(omp->mp_flags & P_DIRTY) &&
6456 (level || (env->me_flags & MDB_WRITEMAP)))
6458 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6461 level = 0; /* dirty in this txn or clean */
6464 if (omp->mp_flags & P_DIRTY) {
6465 /* yes, overwrite it. Note in this case we don't
6466 * bother to try shrinking the page if the new data
6467 * is smaller than the overflow threshold.
6470 /* It is writable only in a parent txn */
6471 size_t sz = (size_t) env->me_psize * ovpages, off;
6472 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6478 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6479 mdb_cassert(mc, rc2 == 0);
6480 if (!(flags & MDB_RESERVE)) {
6481 /* Copy end of page, adjusting alignment so
6482 * compiler may copy words instead of bytes.
6484 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6485 memcpy((size_t *)((char *)np + off),
6486 (size_t *)((char *)omp + off), sz - off);
6489 memcpy(np, omp, sz); /* Copy beginning of page */
6492 SETDSZ(leaf, data->mv_size);
6493 if (F_ISSET(flags, MDB_RESERVE))
6494 data->mv_data = METADATA(omp);
6496 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6500 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6502 } else if (data->mv_size == olddata.mv_size) {
6503 /* same size, just replace it. Note that we could
6504 * also reuse this node if the new data is smaller,
6505 * but instead we opt to shrink the node in that case.
6507 if (F_ISSET(flags, MDB_RESERVE))
6508 data->mv_data = olddata.mv_data;
6509 else if (!(mc->mc_flags & C_SUB))
6510 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6512 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6517 mdb_node_del(mc, 0);
6523 nflags = flags & NODE_ADD_FLAGS;
6524 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6525 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6526 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6527 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6529 nflags |= MDB_SPLIT_REPLACE;
6530 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6532 /* There is room already in this leaf page. */
6533 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6534 if (rc == 0 && insert_key) {
6535 /* Adjust other cursors pointing to mp */
6536 MDB_cursor *m2, *m3;
6537 MDB_dbi dbi = mc->mc_dbi;
6538 unsigned i = mc->mc_top;
6539 MDB_page *mp = mc->mc_pg[i];
6541 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6542 if (mc->mc_flags & C_SUB)
6543 m3 = &m2->mc_xcursor->mx_cursor;
6546 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6547 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6554 if (rc == MDB_SUCCESS) {
6555 /* Now store the actual data in the child DB. Note that we're
6556 * storing the user data in the keys field, so there are strict
6557 * size limits on dupdata. The actual data fields of the child
6558 * DB are all zero size.
6566 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6567 if (flags & MDB_CURRENT) {
6568 xflags = MDB_CURRENT|MDB_NOSPILL;
6570 mdb_xcursor_init1(mc, leaf);
6571 xflags = (flags & MDB_NODUPDATA) ?
6572 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6574 /* converted, write the original data first */
6576 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6580 /* Adjust other cursors pointing to mp */
6582 unsigned i = mc->mc_top;
6583 MDB_page *mp = mc->mc_pg[i];
6585 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6586 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6587 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6588 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6589 mdb_xcursor_init1(m2, leaf);
6593 /* we've done our job */
6596 ecount = mc->mc_xcursor->mx_db.md_entries;
6597 if (flags & MDB_APPENDDUP)
6598 xflags |= MDB_APPEND;
6599 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6600 if (flags & F_SUBDATA) {
6601 void *db = NODEDATA(leaf);
6602 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6604 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6606 /* Increment count unless we just replaced an existing item. */
6608 mc->mc_db->md_entries++;
6610 /* Invalidate txn if we created an empty sub-DB */
6613 /* If we succeeded and the key didn't exist before,
6614 * make sure the cursor is marked valid.
6616 mc->mc_flags |= C_INITIALIZED;
6618 if (flags & MDB_MULTIPLE) {
6621 /* let caller know how many succeeded, if any */
6622 data[1].mv_size = mcount;
6623 if (mcount < dcount) {
6624 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6625 insert_key = insert_data = 0;
6632 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6635 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6640 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6646 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6647 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6649 if (!(mc->mc_flags & C_INITIALIZED))
6652 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6653 return MDB_NOTFOUND;
6655 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6658 rc = mdb_cursor_touch(mc);
6662 mp = mc->mc_pg[mc->mc_top];
6665 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6667 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6668 if (flags & MDB_NODUPDATA) {
6669 /* mdb_cursor_del0() will subtract the final entry */
6670 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6672 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6673 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6675 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6678 /* If sub-DB still has entries, we're done */
6679 if (mc->mc_xcursor->mx_db.md_entries) {
6680 if (leaf->mn_flags & F_SUBDATA) {
6681 /* update subDB info */
6682 void *db = NODEDATA(leaf);
6683 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6686 /* shrink fake page */
6687 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6688 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6689 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6690 /* fix other sub-DB cursors pointed at this fake page */
6691 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6692 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6693 if (m2->mc_pg[mc->mc_top] == mp &&
6694 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6695 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6698 mc->mc_db->md_entries--;
6699 mc->mc_flags |= C_DEL;
6702 /* otherwise fall thru and delete the sub-DB */
6705 if (leaf->mn_flags & F_SUBDATA) {
6706 /* add all the child DB's pages to the free list */
6707 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6713 /* add overflow pages to free list */
6714 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6718 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6719 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6720 (rc = mdb_ovpage_free(mc, omp)))
6725 return mdb_cursor_del0(mc);
6728 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6732 /** Allocate and initialize new pages for a database.
6733 * @param[in] mc a cursor on the database being added to.
6734 * @param[in] flags flags defining what type of page is being allocated.
6735 * @param[in] num the number of pages to allocate. This is usually 1,
6736 * unless allocating overflow pages for a large record.
6737 * @param[out] mp Address of a page, or NULL on failure.
6738 * @return 0 on success, non-zero on failure.
6741 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6746 if ((rc = mdb_page_alloc(mc, num, &np)))
6748 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6749 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6750 np->mp_flags = flags | P_DIRTY;
6751 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
6752 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
6755 mc->mc_db->md_branch_pages++;
6756 else if (IS_LEAF(np))
6757 mc->mc_db->md_leaf_pages++;
6758 else if (IS_OVERFLOW(np)) {
6759 mc->mc_db->md_overflow_pages += num;
6767 /** Calculate the size of a leaf node.
6768 * The size depends on the environment's page size; if a data item
6769 * is too large it will be put onto an overflow page and the node
6770 * size will only include the key and not the data. Sizes are always
6771 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6772 * of the #MDB_node headers.
6773 * @param[in] env The environment handle.
6774 * @param[in] key The key for the node.
6775 * @param[in] data The data for the node.
6776 * @return The number of bytes needed to store the node.
6779 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6783 sz = LEAFSIZE(key, data);
6784 if (sz > env->me_nodemax) {
6785 /* put on overflow page */
6786 sz -= data->mv_size - sizeof(pgno_t);
6789 return EVEN(sz + sizeof(indx_t));
6792 /** Calculate the size of a branch node.
6793 * The size should depend on the environment's page size but since
6794 * we currently don't support spilling large keys onto overflow
6795 * pages, it's simply the size of the #MDB_node header plus the
6796 * size of the key. Sizes are always rounded up to an even number
6797 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6798 * @param[in] env The environment handle.
6799 * @param[in] key The key for the node.
6800 * @return The number of bytes needed to store the node.
6803 mdb_branch_size(MDB_env *env, MDB_val *key)
6808 if (sz > env->me_nodemax) {
6809 /* put on overflow page */
6810 /* not implemented */
6811 /* sz -= key->size - sizeof(pgno_t); */
6814 return sz + sizeof(indx_t);
6817 /** Add a node to the page pointed to by the cursor.
6818 * @param[in] mc The cursor for this operation.
6819 * @param[in] indx The index on the page where the new node should be added.
6820 * @param[in] key The key for the new node.
6821 * @param[in] data The data for the new node, if any.
6822 * @param[in] pgno The page number, if adding a branch node.
6823 * @param[in] flags Flags for the node.
6824 * @return 0 on success, non-zero on failure. Possible errors are:
6826 * <li>ENOMEM - failed to allocate overflow pages for the node.
6827 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6828 * should never happen since all callers already calculate the
6829 * page's free space before calling this function.
6833 mdb_node_add(MDB_cursor *mc, indx_t indx,
6834 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6837 size_t node_size = NODESIZE;
6841 MDB_page *mp = mc->mc_pg[mc->mc_top];
6842 MDB_page *ofp = NULL; /* overflow page */
6845 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
6847 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6848 IS_LEAF(mp) ? "leaf" : "branch",
6849 IS_SUBP(mp) ? "sub-" : "",
6850 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
6851 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6854 /* Move higher keys up one slot. */
6855 int ksize = mc->mc_db->md_pad, dif;
6856 char *ptr = LEAF2KEY(mp, indx, ksize);
6857 dif = NUMKEYS(mp) - indx;
6859 memmove(ptr+ksize, ptr, dif*ksize);
6860 /* insert new key */
6861 memcpy(ptr, key->mv_data, ksize);
6863 /* Just using these for counting */
6864 mp->mp_lower += sizeof(indx_t);
6865 mp->mp_upper -= ksize - sizeof(indx_t);
6869 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6871 node_size += key->mv_size;
6873 mdb_cassert(mc, data);
6874 if (F_ISSET(flags, F_BIGDATA)) {
6875 /* Data already on overflow page. */
6876 node_size += sizeof(pgno_t);
6877 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
6878 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6880 /* Put data on overflow page. */
6881 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6882 data->mv_size, node_size+data->mv_size));
6883 node_size = EVEN(node_size + sizeof(pgno_t));
6884 if ((ssize_t)node_size > room)
6886 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6888 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6892 node_size += data->mv_size;
6895 node_size = EVEN(node_size);
6896 if ((ssize_t)node_size > room)
6900 /* Move higher pointers up one slot. */
6901 for (i = NUMKEYS(mp); i > indx; i--)
6902 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6904 /* Adjust free space offsets. */
6905 ofs = mp->mp_upper - node_size;
6906 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
6907 mp->mp_ptrs[indx] = ofs;
6909 mp->mp_lower += sizeof(indx_t);
6911 /* Write the node data. */
6912 node = NODEPTR(mp, indx);
6913 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6914 node->mn_flags = flags;
6916 SETDSZ(node,data->mv_size);
6921 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6924 mdb_cassert(mc, key);
6926 if (F_ISSET(flags, F_BIGDATA))
6927 memcpy(node->mn_data + key->mv_size, data->mv_data,
6929 else if (F_ISSET(flags, MDB_RESERVE))
6930 data->mv_data = node->mn_data + key->mv_size;
6932 memcpy(node->mn_data + key->mv_size, data->mv_data,
6935 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6937 if (F_ISSET(flags, MDB_RESERVE))
6938 data->mv_data = METADATA(ofp);
6940 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6947 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6948 mdb_dbg_pgno(mp), NUMKEYS(mp)));
6949 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6950 DPRINTF(("node size = %"Z"u", node_size));
6951 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6952 return MDB_PAGE_FULL;
6955 /** Delete the specified node from a page.
6956 * @param[in] mc Cursor pointing to the node to delete.
6957 * @param[in] ksize The size of a node. Only used if the page is
6958 * part of a #MDB_DUPFIXED database.
6961 mdb_node_del(MDB_cursor *mc, int ksize)
6963 MDB_page *mp = mc->mc_pg[mc->mc_top];
6964 indx_t indx = mc->mc_ki[mc->mc_top];
6966 indx_t i, j, numkeys, ptr;
6970 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6971 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
6972 numkeys = NUMKEYS(mp);
6973 mdb_cassert(mc, indx < numkeys);
6976 int x = numkeys - 1 - indx;
6977 base = LEAF2KEY(mp, indx, ksize);
6979 memmove(base, base + ksize, x * ksize);
6980 mp->mp_lower -= sizeof(indx_t);
6981 mp->mp_upper += ksize - sizeof(indx_t);
6985 node = NODEPTR(mp, indx);
6986 sz = NODESIZE + node->mn_ksize;
6988 if (F_ISSET(node->mn_flags, F_BIGDATA))
6989 sz += sizeof(pgno_t);
6991 sz += NODEDSZ(node);
6995 ptr = mp->mp_ptrs[indx];
6996 for (i = j = 0; i < numkeys; i++) {
6998 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6999 if (mp->mp_ptrs[i] < ptr)
7000 mp->mp_ptrs[j] += sz;
7005 base = (char *)mp + mp->mp_upper + PAGEBASE;
7006 memmove(base + sz, base, ptr - mp->mp_upper);
7008 mp->mp_lower -= sizeof(indx_t);
7012 /** Compact the main page after deleting a node on a subpage.
7013 * @param[in] mp The main page to operate on.
7014 * @param[in] indx The index of the subpage on the main page.
7017 mdb_node_shrink(MDB_page *mp, indx_t indx)
7023 indx_t i, numkeys, ptr;
7025 node = NODEPTR(mp, indx);
7026 sp = (MDB_page *)NODEDATA(node);
7027 delta = SIZELEFT(sp);
7028 xp = (MDB_page *)((char *)sp + delta);
7030 /* shift subpage upward */
7032 nsize = NUMKEYS(sp) * sp->mp_pad;
7034 return; /* do not make the node uneven-sized */
7035 memmove(METADATA(xp), METADATA(sp), nsize);
7038 numkeys = NUMKEYS(sp);
7039 for (i=numkeys-1; i>=0; i--)
7040 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
7042 xp->mp_upper = sp->mp_lower;
7043 xp->mp_lower = sp->mp_lower;
7044 xp->mp_flags = sp->mp_flags;
7045 xp->mp_pad = sp->mp_pad;
7046 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
7048 nsize = NODEDSZ(node) - delta;
7049 SETDSZ(node, nsize);
7051 /* shift lower nodes upward */
7052 ptr = mp->mp_ptrs[indx];
7053 numkeys = NUMKEYS(mp);
7054 for (i = 0; i < numkeys; i++) {
7055 if (mp->mp_ptrs[i] <= ptr)
7056 mp->mp_ptrs[i] += delta;
7059 base = (char *)mp + mp->mp_upper + PAGEBASE;
7060 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
7061 mp->mp_upper += delta;
7064 /** Initial setup of a sorted-dups cursor.
7065 * Sorted duplicates are implemented as a sub-database for the given key.
7066 * The duplicate data items are actually keys of the sub-database.
7067 * Operations on the duplicate data items are performed using a sub-cursor
7068 * initialized when the sub-database is first accessed. This function does
7069 * the preliminary setup of the sub-cursor, filling in the fields that
7070 * depend only on the parent DB.
7071 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7074 mdb_xcursor_init0(MDB_cursor *mc)
7076 MDB_xcursor *mx = mc->mc_xcursor;
7078 mx->mx_cursor.mc_xcursor = NULL;
7079 mx->mx_cursor.mc_txn = mc->mc_txn;
7080 mx->mx_cursor.mc_db = &mx->mx_db;
7081 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
7082 mx->mx_cursor.mc_dbi = mc->mc_dbi;
7083 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
7084 mx->mx_cursor.mc_snum = 0;
7085 mx->mx_cursor.mc_top = 0;
7086 mx->mx_cursor.mc_flags = C_SUB;
7087 mx->mx_dbx.md_name.mv_size = 0;
7088 mx->mx_dbx.md_name.mv_data = NULL;
7089 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
7090 mx->mx_dbx.md_dcmp = NULL;
7091 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
7094 /** Final setup of a sorted-dups cursor.
7095 * Sets up the fields that depend on the data from the main cursor.
7096 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7097 * @param[in] node The data containing the #MDB_db record for the
7098 * sorted-dup database.
7101 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
7103 MDB_xcursor *mx = mc->mc_xcursor;
7105 if (node->mn_flags & F_SUBDATA) {
7106 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
7107 mx->mx_cursor.mc_pg[0] = 0;
7108 mx->mx_cursor.mc_snum = 0;
7109 mx->mx_cursor.mc_top = 0;
7110 mx->mx_cursor.mc_flags = C_SUB;
7112 MDB_page *fp = NODEDATA(node);
7113 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
7114 mx->mx_db.md_flags = 0;
7115 mx->mx_db.md_depth = 1;
7116 mx->mx_db.md_branch_pages = 0;
7117 mx->mx_db.md_leaf_pages = 1;
7118 mx->mx_db.md_overflow_pages = 0;
7119 mx->mx_db.md_entries = NUMKEYS(fp);
7120 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
7121 mx->mx_cursor.mc_snum = 1;
7122 mx->mx_cursor.mc_top = 0;
7123 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
7124 mx->mx_cursor.mc_pg[0] = fp;
7125 mx->mx_cursor.mc_ki[0] = 0;
7126 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7127 mx->mx_db.md_flags = MDB_DUPFIXED;
7128 mx->mx_db.md_pad = fp->mp_pad;
7129 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7130 mx->mx_db.md_flags |= MDB_INTEGERKEY;
7133 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7134 mx->mx_db.md_root));
7135 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
7136 #if UINT_MAX < SIZE_MAX
7137 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
7138 mx->mx_dbx.md_cmp = mdb_cmp_clong;
7142 /** Initialize a cursor for a given transaction and database. */
7144 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
7147 mc->mc_backup = NULL;
7150 mc->mc_db = &txn->mt_dbs[dbi];
7151 mc->mc_dbx = &txn->mt_dbxs[dbi];
7152 mc->mc_dbflag = &txn->mt_dbflags[dbi];
7157 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
7158 mdb_tassert(txn, mx != NULL);
7159 mc->mc_xcursor = mx;
7160 mdb_xcursor_init0(mc);
7162 mc->mc_xcursor = NULL;
7164 if (*mc->mc_dbflag & DB_STALE) {
7165 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
7170 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
7173 size_t size = sizeof(MDB_cursor);
7175 if (!ret || !TXN_DBI_EXIST(txn, dbi))
7178 if (txn->mt_flags & MDB_TXN_ERROR)
7181 /* Allow read access to the freelist */
7182 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7185 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
7186 size += sizeof(MDB_xcursor);
7188 if ((mc = malloc(size)) != NULL) {
7189 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
7190 if (txn->mt_cursors) {
7191 mc->mc_next = txn->mt_cursors[dbi];
7192 txn->mt_cursors[dbi] = mc;
7193 mc->mc_flags |= C_UNTRACK;
7205 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
7207 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi))
7210 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
7213 if (txn->mt_flags & MDB_TXN_ERROR)
7216 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
7220 /* Return the count of duplicate data items for the current key */
7222 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7226 if (mc == NULL || countp == NULL)
7229 if (mc->mc_xcursor == NULL)
7230 return MDB_INCOMPATIBLE;
7232 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
7235 if (!(mc->mc_flags & C_INITIALIZED))
7238 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
7239 return MDB_NOTFOUND;
7241 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7242 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7245 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7248 *countp = mc->mc_xcursor->mx_db.md_entries;
7254 mdb_cursor_close(MDB_cursor *mc)
7256 if (mc && !mc->mc_backup) {
7257 /* remove from txn, if tracked */
7258 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7259 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7260 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7262 *prev = mc->mc_next;
7269 mdb_cursor_txn(MDB_cursor *mc)
7271 if (!mc) return NULL;
7276 mdb_cursor_dbi(MDB_cursor *mc)
7281 /** Replace the key for a branch node with a new key.
7282 * @param[in] mc Cursor pointing to the node to operate on.
7283 * @param[in] key The new key to use.
7284 * @return 0 on success, non-zero on failure.
7287 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7293 int delta, ksize, oksize;
7294 indx_t ptr, i, numkeys, indx;
7297 indx = mc->mc_ki[mc->mc_top];
7298 mp = mc->mc_pg[mc->mc_top];
7299 node = NODEPTR(mp, indx);
7300 ptr = mp->mp_ptrs[indx];
7304 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7305 k2.mv_data = NODEKEY(node);
7306 k2.mv_size = node->mn_ksize;
7307 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7309 mdb_dkey(&k2, kbuf2),
7315 /* Sizes must be 2-byte aligned. */
7316 ksize = EVEN(key->mv_size);
7317 oksize = EVEN(node->mn_ksize);
7318 delta = ksize - oksize;
7320 /* Shift node contents if EVEN(key length) changed. */
7322 if (delta > 0 && SIZELEFT(mp) < delta) {
7324 /* not enough space left, do a delete and split */
7325 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7326 pgno = NODEPGNO(node);
7327 mdb_node_del(mc, 0);
7328 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7331 numkeys = NUMKEYS(mp);
7332 for (i = 0; i < numkeys; i++) {
7333 if (mp->mp_ptrs[i] <= ptr)
7334 mp->mp_ptrs[i] -= delta;
7337 base = (char *)mp + mp->mp_upper + PAGEBASE;
7338 len = ptr - mp->mp_upper + NODESIZE;
7339 memmove(base - delta, base, len);
7340 mp->mp_upper -= delta;
7342 node = NODEPTR(mp, indx);
7345 /* But even if no shift was needed, update ksize */
7346 if (node->mn_ksize != key->mv_size)
7347 node->mn_ksize = key->mv_size;
7350 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7356 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7358 /** Move a node from csrc to cdst.
7361 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
7368 unsigned short flags;
7372 /* Mark src and dst as dirty. */
7373 if ((rc = mdb_page_touch(csrc)) ||
7374 (rc = mdb_page_touch(cdst)))
7377 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7378 key.mv_size = csrc->mc_db->md_pad;
7379 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7381 data.mv_data = NULL;
7385 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7386 mdb_cassert(csrc, !((size_t)srcnode & 1));
7387 srcpg = NODEPGNO(srcnode);
7388 flags = srcnode->mn_flags;
7389 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7390 unsigned int snum = csrc->mc_snum;
7392 /* must find the lowest key below src */
7393 rc = mdb_page_search_lowest(csrc);
7396 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7397 key.mv_size = csrc->mc_db->md_pad;
7398 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7400 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7401 key.mv_size = NODEKSZ(s2);
7402 key.mv_data = NODEKEY(s2);
7404 csrc->mc_snum = snum--;
7405 csrc->mc_top = snum;
7407 key.mv_size = NODEKSZ(srcnode);
7408 key.mv_data = NODEKEY(srcnode);
7410 data.mv_size = NODEDSZ(srcnode);
7411 data.mv_data = NODEDATA(srcnode);
7413 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7414 unsigned int snum = cdst->mc_snum;
7417 /* must find the lowest key below dst */
7418 mdb_cursor_copy(cdst, &mn);
7419 rc = mdb_page_search_lowest(&mn);
7422 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7423 bkey.mv_size = mn.mc_db->md_pad;
7424 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7426 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7427 bkey.mv_size = NODEKSZ(s2);
7428 bkey.mv_data = NODEKEY(s2);
7430 mn.mc_snum = snum--;
7433 rc = mdb_update_key(&mn, &bkey);
7438 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7439 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7440 csrc->mc_ki[csrc->mc_top],
7442 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7443 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7445 /* Add the node to the destination page.
7447 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7448 if (rc != MDB_SUCCESS)
7451 /* Delete the node from the source page.
7453 mdb_node_del(csrc, key.mv_size);
7456 /* Adjust other cursors pointing to mp */
7457 MDB_cursor *m2, *m3;
7458 MDB_dbi dbi = csrc->mc_dbi;
7459 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
7461 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7462 if (csrc->mc_flags & C_SUB)
7463 m3 = &m2->mc_xcursor->mx_cursor;
7466 if (m3 == csrc) continue;
7467 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
7468 csrc->mc_ki[csrc->mc_top]) {
7469 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7470 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7475 /* Update the parent separators.
7477 if (csrc->mc_ki[csrc->mc_top] == 0) {
7478 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7479 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7480 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7482 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7483 key.mv_size = NODEKSZ(srcnode);
7484 key.mv_data = NODEKEY(srcnode);
7486 DPRINTF(("update separator for source page %"Z"u to [%s]",
7487 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7488 mdb_cursor_copy(csrc, &mn);
7491 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7494 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7496 indx_t ix = csrc->mc_ki[csrc->mc_top];
7497 nullkey.mv_size = 0;
7498 csrc->mc_ki[csrc->mc_top] = 0;
7499 rc = mdb_update_key(csrc, &nullkey);
7500 csrc->mc_ki[csrc->mc_top] = ix;
7501 mdb_cassert(csrc, rc == MDB_SUCCESS);
7505 if (cdst->mc_ki[cdst->mc_top] == 0) {
7506 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7507 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7508 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7510 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7511 key.mv_size = NODEKSZ(srcnode);
7512 key.mv_data = NODEKEY(srcnode);
7514 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7515 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7516 mdb_cursor_copy(cdst, &mn);
7519 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7522 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7524 indx_t ix = cdst->mc_ki[cdst->mc_top];
7525 nullkey.mv_size = 0;
7526 cdst->mc_ki[cdst->mc_top] = 0;
7527 rc = mdb_update_key(cdst, &nullkey);
7528 cdst->mc_ki[cdst->mc_top] = ix;
7529 mdb_cassert(csrc, rc == MDB_SUCCESS);
7536 /** Merge one page into another.
7537 * The nodes from the page pointed to by \b csrc will
7538 * be copied to the page pointed to by \b cdst and then
7539 * the \b csrc page will be freed.
7540 * @param[in] csrc Cursor pointing to the source page.
7541 * @param[in] cdst Cursor pointing to the destination page.
7542 * @return 0 on success, non-zero on failure.
7545 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7547 MDB_page *psrc, *pdst;
7554 psrc = csrc->mc_pg[csrc->mc_top];
7555 pdst = cdst->mc_pg[cdst->mc_top];
7557 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7559 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7560 mdb_cassert(csrc, cdst->mc_snum > 1);
7562 /* Mark dst as dirty. */
7563 if ((rc = mdb_page_touch(cdst)))
7566 /* Move all nodes from src to dst.
7568 j = nkeys = NUMKEYS(pdst);
7569 if (IS_LEAF2(psrc)) {
7570 key.mv_size = csrc->mc_db->md_pad;
7571 key.mv_data = METADATA(psrc);
7572 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7573 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7574 if (rc != MDB_SUCCESS)
7576 key.mv_data = (char *)key.mv_data + key.mv_size;
7579 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7580 srcnode = NODEPTR(psrc, i);
7581 if (i == 0 && IS_BRANCH(psrc)) {
7584 mdb_cursor_copy(csrc, &mn);
7585 /* must find the lowest key below src */
7586 rc = mdb_page_search_lowest(&mn);
7589 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7590 key.mv_size = mn.mc_db->md_pad;
7591 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7593 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7594 key.mv_size = NODEKSZ(s2);
7595 key.mv_data = NODEKEY(s2);
7598 key.mv_size = srcnode->mn_ksize;
7599 key.mv_data = NODEKEY(srcnode);
7602 data.mv_size = NODEDSZ(srcnode);
7603 data.mv_data = NODEDATA(srcnode);
7604 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7605 if (rc != MDB_SUCCESS)
7610 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7611 pdst->mp_pgno, NUMKEYS(pdst),
7612 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7614 /* Unlink the src page from parent and add to free list.
7617 mdb_node_del(csrc, 0);
7618 if (csrc->mc_ki[csrc->mc_top] == 0) {
7620 rc = mdb_update_key(csrc, &key);
7628 psrc = csrc->mc_pg[csrc->mc_top];
7629 /* If not operating on FreeDB, allow this page to be reused
7630 * in this txn. Otherwise just add to free list.
7632 rc = mdb_page_loose(csrc, psrc);
7636 csrc->mc_db->md_leaf_pages--;
7638 csrc->mc_db->md_branch_pages--;
7640 /* Adjust other cursors pointing to mp */
7641 MDB_cursor *m2, *m3;
7642 MDB_dbi dbi = csrc->mc_dbi;
7644 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7645 if (csrc->mc_flags & C_SUB)
7646 m3 = &m2->mc_xcursor->mx_cursor;
7649 if (m3 == csrc) continue;
7650 if (m3->mc_snum < csrc->mc_snum) continue;
7651 if (m3->mc_pg[csrc->mc_top] == psrc) {
7652 m3->mc_pg[csrc->mc_top] = pdst;
7653 m3->mc_ki[csrc->mc_top] += nkeys;
7658 unsigned int snum = cdst->mc_snum;
7659 uint16_t depth = cdst->mc_db->md_depth;
7660 mdb_cursor_pop(cdst);
7661 rc = mdb_rebalance(cdst);
7662 /* Did the tree shrink? */
7663 if (depth > cdst->mc_db->md_depth)
7665 cdst->mc_snum = snum;
7666 cdst->mc_top = snum-1;
7671 /** Copy the contents of a cursor.
7672 * @param[in] csrc The cursor to copy from.
7673 * @param[out] cdst The cursor to copy to.
7676 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7680 cdst->mc_txn = csrc->mc_txn;
7681 cdst->mc_dbi = csrc->mc_dbi;
7682 cdst->mc_db = csrc->mc_db;
7683 cdst->mc_dbx = csrc->mc_dbx;
7684 cdst->mc_snum = csrc->mc_snum;
7685 cdst->mc_top = csrc->mc_top;
7686 cdst->mc_flags = csrc->mc_flags;
7688 for (i=0; i<csrc->mc_snum; i++) {
7689 cdst->mc_pg[i] = csrc->mc_pg[i];
7690 cdst->mc_ki[i] = csrc->mc_ki[i];
7694 /** Rebalance the tree after a delete operation.
7695 * @param[in] mc Cursor pointing to the page where rebalancing
7697 * @return 0 on success, non-zero on failure.
7700 mdb_rebalance(MDB_cursor *mc)
7704 unsigned int ptop, minkeys;
7708 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7709 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7710 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7711 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7712 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7714 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7715 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7716 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7717 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7721 if (mc->mc_snum < 2) {
7722 MDB_page *mp = mc->mc_pg[0];
7724 DPUTS("Can't rebalance a subpage, ignoring");
7727 if (NUMKEYS(mp) == 0) {
7728 DPUTS("tree is completely empty");
7729 mc->mc_db->md_root = P_INVALID;
7730 mc->mc_db->md_depth = 0;
7731 mc->mc_db->md_leaf_pages = 0;
7732 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7735 /* Adjust cursors pointing to mp */
7738 mc->mc_flags &= ~C_INITIALIZED;
7740 MDB_cursor *m2, *m3;
7741 MDB_dbi dbi = mc->mc_dbi;
7743 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7744 if (mc->mc_flags & C_SUB)
7745 m3 = &m2->mc_xcursor->mx_cursor;
7748 if (m3->mc_snum < mc->mc_snum) continue;
7749 if (m3->mc_pg[0] == mp) {
7752 m3->mc_flags &= ~C_INITIALIZED;
7756 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7758 DPUTS("collapsing root page!");
7759 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7762 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7763 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7766 mc->mc_db->md_depth--;
7767 mc->mc_db->md_branch_pages--;
7768 mc->mc_ki[0] = mc->mc_ki[1];
7769 for (i = 1; i<mc->mc_db->md_depth; i++) {
7770 mc->mc_pg[i] = mc->mc_pg[i+1];
7771 mc->mc_ki[i] = mc->mc_ki[i+1];
7774 /* Adjust other cursors pointing to mp */
7775 MDB_cursor *m2, *m3;
7776 MDB_dbi dbi = mc->mc_dbi;
7778 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7779 if (mc->mc_flags & C_SUB)
7780 m3 = &m2->mc_xcursor->mx_cursor;
7783 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7784 if (m3->mc_pg[0] == mp) {
7787 for (i=0; i<m3->mc_snum; i++) {
7788 m3->mc_pg[i] = m3->mc_pg[i+1];
7789 m3->mc_ki[i] = m3->mc_ki[i+1];
7795 DPUTS("root page doesn't need rebalancing");
7799 /* The parent (branch page) must have at least 2 pointers,
7800 * otherwise the tree is invalid.
7802 ptop = mc->mc_top-1;
7803 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
7805 /* Leaf page fill factor is below the threshold.
7806 * Try to move keys from left or right neighbor, or
7807 * merge with a neighbor page.
7812 mdb_cursor_copy(mc, &mn);
7813 mn.mc_xcursor = NULL;
7815 oldki = mc->mc_ki[mc->mc_top];
7816 if (mc->mc_ki[ptop] == 0) {
7817 /* We're the leftmost leaf in our parent.
7819 DPUTS("reading right neighbor");
7821 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7822 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7825 mn.mc_ki[mn.mc_top] = 0;
7826 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7828 /* There is at least one neighbor to the left.
7830 DPUTS("reading left neighbor");
7832 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7833 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7836 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7837 mc->mc_ki[mc->mc_top] = 0;
7840 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7841 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7842 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7844 /* If the neighbor page is above threshold and has enough keys,
7845 * move one key from it. Otherwise we should try to merge them.
7846 * (A branch page must never have less than 2 keys.)
7848 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7849 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
7850 rc = mdb_node_move(&mn, mc);
7851 if (mc->mc_ki[ptop]) {
7855 if (mc->mc_ki[ptop] == 0) {
7856 rc = mdb_page_merge(&mn, mc);
7858 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
7859 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7860 rc = mdb_page_merge(mc, &mn);
7861 mdb_cursor_copy(&mn, mc);
7863 mc->mc_flags &= ~C_EOF;
7865 mc->mc_ki[mc->mc_top] = oldki;
7869 /** Complete a delete operation started by #mdb_cursor_del(). */
7871 mdb_cursor_del0(MDB_cursor *mc)
7878 ki = mc->mc_ki[mc->mc_top];
7879 mdb_node_del(mc, mc->mc_db->md_pad);
7880 mc->mc_db->md_entries--;
7881 rc = mdb_rebalance(mc);
7883 if (rc == MDB_SUCCESS) {
7884 MDB_cursor *m2, *m3;
7885 MDB_dbi dbi = mc->mc_dbi;
7887 mp = mc->mc_pg[mc->mc_top];
7888 nkeys = NUMKEYS(mp);
7890 /* if mc points past last node in page, find next sibling */
7891 if (mc->mc_ki[mc->mc_top] >= nkeys) {
7892 rc = mdb_cursor_sibling(mc, 1);
7893 if (rc == MDB_NOTFOUND) {
7894 mc->mc_flags |= C_EOF;
7899 /* Adjust other cursors pointing to mp */
7900 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
7901 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
7902 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7904 if (m3 == mc || m3->mc_snum < mc->mc_snum)
7906 if (m3->mc_pg[mc->mc_top] == mp) {
7907 if (m3->mc_ki[mc->mc_top] >= ki) {
7908 m3->mc_flags |= C_DEL;
7909 if (m3->mc_ki[mc->mc_top] > ki)
7910 m3->mc_ki[mc->mc_top]--;
7911 else if (mc->mc_db->md_flags & MDB_DUPSORT)
7912 m3->mc_xcursor->mx_cursor.mc_flags |= C_EOF;
7914 if (m3->mc_ki[mc->mc_top] >= nkeys) {
7915 rc = mdb_cursor_sibling(m3, 1);
7916 if (rc == MDB_NOTFOUND) {
7917 m3->mc_flags |= C_EOF;
7923 mc->mc_flags |= C_DEL;
7927 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7932 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7933 MDB_val *key, MDB_val *data)
7935 if (!key || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
7938 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7939 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7941 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7942 /* must ignore any data */
7946 return mdb_del0(txn, dbi, key, data, 0);
7950 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
7951 MDB_val *key, MDB_val *data, unsigned flags)
7956 MDB_val rdata, *xdata;
7960 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7962 mdb_cursor_init(&mc, txn, dbi, &mx);
7971 flags |= MDB_NODUPDATA;
7973 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7975 /* let mdb_page_split know about this cursor if needed:
7976 * delete will trigger a rebalance; if it needs to move
7977 * a node from one page to another, it will have to
7978 * update the parent's separator key(s). If the new sepkey
7979 * is larger than the current one, the parent page may
7980 * run out of space, triggering a split. We need this
7981 * cursor to be consistent until the end of the rebalance.
7983 mc.mc_flags |= C_UNTRACK;
7984 mc.mc_next = txn->mt_cursors[dbi];
7985 txn->mt_cursors[dbi] = &mc;
7986 rc = mdb_cursor_del(&mc, flags);
7987 txn->mt_cursors[dbi] = mc.mc_next;
7992 /** Split a page and insert a new node.
7993 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7994 * The cursor will be updated to point to the actual page and index where
7995 * the node got inserted after the split.
7996 * @param[in] newkey The key for the newly inserted node.
7997 * @param[in] newdata The data for the newly inserted node.
7998 * @param[in] newpgno The page number, if the new node is a branch node.
7999 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
8000 * @return 0 on success, non-zero on failure.
8003 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
8004 unsigned int nflags)
8007 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
8010 int i, j, split_indx, nkeys, pmax;
8011 MDB_env *env = mc->mc_txn->mt_env;
8013 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
8014 MDB_page *copy = NULL;
8015 MDB_page *mp, *rp, *pp;
8020 mp = mc->mc_pg[mc->mc_top];
8021 newindx = mc->mc_ki[mc->mc_top];
8022 nkeys = NUMKEYS(mp);
8024 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
8025 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
8026 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
8028 /* Create a right sibling. */
8029 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
8031 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
8033 if (mc->mc_snum < 2) {
8034 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
8036 /* shift current top to make room for new parent */
8037 mc->mc_pg[1] = mc->mc_pg[0];
8038 mc->mc_ki[1] = mc->mc_ki[0];
8041 mc->mc_db->md_root = pp->mp_pgno;
8042 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
8043 mc->mc_db->md_depth++;
8046 /* Add left (implicit) pointer. */
8047 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
8048 /* undo the pre-push */
8049 mc->mc_pg[0] = mc->mc_pg[1];
8050 mc->mc_ki[0] = mc->mc_ki[1];
8051 mc->mc_db->md_root = mp->mp_pgno;
8052 mc->mc_db->md_depth--;
8059 ptop = mc->mc_top-1;
8060 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
8063 mc->mc_flags |= C_SPLITTING;
8064 mdb_cursor_copy(mc, &mn);
8065 mn.mc_pg[mn.mc_top] = rp;
8066 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
8068 if (nflags & MDB_APPEND) {
8069 mn.mc_ki[mn.mc_top] = 0;
8071 split_indx = newindx;
8075 split_indx = (nkeys+1) / 2;
8080 unsigned int lsize, rsize, ksize;
8081 /* Move half of the keys to the right sibling */
8082 x = mc->mc_ki[mc->mc_top] - split_indx;
8083 ksize = mc->mc_db->md_pad;
8084 split = LEAF2KEY(mp, split_indx, ksize);
8085 rsize = (nkeys - split_indx) * ksize;
8086 lsize = (nkeys - split_indx) * sizeof(indx_t);
8087 mp->mp_lower -= lsize;
8088 rp->mp_lower += lsize;
8089 mp->mp_upper += rsize - lsize;
8090 rp->mp_upper -= rsize - lsize;
8091 sepkey.mv_size = ksize;
8092 if (newindx == split_indx) {
8093 sepkey.mv_data = newkey->mv_data;
8095 sepkey.mv_data = split;
8098 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
8099 memcpy(rp->mp_ptrs, split, rsize);
8100 sepkey.mv_data = rp->mp_ptrs;
8101 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
8102 memcpy(ins, newkey->mv_data, ksize);
8103 mp->mp_lower += sizeof(indx_t);
8104 mp->mp_upper -= ksize - sizeof(indx_t);
8107 memcpy(rp->mp_ptrs, split, x * ksize);
8108 ins = LEAF2KEY(rp, x, ksize);
8109 memcpy(ins, newkey->mv_data, ksize);
8110 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
8111 rp->mp_lower += sizeof(indx_t);
8112 rp->mp_upper -= ksize - sizeof(indx_t);
8113 mc->mc_ki[mc->mc_top] = x;
8114 mc->mc_pg[mc->mc_top] = rp;
8117 int psize, nsize, k;
8118 /* Maximum free space in an empty page */
8119 pmax = env->me_psize - PAGEHDRSZ;
8121 nsize = mdb_leaf_size(env, newkey, newdata);
8123 nsize = mdb_branch_size(env, newkey);
8124 nsize = EVEN(nsize);
8126 /* grab a page to hold a temporary copy */
8127 copy = mdb_page_malloc(mc->mc_txn, 1);
8132 copy->mp_pgno = mp->mp_pgno;
8133 copy->mp_flags = mp->mp_flags;
8134 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
8135 copy->mp_upper = env->me_psize - PAGEBASE;
8137 /* prepare to insert */
8138 for (i=0, j=0; i<nkeys; i++) {
8140 copy->mp_ptrs[j++] = 0;
8142 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
8145 /* When items are relatively large the split point needs
8146 * to be checked, because being off-by-one will make the
8147 * difference between success or failure in mdb_node_add.
8149 * It's also relevant if a page happens to be laid out
8150 * such that one half of its nodes are all "small" and
8151 * the other half of its nodes are "large." If the new
8152 * item is also "large" and falls on the half with
8153 * "large" nodes, it also may not fit.
8155 * As a final tweak, if the new item goes on the last
8156 * spot on the page (and thus, onto the new page), bias
8157 * the split so the new page is emptier than the old page.
8158 * This yields better packing during sequential inserts.
8160 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
8161 /* Find split point */
8163 if (newindx <= split_indx || newindx >= nkeys) {
8165 k = newindx >= nkeys ? nkeys : split_indx+2;
8170 for (; i!=k; i+=j) {
8175 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8176 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
8178 if (F_ISSET(node->mn_flags, F_BIGDATA))
8179 psize += sizeof(pgno_t);
8181 psize += NODEDSZ(node);
8183 psize = EVEN(psize);
8185 if (psize > pmax || i == k-j) {
8186 split_indx = i + (j<0);
8191 if (split_indx == newindx) {
8192 sepkey.mv_size = newkey->mv_size;
8193 sepkey.mv_data = newkey->mv_data;
8195 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
8196 sepkey.mv_size = node->mn_ksize;
8197 sepkey.mv_data = NODEKEY(node);
8202 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
8204 /* Copy separator key to the parent.
8206 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
8210 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
8215 if (mn.mc_snum == mc->mc_snum) {
8216 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
8217 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
8218 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
8219 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
8224 /* Right page might now have changed parent.
8225 * Check if left page also changed parent.
8227 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8228 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8229 for (i=0; i<ptop; i++) {
8230 mc->mc_pg[i] = mn.mc_pg[i];
8231 mc->mc_ki[i] = mn.mc_ki[i];
8233 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8234 if (mn.mc_ki[ptop]) {
8235 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8237 /* find right page's left sibling */
8238 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8239 mdb_cursor_sibling(mc, 0);
8244 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8247 mc->mc_flags ^= C_SPLITTING;
8248 if (rc != MDB_SUCCESS) {
8251 if (nflags & MDB_APPEND) {
8252 mc->mc_pg[mc->mc_top] = rp;
8253 mc->mc_ki[mc->mc_top] = 0;
8254 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8257 for (i=0; i<mc->mc_top; i++)
8258 mc->mc_ki[i] = mn.mc_ki[i];
8259 } else if (!IS_LEAF2(mp)) {
8261 mc->mc_pg[mc->mc_top] = rp;
8266 rkey.mv_data = newkey->mv_data;
8267 rkey.mv_size = newkey->mv_size;
8273 /* Update index for the new key. */
8274 mc->mc_ki[mc->mc_top] = j;
8276 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8277 rkey.mv_data = NODEKEY(node);
8278 rkey.mv_size = node->mn_ksize;
8280 xdata.mv_data = NODEDATA(node);
8281 xdata.mv_size = NODEDSZ(node);
8284 pgno = NODEPGNO(node);
8285 flags = node->mn_flags;
8288 if (!IS_LEAF(mp) && j == 0) {
8289 /* First branch index doesn't need key data. */
8293 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8299 mc->mc_pg[mc->mc_top] = copy;
8304 } while (i != split_indx);
8306 nkeys = NUMKEYS(copy);
8307 for (i=0; i<nkeys; i++)
8308 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8309 mp->mp_lower = copy->mp_lower;
8310 mp->mp_upper = copy->mp_upper;
8311 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8312 env->me_psize - copy->mp_upper - PAGEBASE);
8314 /* reset back to original page */
8315 if (newindx < split_indx) {
8316 mc->mc_pg[mc->mc_top] = mp;
8317 if (nflags & MDB_RESERVE) {
8318 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
8319 if (!(node->mn_flags & F_BIGDATA))
8320 newdata->mv_data = NODEDATA(node);
8323 mc->mc_pg[mc->mc_top] = rp;
8325 /* Make sure mc_ki is still valid.
8327 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8328 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8329 for (i=0; i<=ptop; i++) {
8330 mc->mc_pg[i] = mn.mc_pg[i];
8331 mc->mc_ki[i] = mn.mc_ki[i];
8338 /* Adjust other cursors pointing to mp */
8339 MDB_cursor *m2, *m3;
8340 MDB_dbi dbi = mc->mc_dbi;
8341 int fixup = NUMKEYS(mp);
8343 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8344 if (mc->mc_flags & C_SUB)
8345 m3 = &m2->mc_xcursor->mx_cursor;
8350 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8352 if (m3->mc_flags & C_SPLITTING)
8357 for (k=m3->mc_top; k>=0; k--) {
8358 m3->mc_ki[k+1] = m3->mc_ki[k];
8359 m3->mc_pg[k+1] = m3->mc_pg[k];
8361 if (m3->mc_ki[0] >= split_indx) {
8366 m3->mc_pg[0] = mc->mc_pg[0];
8370 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8371 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8372 m3->mc_ki[mc->mc_top]++;
8373 if (m3->mc_ki[mc->mc_top] >= fixup) {
8374 m3->mc_pg[mc->mc_top] = rp;
8375 m3->mc_ki[mc->mc_top] -= fixup;
8376 m3->mc_ki[ptop] = mn.mc_ki[ptop];
8378 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8379 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8384 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8387 if (copy) /* tmp page */
8388 mdb_page_free(env, copy);
8390 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8395 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8396 MDB_val *key, MDB_val *data, unsigned int flags)
8401 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8404 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
8407 mdb_cursor_init(&mc, txn, dbi, &mx);
8408 return mdb_cursor_put(&mc, key, data, flags);
8412 #define MDB_WBUF (1024*1024)
8415 /** State needed for a compacting copy. */
8416 typedef struct mdb_copy {
8417 pthread_mutex_t mc_mutex;
8418 pthread_cond_t mc_cond;
8425 pgno_t mc_next_pgno;
8428 volatile int mc_new;
8433 /** Dedicated writer thread for compacting copy. */
8434 static THREAD_RET ESECT
8435 mdb_env_copythr(void *arg)
8439 int toggle = 0, wsize, rc;
8442 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8445 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8448 pthread_mutex_lock(&my->mc_mutex);
8450 pthread_cond_signal(&my->mc_cond);
8453 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8454 if (my->mc_new < 0) {
8459 wsize = my->mc_wlen[toggle];
8460 ptr = my->mc_wbuf[toggle];
8463 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8467 } else if (len > 0) {
8481 /* If there's an overflow page tail, write it too */
8482 if (my->mc_olen[toggle]) {
8483 wsize = my->mc_olen[toggle];
8484 ptr = my->mc_over[toggle];
8485 my->mc_olen[toggle] = 0;
8488 my->mc_wlen[toggle] = 0;
8490 pthread_cond_signal(&my->mc_cond);
8492 pthread_cond_signal(&my->mc_cond);
8493 pthread_mutex_unlock(&my->mc_mutex);
8494 return (THREAD_RET)0;
8498 /** Tell the writer thread there's a buffer ready to write */
8500 mdb_env_cthr_toggle(mdb_copy *my, int st)
8502 int toggle = my->mc_toggle ^ 1;
8503 pthread_mutex_lock(&my->mc_mutex);
8504 if (my->mc_status) {
8505 pthread_mutex_unlock(&my->mc_mutex);
8506 return my->mc_status;
8508 while (my->mc_new == 1)
8509 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8511 my->mc_toggle = toggle;
8512 pthread_cond_signal(&my->mc_cond);
8513 pthread_mutex_unlock(&my->mc_mutex);
8517 /** Depth-first tree traversal for compacting copy. */
8519 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8522 MDB_txn *txn = my->mc_txn;
8524 MDB_page *mo, *mp, *leaf;
8529 /* Empty DB, nothing to do */
8530 if (*pg == P_INVALID)
8537 rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
8540 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8544 /* Make cursor pages writable */
8545 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8549 for (i=0; i<mc.mc_top; i++) {
8550 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8551 mc.mc_pg[i] = (MDB_page *)ptr;
8552 ptr += my->mc_env->me_psize;
8555 /* This is writable space for a leaf page. Usually not needed. */
8556 leaf = (MDB_page *)ptr;
8558 toggle = my->mc_toggle;
8559 while (mc.mc_snum > 0) {
8561 mp = mc.mc_pg[mc.mc_top];
8565 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8566 for (i=0; i<n; i++) {
8567 ni = NODEPTR(mp, i);
8568 if (ni->mn_flags & F_BIGDATA) {
8572 /* Need writable leaf */
8574 mc.mc_pg[mc.mc_top] = leaf;
8575 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8577 ni = NODEPTR(mp, i);
8580 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8581 rc = mdb_page_get(txn, pg, &omp, NULL);
8584 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8585 rc = mdb_env_cthr_toggle(my, 1);
8588 toggle = my->mc_toggle;
8590 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8591 memcpy(mo, omp, my->mc_env->me_psize);
8592 mo->mp_pgno = my->mc_next_pgno;
8593 my->mc_next_pgno += omp->mp_pages;
8594 my->mc_wlen[toggle] += my->mc_env->me_psize;
8595 if (omp->mp_pages > 1) {
8596 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
8597 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
8598 rc = mdb_env_cthr_toggle(my, 1);
8601 toggle = my->mc_toggle;
8603 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
8604 } else if (ni->mn_flags & F_SUBDATA) {
8607 /* Need writable leaf */
8609 mc.mc_pg[mc.mc_top] = leaf;
8610 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8612 ni = NODEPTR(mp, i);
8615 memcpy(&db, NODEDATA(ni), sizeof(db));
8616 my->mc_toggle = toggle;
8617 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
8620 toggle = my->mc_toggle;
8621 memcpy(NODEDATA(ni), &db, sizeof(db));
8626 mc.mc_ki[mc.mc_top]++;
8627 if (mc.mc_ki[mc.mc_top] < n) {
8630 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
8632 rc = mdb_page_get(txn, pg, &mp, NULL);
8637 mc.mc_ki[mc.mc_top] = 0;
8638 if (IS_BRANCH(mp)) {
8639 /* Whenever we advance to a sibling branch page,
8640 * we must proceed all the way down to its first leaf.
8642 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
8645 mc.mc_pg[mc.mc_top] = mp;
8649 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8650 rc = mdb_env_cthr_toggle(my, 1);
8653 toggle = my->mc_toggle;
8655 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8656 mdb_page_copy(mo, mp, my->mc_env->me_psize);
8657 mo->mp_pgno = my->mc_next_pgno++;
8658 my->mc_wlen[toggle] += my->mc_env->me_psize;
8660 /* Update parent if there is one */
8661 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
8662 SETPGNO(ni, mo->mp_pgno);
8663 mdb_cursor_pop(&mc);
8665 /* Otherwise we're done */
8675 /** Copy environment with compaction. */
8677 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
8682 MDB_txn *txn = NULL;
8687 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
8688 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
8689 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
8690 if (my.mc_wbuf[0] == NULL)
8693 pthread_mutex_init(&my.mc_mutex, NULL);
8694 pthread_cond_init(&my.mc_cond, NULL);
8695 #ifdef HAVE_MEMALIGN
8696 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
8697 if (my.mc_wbuf[0] == NULL)
8700 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_os_psize, MDB_WBUF*2);
8705 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
8706 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
8711 my.mc_next_pgno = 2;
8717 THREAD_CREATE(thr, mdb_env_copythr, &my);
8719 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8723 mp = (MDB_page *)my.mc_wbuf[0];
8724 memset(mp, 0, 2*env->me_psize);
8726 mp->mp_flags = P_META;
8727 mm = (MDB_meta *)METADATA(mp);
8728 mdb_env_init_meta0(env, mm);
8729 mm->mm_address = env->me_metas[0]->mm_address;
8731 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
8733 mp->mp_flags = P_META;
8734 *(MDB_meta *)METADATA(mp) = *mm;
8735 mm = (MDB_meta *)METADATA(mp);
8737 /* Count the number of free pages, subtract from lastpg to find
8738 * number of active pages
8741 MDB_ID freecount = 0;
8744 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
8745 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
8746 freecount += *(MDB_ID *)data.mv_data;
8747 freecount += txn->mt_dbs[0].md_branch_pages +
8748 txn->mt_dbs[0].md_leaf_pages +
8749 txn->mt_dbs[0].md_overflow_pages;
8751 /* Set metapage 1 */
8752 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
8753 mm->mm_dbs[1] = txn->mt_dbs[1];
8754 mm->mm_dbs[1].md_root = mm->mm_last_pg;
8757 my.mc_wlen[0] = env->me_psize * 2;
8759 pthread_mutex_lock(&my.mc_mutex);
8761 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8762 pthread_mutex_unlock(&my.mc_mutex);
8763 rc = mdb_env_cwalk(&my, &txn->mt_dbs[1].md_root, 0);
8764 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
8765 rc = mdb_env_cthr_toggle(&my, 1);
8766 mdb_env_cthr_toggle(&my, -1);
8767 pthread_mutex_lock(&my.mc_mutex);
8769 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8770 pthread_mutex_unlock(&my.mc_mutex);
8775 CloseHandle(my.mc_cond);
8776 CloseHandle(my.mc_mutex);
8777 _aligned_free(my.mc_wbuf[0]);
8779 pthread_cond_destroy(&my.mc_cond);
8780 pthread_mutex_destroy(&my.mc_mutex);
8781 free(my.mc_wbuf[0]);
8786 /** Copy environment as-is. */
8788 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
8790 MDB_txn *txn = NULL;
8796 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8800 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8803 /* Do the lock/unlock of the reader mutex before starting the
8804 * write txn. Otherwise other read txns could block writers.
8806 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8811 /* We must start the actual read txn after blocking writers */
8812 mdb_txn_reset0(txn, "reset-stage1");
8814 /* Temporarily block writers until we snapshot the meta pages */
8817 rc = mdb_txn_renew0(txn);
8819 UNLOCK_MUTEX_W(env);
8824 wsize = env->me_psize * 2;
8828 DO_WRITE(rc, fd, ptr, w2, len);
8832 } else if (len > 0) {
8838 /* Non-blocking or async handles are not supported */
8844 UNLOCK_MUTEX_W(env);
8849 w2 = txn->mt_next_pgno * env->me_psize;
8852 LARGE_INTEGER fsize;
8853 GetFileSizeEx(env->me_fd, &fsize);
8854 if (w2 > fsize.QuadPart)
8855 w2 = fsize.QuadPart;
8860 fstat(env->me_fd, &st);
8861 if (w2 > (size_t)st.st_size)
8867 if (wsize > MAX_WRITE)
8871 DO_WRITE(rc, fd, ptr, w2, len);
8875 } else if (len > 0) {
8892 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
8894 if (flags & MDB_CP_COMPACT)
8895 return mdb_env_copyfd1(env, fd);
8897 return mdb_env_copyfd0(env, fd);
8901 mdb_env_copyfd(MDB_env *env, HANDLE fd)
8903 return mdb_env_copyfd2(env, fd, 0);
8907 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
8911 HANDLE newfd = INVALID_HANDLE_VALUE;
8913 if (env->me_flags & MDB_NOSUBDIR) {
8914 lpath = (char *)path;
8917 len += sizeof(DATANAME);
8918 lpath = malloc(len);
8921 sprintf(lpath, "%s" DATANAME, path);
8924 /* The destination path must exist, but the destination file must not.
8925 * We don't want the OS to cache the writes, since the source data is
8926 * already in the OS cache.
8929 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
8930 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
8932 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
8934 if (newfd == INVALID_HANDLE_VALUE) {
8939 if (env->me_psize >= env->me_os_psize) {
8941 /* Set O_DIRECT if the file system supports it */
8942 if ((rc = fcntl(newfd, F_GETFL)) != -1)
8943 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
8945 #ifdef F_NOCACHE /* __APPLE__ */
8946 rc = fcntl(newfd, F_NOCACHE, 1);
8954 rc = mdb_env_copyfd2(env, newfd, flags);
8957 if (!(env->me_flags & MDB_NOSUBDIR))
8959 if (newfd != INVALID_HANDLE_VALUE)
8960 if (close(newfd) < 0 && rc == MDB_SUCCESS)
8967 mdb_env_copy(MDB_env *env, const char *path)
8969 return mdb_env_copy2(env, path, 0);
8973 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
8975 if ((flag & CHANGEABLE) != flag)
8978 env->me_flags |= flag;
8980 env->me_flags &= ~flag;
8985 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
8990 *arg = env->me_flags;
8995 mdb_env_set_userctx(MDB_env *env, void *ctx)
8999 env->me_userctx = ctx;
9004 mdb_env_get_userctx(MDB_env *env)
9006 return env ? env->me_userctx : NULL;
9010 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
9015 env->me_assert_func = func;
9021 mdb_env_get_path(MDB_env *env, const char **arg)
9026 *arg = env->me_path;
9031 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
9040 /** Common code for #mdb_stat() and #mdb_env_stat().
9041 * @param[in] env the environment to operate in.
9042 * @param[in] db the #MDB_db record containing the stats to return.
9043 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
9044 * @return 0, this function always succeeds.
9047 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
9049 arg->ms_psize = env->me_psize;
9050 arg->ms_depth = db->md_depth;
9051 arg->ms_branch_pages = db->md_branch_pages;
9052 arg->ms_leaf_pages = db->md_leaf_pages;
9053 arg->ms_overflow_pages = db->md_overflow_pages;
9054 arg->ms_entries = db->md_entries;
9060 mdb_env_stat(MDB_env *env, MDB_stat *arg)
9064 if (env == NULL || arg == NULL)
9067 toggle = mdb_env_pick_meta(env);
9069 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
9073 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
9077 if (env == NULL || arg == NULL)
9080 toggle = mdb_env_pick_meta(env);
9081 arg->me_mapaddr = env->me_metas[toggle]->mm_address;
9082 arg->me_mapsize = env->me_mapsize;
9083 arg->me_maxreaders = env->me_maxreaders;
9085 /* me_numreaders may be zero if this process never used any readers. Use
9086 * the shared numreader count if it exists.
9088 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
9090 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
9091 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
9095 /** Set the default comparison functions for a database.
9096 * Called immediately after a database is opened to set the defaults.
9097 * The user can then override them with #mdb_set_compare() or
9098 * #mdb_set_dupsort().
9099 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
9100 * @param[in] dbi A database handle returned by #mdb_dbi_open()
9103 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
9105 uint16_t f = txn->mt_dbs[dbi].md_flags;
9107 txn->mt_dbxs[dbi].md_cmp =
9108 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
9109 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
9111 txn->mt_dbxs[dbi].md_dcmp =
9112 !(f & MDB_DUPSORT) ? 0 :
9113 ((f & MDB_INTEGERDUP)
9114 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
9115 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
9118 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
9124 int rc, dbflag, exact;
9125 unsigned int unused = 0, seq;
9128 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
9129 mdb_default_cmp(txn, FREE_DBI);
9132 if ((flags & VALID_FLAGS) != flags)
9134 if (txn->mt_flags & MDB_TXN_ERROR)
9140 if (flags & PERSISTENT_FLAGS) {
9141 uint16_t f2 = flags & PERSISTENT_FLAGS;
9142 /* make sure flag changes get committed */
9143 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
9144 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
9145 txn->mt_flags |= MDB_TXN_DIRTY;
9148 mdb_default_cmp(txn, MAIN_DBI);
9152 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
9153 mdb_default_cmp(txn, MAIN_DBI);
9156 /* Is the DB already open? */
9158 for (i=2; i<txn->mt_numdbs; i++) {
9159 if (!txn->mt_dbxs[i].md_name.mv_size) {
9160 /* Remember this free slot */
9161 if (!unused) unused = i;
9164 if (len == txn->mt_dbxs[i].md_name.mv_size &&
9165 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
9171 /* If no free slot and max hit, fail */
9172 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
9173 return MDB_DBS_FULL;
9175 /* Cannot mix named databases with some mainDB flags */
9176 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
9177 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
9179 /* Find the DB info */
9180 dbflag = DB_NEW|DB_VALID;
9183 key.mv_data = (void *)name;
9184 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
9185 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
9186 if (rc == MDB_SUCCESS) {
9187 /* make sure this is actually a DB */
9188 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
9189 if (!(node->mn_flags & F_SUBDATA))
9190 return MDB_INCOMPATIBLE;
9191 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
9192 /* Create if requested */
9193 data.mv_size = sizeof(MDB_db);
9194 data.mv_data = &dummy;
9195 memset(&dummy, 0, sizeof(dummy));
9196 dummy.md_root = P_INVALID;
9197 dummy.md_flags = flags & PERSISTENT_FLAGS;
9198 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
9202 /* OK, got info, add to table */
9203 if (rc == MDB_SUCCESS) {
9204 unsigned int slot = unused ? unused : txn->mt_numdbs;
9205 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
9206 txn->mt_dbxs[slot].md_name.mv_size = len;
9207 txn->mt_dbxs[slot].md_rel = NULL;
9208 txn->mt_dbflags[slot] = dbflag;
9209 /* txn-> and env-> are the same in read txns, use
9210 * tmp variable to avoid undefined assignment
9212 seq = ++txn->mt_env->me_dbiseqs[slot];
9213 txn->mt_dbiseqs[slot] = seq;
9215 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
9217 mdb_default_cmp(txn, slot);
9226 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9228 if (!arg || !TXN_DBI_EXIST(txn, dbi))
9231 if (txn->mt_flags & MDB_TXN_ERROR)
9234 if (txn->mt_dbflags[dbi] & DB_STALE) {
9237 /* Stale, must read the DB's root. cursor_init does it for us. */
9238 mdb_cursor_init(&mc, txn, dbi, &mx);
9240 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9243 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9246 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
9248 ptr = env->me_dbxs[dbi].md_name.mv_data;
9249 /* If there was no name, this was already closed */
9251 env->me_dbxs[dbi].md_name.mv_data = NULL;
9252 env->me_dbxs[dbi].md_name.mv_size = 0;
9253 env->me_dbflags[dbi] = 0;
9254 env->me_dbiseqs[dbi]++;
9259 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9261 /* We could return the flags for the FREE_DBI too but what's the point? */
9262 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9264 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9268 /** Add all the DB's pages to the free list.
9269 * @param[in] mc Cursor on the DB to free.
9270 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9271 * @return 0 on success, non-zero on failure.
9274 mdb_drop0(MDB_cursor *mc, int subs)
9278 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9279 if (rc == MDB_SUCCESS) {
9280 MDB_txn *txn = mc->mc_txn;
9285 /* LEAF2 pages have no nodes, cannot have sub-DBs */
9286 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
9289 mdb_cursor_copy(mc, &mx);
9290 while (mc->mc_snum > 0) {
9291 MDB_page *mp = mc->mc_pg[mc->mc_top];
9292 unsigned n = NUMKEYS(mp);
9294 for (i=0; i<n; i++) {
9295 ni = NODEPTR(mp, i);
9296 if (ni->mn_flags & F_BIGDATA) {
9299 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9300 rc = mdb_page_get(txn, pg, &omp, NULL);
9303 mdb_cassert(mc, IS_OVERFLOW(omp));
9304 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9308 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9309 mdb_xcursor_init1(mc, ni);
9310 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9316 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9318 for (i=0; i<n; i++) {
9320 ni = NODEPTR(mp, i);
9323 mdb_midl_xappend(txn->mt_free_pgs, pg);
9328 mc->mc_ki[mc->mc_top] = i;
9329 rc = mdb_cursor_sibling(mc, 1);
9331 if (rc != MDB_NOTFOUND)
9333 /* no more siblings, go back to beginning
9334 * of previous level.
9338 for (i=1; i<mc->mc_snum; i++) {
9340 mc->mc_pg[i] = mx.mc_pg[i];
9345 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9348 txn->mt_flags |= MDB_TXN_ERROR;
9349 } else if (rc == MDB_NOTFOUND) {
9355 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9357 MDB_cursor *mc, *m2;
9360 if ((unsigned)del > 1 || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9363 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9366 if (dbi > MAIN_DBI && TXN_DBI_CHANGED(txn, dbi))
9369 rc = mdb_cursor_open(txn, dbi, &mc);
9373 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9374 /* Invalidate the dropped DB's cursors */
9375 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9376 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9380 /* Can't delete the main DB */
9381 if (del && dbi > MAIN_DBI) {
9382 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, 0);
9384 txn->mt_dbflags[dbi] = DB_STALE;
9385 mdb_dbi_close(txn->mt_env, dbi);
9387 txn->mt_flags |= MDB_TXN_ERROR;
9390 /* reset the DB record, mark it dirty */
9391 txn->mt_dbflags[dbi] |= DB_DIRTY;
9392 txn->mt_dbs[dbi].md_depth = 0;
9393 txn->mt_dbs[dbi].md_branch_pages = 0;
9394 txn->mt_dbs[dbi].md_leaf_pages = 0;
9395 txn->mt_dbs[dbi].md_overflow_pages = 0;
9396 txn->mt_dbs[dbi].md_entries = 0;
9397 txn->mt_dbs[dbi].md_root = P_INVALID;
9399 txn->mt_flags |= MDB_TXN_DIRTY;
9402 mdb_cursor_close(mc);
9406 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9408 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9411 txn->mt_dbxs[dbi].md_cmp = cmp;
9415 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9417 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9420 txn->mt_dbxs[dbi].md_dcmp = cmp;
9424 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9426 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9429 txn->mt_dbxs[dbi].md_rel = rel;
9433 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9435 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9438 txn->mt_dbxs[dbi].md_relctx = ctx;
9443 mdb_env_get_maxkeysize(MDB_env *env)
9445 return ENV_MAXKEY(env);
9449 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9451 unsigned int i, rdrs;
9454 int rc = 0, first = 1;
9458 if (!env->me_txns) {
9459 return func("(no reader locks)\n", ctx);
9461 rdrs = env->me_txns->mti_numreaders;
9462 mr = env->me_txns->mti_readers;
9463 for (i=0; i<rdrs; i++) {
9465 txnid_t txnid = mr[i].mr_txnid;
9466 sprintf(buf, txnid == (txnid_t)-1 ?
9467 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9468 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9471 rc = func(" pid thread txnid\n", ctx);
9475 rc = func(buf, ctx);
9481 rc = func("(no active readers)\n", ctx);
9486 /** Insert pid into list if not already present.
9487 * return -1 if already present.
9490 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9492 /* binary search of pid in list */
9494 unsigned cursor = 1;
9496 unsigned n = ids[0];
9499 unsigned pivot = n >> 1;
9500 cursor = base + pivot + 1;
9501 val = pid - ids[cursor];
9506 } else if ( val > 0 ) {
9511 /* found, so it's a duplicate */
9520 for (n = ids[0]; n > cursor; n--)
9527 mdb_reader_check(MDB_env *env, int *dead)
9529 unsigned int i, j, rdrs;
9531 MDB_PID_T *pids, pid;
9540 rdrs = env->me_txns->mti_numreaders;
9541 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
9545 mr = env->me_txns->mti_readers;
9546 for (i=0; i<rdrs; i++) {
9547 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
9549 if (mdb_pid_insert(pids, pid) == 0) {
9550 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9552 /* Recheck, a new process may have reused pid */
9553 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9554 for (j=i; j<rdrs; j++)
9555 if (mr[j].mr_pid == pid) {
9556 DPRINTF(("clear stale reader pid %u txn %"Z"d",
9557 (unsigned) pid, mr[j].mr_txnid));
9562 UNLOCK_MUTEX_R(env);