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
83 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
84 #include <netinet/in.h>
85 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
88 #if defined(__APPLE__) || defined (BSD)
89 # define MDB_USE_POSIX_SEM 1
90 # define MDB_FDATASYNC fsync
91 #elif defined(ANDROID)
92 # define MDB_FDATASYNC fsync
97 #ifdef MDB_USE_POSIX_SEM
98 # define MDB_USE_HASH 1
99 #include <semaphore.h>
104 #include <valgrind/memcheck.h>
105 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
106 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
107 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
108 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
109 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
111 #define VGMEMP_CREATE(h,r,z)
112 #define VGMEMP_ALLOC(h,a,s)
113 #define VGMEMP_FREE(h,a)
114 #define VGMEMP_DESTROY(h)
115 #define VGMEMP_DEFINED(a,s)
119 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
120 /* Solaris just defines one or the other */
121 # define LITTLE_ENDIAN 1234
122 # define BIG_ENDIAN 4321
123 # ifdef _LITTLE_ENDIAN
124 # define BYTE_ORDER LITTLE_ENDIAN
126 # define BYTE_ORDER BIG_ENDIAN
129 # define BYTE_ORDER __BYTE_ORDER
133 #ifndef LITTLE_ENDIAN
134 #define LITTLE_ENDIAN __LITTLE_ENDIAN
137 #define BIG_ENDIAN __BIG_ENDIAN
140 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
141 #define MISALIGNED_OK 1
147 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
148 # error "Unknown or unsupported endianness (BYTE_ORDER)"
149 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
150 # error "Two's complement, reasonably sized integer types, please"
154 /** Put infrequently used env functions in separate section */
156 # define ESECT __attribute__ ((section("__TEXT,text_env")))
158 # define ESECT __attribute__ ((section("text_env")))
164 /** @defgroup internal LMDB Internals
167 /** @defgroup compat Compatibility Macros
168 * A bunch of macros to minimize the amount of platform-specific ifdefs
169 * needed throughout the rest of the code. When the features this library
170 * needs are similar enough to POSIX to be hidden in a one-or-two line
171 * replacement, this macro approach is used.
175 /** Features under development */
180 /** Wrapper around __func__, which is a C99 feature */
181 #if __STDC_VERSION__ >= 199901L
182 # define mdb_func_ __func__
183 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
184 # define mdb_func_ __FUNCTION__
186 /* If a debug message says <mdb_unknown>(), update the #if statements above */
187 # define mdb_func_ "<mdb_unknown>"
191 #define MDB_USE_HASH 1
192 #define MDB_PIDLOCK 0
193 #define THREAD_RET DWORD
194 #define pthread_t HANDLE
195 #define pthread_mutex_t HANDLE
196 #define pthread_cond_t HANDLE
197 #define pthread_key_t DWORD
198 #define pthread_self() GetCurrentThreadId()
199 #define pthread_key_create(x,y) \
200 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
201 #define pthread_key_delete(x) TlsFree(x)
202 #define pthread_getspecific(x) TlsGetValue(x)
203 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
204 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
205 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
206 #define pthread_cond_signal(x) SetEvent(*x)
207 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
208 #define THREAD_CREATE(thr,start,arg) thr=CreateThread(NULL,0,start,arg,0,NULL)
209 #define THREAD_FINISH(thr) WaitForSingleObject(thr, INFINITE)
210 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_rmutex)
211 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_rmutex)
212 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_wmutex)
213 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_wmutex)
214 #define getpid() GetCurrentProcessId()
215 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
216 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
217 #define ErrCode() GetLastError()
218 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
219 #define close(fd) (CloseHandle(fd) ? 0 : -1)
220 #define munmap(ptr,len) UnmapViewOfFile(ptr)
221 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
222 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
224 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
228 #define THREAD_RET void *
229 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
230 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
231 #define Z "z" /**< printf format modifier for size_t */
233 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
234 #define MDB_PIDLOCK 1
236 #ifdef MDB_USE_POSIX_SEM
238 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
239 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
240 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
241 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
244 mdb_sem_wait(sem_t *sem)
247 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
252 /** Lock the reader mutex.
254 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
255 /** Unlock the reader mutex.
257 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
259 /** Lock the writer mutex.
260 * Only a single write transaction is allowed at a time. Other writers
261 * will block waiting for this mutex.
263 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
264 /** Unlock the writer mutex.
266 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
267 #endif /* MDB_USE_POSIX_SEM */
269 /** Get the error code for the last failed system function.
271 #define ErrCode() errno
273 /** An abstraction for a file handle.
274 * On POSIX systems file handles are small integers. On Windows
275 * they're opaque pointers.
279 /** A value for an invalid file handle.
280 * Mainly used to initialize file variables and signify that they are
283 #define INVALID_HANDLE_VALUE (-1)
285 /** Get the size of a memory page for the system.
286 * This is the basic size that the platform's memory manager uses, and is
287 * fundamental to the use of memory-mapped files.
289 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
292 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
295 #define MNAME_LEN (sizeof(pthread_mutex_t))
301 /** A flag for opening a file and requesting synchronous data writes.
302 * This is only used when writing a meta page. It's not strictly needed;
303 * we could just do a normal write and then immediately perform a flush.
304 * But if this flag is available it saves us an extra system call.
306 * @note If O_DSYNC is undefined but exists in /usr/include,
307 * preferably set some compiler flag to get the definition.
308 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
311 # define MDB_DSYNC O_DSYNC
315 /** Function for flushing the data of a file. Define this to fsync
316 * if fdatasync() is not supported.
318 #ifndef MDB_FDATASYNC
319 # define MDB_FDATASYNC fdatasync
323 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
334 /** A page number in the database.
335 * Note that 64 bit page numbers are overkill, since pages themselves
336 * already represent 12-13 bits of addressable memory, and the OS will
337 * always limit applications to a maximum of 63 bits of address space.
339 * @note In the #MDB_node structure, we only store 48 bits of this value,
340 * which thus limits us to only 60 bits of addressable data.
342 typedef MDB_ID pgno_t;
344 /** A transaction ID.
345 * See struct MDB_txn.mt_txnid for details.
347 typedef MDB_ID txnid_t;
349 /** @defgroup debug Debug Macros
353 /** Enable debug output. Needs variable argument macros (a C99 feature).
354 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
355 * read from and written to the database (used for free space management).
361 static int mdb_debug;
362 static txnid_t mdb_debug_start;
364 /** Print a debug message with printf formatting.
365 * Requires double parenthesis around 2 or more args.
367 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
368 # define DPRINTF0(fmt, ...) \
369 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
371 # define DPRINTF(args) ((void) 0)
373 /** Print a debug string.
374 * The string is printed literally, with no format processing.
376 #define DPUTS(arg) DPRINTF(("%s", arg))
377 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
379 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
382 /** @brief The maximum size of a database page.
384 * It is 32k or 64k, since value-PAGEBASE must fit in
385 * #MDB_page.%mp_upper.
387 * LMDB will use database pages < OS pages if needed.
388 * That causes more I/O in write transactions: The OS must
389 * know (read) the whole page before writing a partial page.
391 * Note that we don't currently support Huge pages. On Linux,
392 * regular data files cannot use Huge pages, and in general
393 * Huge pages aren't actually pageable. We rely on the OS
394 * demand-pager to read our data and page it out when memory
395 * pressure from other processes is high. So until OSs have
396 * actual paging support for Huge pages, they're not viable.
398 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
400 /** The minimum number of keys required in a database page.
401 * Setting this to a larger value will place a smaller bound on the
402 * maximum size of a data item. Data items larger than this size will
403 * be pushed into overflow pages instead of being stored directly in
404 * the B-tree node. This value used to default to 4. With a page size
405 * of 4096 bytes that meant that any item larger than 1024 bytes would
406 * go into an overflow page. That also meant that on average 2-3KB of
407 * each overflow page was wasted space. The value cannot be lower than
408 * 2 because then there would no longer be a tree structure. With this
409 * value, items larger than 2KB will go into overflow pages, and on
410 * average only 1KB will be wasted.
412 #define MDB_MINKEYS 2
414 /** A stamp that identifies a file as an LMDB file.
415 * There's nothing special about this value other than that it is easily
416 * recognizable, and it will reflect any byte order mismatches.
418 #define MDB_MAGIC 0xBEEFC0DE
420 /** The version number for a database's datafile format. */
421 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
422 /** The version number for a database's lockfile format. */
423 #define MDB_LOCK_VERSION 1
425 /** @brief The max size of a key we can write, or 0 for dynamic max.
427 * Define this as 0 to compute the max from the page size. 511
428 * is default for backwards compat: liblmdb <= 0.9.10 can break
429 * when modifying a DB with keys/dupsort data bigger than its max.
431 * Data items in an #MDB_DUPSORT database are also limited to
432 * this size, since they're actually keys of a sub-DB. Keys and
433 * #MDB_DUPSORT data items must fit on a node in a regular page.
435 #ifndef MDB_MAXKEYSIZE
436 #define MDB_MAXKEYSIZE 511
439 /** The maximum size of a key we can write to the environment. */
441 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
443 #define ENV_MAXKEY(env) ((env)->me_maxkey)
446 /** @brief The maximum size of a data item.
448 * We only store a 32 bit value for node sizes.
450 #define MAXDATASIZE 0xffffffffUL
453 /** Key size which fits in a #DKBUF.
456 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
459 * This is used for printing a hex dump of a key's contents.
461 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
462 /** Display a key in hex.
464 * Invoke a function to display a key in hex.
466 #define DKEY(x) mdb_dkey(x, kbuf)
472 /** An invalid page number.
473 * Mainly used to denote an empty tree.
475 #define P_INVALID (~(pgno_t)0)
477 /** Test if the flags \b f are set in a flag word \b w. */
478 #define F_ISSET(w, f) (((w) & (f)) == (f))
480 /** Round \b n up to an even number. */
481 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
483 /** Used for offsets within a single page.
484 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
487 typedef uint16_t indx_t;
489 /** Default size of memory map.
490 * This is certainly too small for any actual applications. Apps should always set
491 * the size explicitly using #mdb_env_set_mapsize().
493 #define DEFAULT_MAPSIZE 1048576
495 /** @defgroup readers Reader Lock Table
496 * Readers don't acquire any locks for their data access. Instead, they
497 * simply record their transaction ID in the reader table. The reader
498 * mutex is needed just to find an empty slot in the reader table. The
499 * slot's address is saved in thread-specific data so that subsequent read
500 * transactions started by the same thread need no further locking to proceed.
502 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
504 * No reader table is used if the database is on a read-only filesystem, or
505 * if #MDB_NOLOCK is set.
507 * Since the database uses multi-version concurrency control, readers don't
508 * actually need any locking. This table is used to keep track of which
509 * readers are using data from which old transactions, so that we'll know
510 * when a particular old transaction is no longer in use. Old transactions
511 * that have discarded any data pages can then have those pages reclaimed
512 * for use by a later write transaction.
514 * The lock table is constructed such that reader slots are aligned with the
515 * processor's cache line size. Any slot is only ever used by one thread.
516 * This alignment guarantees that there will be no contention or cache
517 * thrashing as threads update their own slot info, and also eliminates
518 * any need for locking when accessing a slot.
520 * A writer thread will scan every slot in the table to determine the oldest
521 * outstanding reader transaction. Any freed pages older than this will be
522 * reclaimed by the writer. The writer doesn't use any locks when scanning
523 * this table. This means that there's no guarantee that the writer will
524 * see the most up-to-date reader info, but that's not required for correct
525 * operation - all we need is to know the upper bound on the oldest reader,
526 * we don't care at all about the newest reader. So the only consequence of
527 * reading stale information here is that old pages might hang around a
528 * while longer before being reclaimed. That's actually good anyway, because
529 * the longer we delay reclaiming old pages, the more likely it is that a
530 * string of contiguous pages can be found after coalescing old pages from
531 * many old transactions together.
534 /** Number of slots in the reader table.
535 * This value was chosen somewhat arbitrarily. 126 readers plus a
536 * couple mutexes fit exactly into 8KB on my development machine.
537 * Applications should set the table size using #mdb_env_set_maxreaders().
539 #define DEFAULT_READERS 126
541 /** The size of a CPU cache line in bytes. We want our lock structures
542 * aligned to this size to avoid false cache line sharing in the
544 * This value works for most CPUs. For Itanium this should be 128.
550 /** The information we store in a single slot of the reader table.
551 * In addition to a transaction ID, we also record the process and
552 * thread ID that owns a slot, so that we can detect stale information,
553 * e.g. threads or processes that went away without cleaning up.
554 * @note We currently don't check for stale records. We simply re-init
555 * the table when we know that we're the only process opening the
558 typedef struct MDB_rxbody {
559 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
560 * Multiple readers that start at the same time will probably have the
561 * same ID here. Again, it's not important to exclude them from
562 * anything; all we need to know is which version of the DB they
563 * started from so we can avoid overwriting any data used in that
564 * particular version.
567 /** The process ID of the process owning this reader txn. */
569 /** The thread ID of the thread owning this txn. */
573 /** The actual reader record, with cacheline padding. */
574 typedef struct MDB_reader {
577 /** shorthand for mrb_txnid */
578 #define mr_txnid mru.mrx.mrb_txnid
579 #define mr_pid mru.mrx.mrb_pid
580 #define mr_tid mru.mrx.mrb_tid
581 /** cache line alignment */
582 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
586 /** The header for the reader table.
587 * The table resides in a memory-mapped file. (This is a different file
588 * than is used for the main database.)
590 * For POSIX the actual mutexes reside in the shared memory of this
591 * mapped file. On Windows, mutexes are named objects allocated by the
592 * kernel; we store the mutex names in this mapped file so that other
593 * processes can grab them. This same approach is also used on
594 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
595 * process-shared POSIX mutexes. For these cases where a named object
596 * is used, the object name is derived from a 64 bit FNV hash of the
597 * environment pathname. As such, naming collisions are extremely
598 * unlikely. If a collision occurs, the results are unpredictable.
600 typedef struct MDB_txbody {
601 /** Stamp identifying this as an LMDB file. It must be set
604 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
606 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
607 char mtb_rmname[MNAME_LEN];
609 /** Mutex protecting access to this table.
610 * This is the reader lock that #LOCK_MUTEX_R acquires.
612 pthread_mutex_t mtb_mutex;
614 /** The ID of the last transaction committed to the database.
615 * This is recorded here only for convenience; the value can always
616 * be determined by reading the main database meta pages.
619 /** The number of slots that have been used in the reader table.
620 * This always records the maximum count, it is not decremented
621 * when readers release their slots.
623 unsigned mtb_numreaders;
626 /** The actual reader table definition. */
627 typedef struct MDB_txninfo {
630 #define mti_magic mt1.mtb.mtb_magic
631 #define mti_format mt1.mtb.mtb_format
632 #define mti_mutex mt1.mtb.mtb_mutex
633 #define mti_rmname mt1.mtb.mtb_rmname
634 #define mti_txnid mt1.mtb.mtb_txnid
635 #define mti_numreaders mt1.mtb.mtb_numreaders
636 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
639 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
640 char mt2_wmname[MNAME_LEN];
641 #define mti_wmname mt2.mt2_wmname
643 pthread_mutex_t mt2_wmutex;
644 #define mti_wmutex mt2.mt2_wmutex
646 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
648 MDB_reader mti_readers[1];
651 /** Lockfile format signature: version, features and field layout */
652 #define MDB_LOCK_FORMAT \
654 ((MDB_LOCK_VERSION) \
655 /* Flags which describe functionality */ \
656 + (((MDB_PIDLOCK) != 0) << 16)))
659 /** Common header for all page types.
660 * Overflow records occupy a number of contiguous pages with no
661 * headers on any page after the first.
663 typedef struct MDB_page {
664 #define mp_pgno mp_p.p_pgno
665 #define mp_next mp_p.p_next
667 pgno_t p_pgno; /**< page number */
668 struct MDB_page *p_next; /**< for in-memory list of freed pages */
671 /** @defgroup mdb_page Page Flags
673 * Flags for the page headers.
676 #define P_BRANCH 0x01 /**< branch page */
677 #define P_LEAF 0x02 /**< leaf page */
678 #define P_OVERFLOW 0x04 /**< overflow page */
679 #define P_META 0x08 /**< meta page */
680 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
681 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
682 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
683 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
684 #define P_KEEP 0x8000 /**< leave this page alone during spill */
686 uint16_t mp_flags; /**< @ref mdb_page */
687 #define mp_lower mp_pb.pb.pb_lower
688 #define mp_upper mp_pb.pb.pb_upper
689 #define mp_pages mp_pb.pb_pages
692 indx_t pb_lower; /**< lower bound of free space */
693 indx_t pb_upper; /**< upper bound of free space */
695 uint32_t pb_pages; /**< number of overflow pages */
697 indx_t mp_ptrs[1]; /**< dynamic size */
700 /** Size of the page header, excluding dynamic data at the end */
701 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
703 /** Address of first usable data byte in a page, after the header */
704 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
706 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
707 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
709 /** Number of nodes on a page */
710 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
712 /** The amount of space remaining in the page */
713 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
715 /** The percentage of space used in the page, in tenths of a percent. */
716 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
717 ((env)->me_psize - PAGEHDRSZ))
718 /** The minimum page fill factor, in tenths of a percent.
719 * Pages emptier than this are candidates for merging.
721 #define FILL_THRESHOLD 250
723 /** Test if a page is a leaf page */
724 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
725 /** Test if a page is a LEAF2 page */
726 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
727 /** Test if a page is a branch page */
728 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
729 /** Test if a page is an overflow page */
730 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
731 /** Test if a page is a sub page */
732 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
734 /** The number of overflow pages needed to store the given size. */
735 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
737 /** Link in #MDB_txn.%mt_loose_pages list */
738 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
740 /** Header for a single key/data pair within a page.
741 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
742 * We guarantee 2-byte alignment for 'MDB_node's.
744 typedef struct MDB_node {
745 /** lo and hi are used for data size on leaf nodes and for
746 * child pgno on branch nodes. On 64 bit platforms, flags
747 * is also used for pgno. (Branch nodes have no flags).
748 * They are in host byte order in case that lets some
749 * accesses be optimized into a 32-bit word access.
751 #if BYTE_ORDER == LITTLE_ENDIAN
752 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
754 unsigned short mn_hi, mn_lo;
756 /** @defgroup mdb_node Node Flags
758 * Flags for node headers.
761 #define F_BIGDATA 0x01 /**< data put on overflow page */
762 #define F_SUBDATA 0x02 /**< data is a sub-database */
763 #define F_DUPDATA 0x04 /**< data has duplicates */
765 /** valid flags for #mdb_node_add() */
766 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
769 unsigned short mn_flags; /**< @ref mdb_node */
770 unsigned short mn_ksize; /**< key size */
771 char mn_data[1]; /**< key and data are appended here */
774 /** Size of the node header, excluding dynamic data at the end */
775 #define NODESIZE offsetof(MDB_node, mn_data)
777 /** Bit position of top word in page number, for shifting mn_flags */
778 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
780 /** Size of a node in a branch page with a given key.
781 * This is just the node header plus the key, there is no data.
783 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
785 /** Size of a node in a leaf page with a given key and data.
786 * This is node header plus key plus data size.
788 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
790 /** Address of node \b i in page \b p */
791 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
793 /** Address of the key for the node */
794 #define NODEKEY(node) (void *)((node)->mn_data)
796 /** Address of the data for a node */
797 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
799 /** Get the page number pointed to by a branch node */
800 #define NODEPGNO(node) \
801 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
802 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
803 /** Set the page number in a branch node */
804 #define SETPGNO(node,pgno) do { \
805 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
806 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
808 /** Get the size of the data in a leaf node */
809 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
810 /** Set the size of the data for a leaf node */
811 #define SETDSZ(node,size) do { \
812 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
813 /** The size of a key in a node */
814 #define NODEKSZ(node) ((node)->mn_ksize)
816 /** Copy a page number from src to dst */
818 #define COPY_PGNO(dst,src) dst = src
820 #if SIZE_MAX > 4294967295UL
821 #define COPY_PGNO(dst,src) do { \
822 unsigned short *s, *d; \
823 s = (unsigned short *)&(src); \
824 d = (unsigned short *)&(dst); \
831 #define COPY_PGNO(dst,src) do { \
832 unsigned short *s, *d; \
833 s = (unsigned short *)&(src); \
834 d = (unsigned short *)&(dst); \
840 /** The address of a key in a LEAF2 page.
841 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
842 * There are no node headers, keys are stored contiguously.
844 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
846 /** Set the \b node's key into \b keyptr, if requested. */
847 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
848 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
850 /** Set the \b node's key into \b key. */
851 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
853 /** Information about a single database in the environment. */
854 typedef struct MDB_db {
855 uint32_t md_pad; /**< also ksize for LEAF2 pages */
856 uint16_t md_flags; /**< @ref mdb_dbi_open */
857 uint16_t md_depth; /**< depth of this tree */
858 pgno_t md_branch_pages; /**< number of internal pages */
859 pgno_t md_leaf_pages; /**< number of leaf pages */
860 pgno_t md_overflow_pages; /**< number of overflow pages */
861 size_t md_entries; /**< number of data items */
862 pgno_t md_root; /**< the root page of this tree */
865 /** mdb_dbi_open flags */
866 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
867 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
868 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
869 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
871 /** Handle for the DB used to track free pages. */
873 /** Handle for the default DB. */
876 /** Meta page content.
877 * A meta page is the start point for accessing a database snapshot.
878 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
880 typedef struct MDB_meta {
881 /** Stamp identifying this as an LMDB file. It must be set
884 /** Version number of this lock file. Must be set to #MDB_DATA_VERSION. */
886 void *mm_address; /**< address for fixed mapping */
887 size_t mm_mapsize; /**< size of mmap region */
888 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
889 /** The size of pages used in this DB */
890 #define mm_psize mm_dbs[0].md_pad
891 /** Any persistent environment flags. @ref mdb_env */
892 #define mm_flags mm_dbs[0].md_flags
893 pgno_t mm_last_pg; /**< last used page in file */
894 txnid_t mm_txnid; /**< txnid that committed this page */
897 /** Buffer for a stack-allocated meta page.
898 * The members define size and alignment, and silence type
899 * aliasing warnings. They are not used directly; that could
900 * mean incorrectly using several union members in parallel.
902 typedef union MDB_metabuf {
905 char mm_pad[PAGEHDRSZ];
910 /** Auxiliary DB info.
911 * The information here is mostly static/read-only. There is
912 * only a single copy of this record in the environment.
914 typedef struct MDB_dbx {
915 MDB_val md_name; /**< name of the database */
916 MDB_cmp_func *md_cmp; /**< function for comparing keys */
917 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
918 MDB_rel_func *md_rel; /**< user relocate function */
919 void *md_relctx; /**< user-provided context for md_rel */
922 /** A database transaction.
923 * Every operation requires a transaction handle.
926 MDB_txn *mt_parent; /**< parent of a nested txn */
927 MDB_txn *mt_child; /**< nested txn under this txn */
928 pgno_t mt_next_pgno; /**< next unallocated page */
929 /** The ID of this transaction. IDs are integers incrementing from 1.
930 * Only committed write transactions increment the ID. If a transaction
931 * aborts, the ID may be re-used by the next writer.
934 MDB_env *mt_env; /**< the DB environment */
935 /** The list of pages that became unused during this transaction.
938 /** The list of loose pages that became unused and may be reused
939 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
941 MDB_page *mt_loose_pgs;
942 /** The sorted list of dirty pages we temporarily wrote to disk
943 * because the dirty list was full. page numbers in here are
944 * shifted left by 1, deleted slots have the LSB set.
946 MDB_IDL mt_spill_pgs;
948 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
950 /** For read txns: This thread/txn's reader table slot, or NULL. */
953 /** Array of records for each DB known in the environment. */
955 /** Array of MDB_db records for each known DB */
957 /** Array of sequence numbers for each DB handle */
958 unsigned int *mt_dbiseqs;
959 /** @defgroup mt_dbflag Transaction DB Flags
963 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
964 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
965 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
966 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
968 /** In write txns, array of cursors for each DB */
969 MDB_cursor **mt_cursors;
970 /** Array of flags for each DB */
971 unsigned char *mt_dbflags;
972 /** Number of DB records in use. This number only ever increments;
973 * we don't decrement it when individual DB handles are closed.
977 /** @defgroup mdb_txn Transaction Flags
981 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
982 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
983 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
984 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
986 unsigned int mt_flags; /**< @ref mdb_txn */
987 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
988 * Includes ancestor txns' dirty pages not hidden by other txns'
989 * dirty/spilled pages. Thus commit(nested txn) has room to merge
990 * dirty_list into mt_parent after freeing hidden mt_parent pages.
992 unsigned int mt_dirty_room;
995 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
996 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
997 * raise this on a 64 bit machine.
999 #define CURSOR_STACK 32
1003 /** Cursors are used for all DB operations.
1004 * A cursor holds a path of (page pointer, key index) from the DB
1005 * root to a position in the DB, plus other state. #MDB_DUPSORT
1006 * cursors include an xcursor to the current data item. Write txns
1007 * track their cursors and keep them up to date when data moves.
1008 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1009 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1012 /** Next cursor on this DB in this txn */
1013 MDB_cursor *mc_next;
1014 /** Backup of the original cursor if this cursor is a shadow */
1015 MDB_cursor *mc_backup;
1016 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1017 struct MDB_xcursor *mc_xcursor;
1018 /** The transaction that owns this cursor */
1020 /** The database handle this cursor operates on */
1022 /** The database record for this cursor */
1024 /** The database auxiliary record for this cursor */
1026 /** The @ref mt_dbflag for this database */
1027 unsigned char *mc_dbflag;
1028 unsigned short mc_snum; /**< number of pushed pages */
1029 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1030 /** @defgroup mdb_cursor Cursor Flags
1032 * Cursor state flags.
1035 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1036 #define C_EOF 0x02 /**< No more data */
1037 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1038 #define C_DEL 0x08 /**< last op was a cursor_del */
1039 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
1040 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1042 unsigned int mc_flags; /**< @ref mdb_cursor */
1043 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1044 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1047 /** Context for sorted-dup records.
1048 * We could have gone to a fully recursive design, with arbitrarily
1049 * deep nesting of sub-databases. But for now we only handle these
1050 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1052 typedef struct MDB_xcursor {
1053 /** A sub-cursor for traversing the Dup DB */
1054 MDB_cursor mx_cursor;
1055 /** The database record for this Dup DB */
1057 /** The auxiliary DB record for this Dup DB */
1059 /** The @ref mt_dbflag for this Dup DB */
1060 unsigned char mx_dbflag;
1063 /** State of FreeDB old pages, stored in the MDB_env */
1064 typedef struct MDB_pgstate {
1065 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1066 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1069 /** The database environment. */
1071 HANDLE me_fd; /**< The main data file */
1072 HANDLE me_lfd; /**< The lock file */
1073 HANDLE me_mfd; /**< just for writing the meta pages */
1074 /** Failed to update the meta page. Probably an I/O error. */
1075 #define MDB_FATAL_ERROR 0x80000000U
1076 /** We're explicitly changing the mapsize. */
1077 #define MDB_RESIZING 0x40000000U
1078 /** Some fields are initialized. */
1079 #define MDB_ENV_ACTIVE 0x20000000U
1080 /** me_txkey is set */
1081 #define MDB_ENV_TXKEY 0x10000000U
1082 uint32_t me_flags; /**< @ref mdb_env */
1083 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1084 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1085 unsigned int me_maxreaders; /**< size of the reader table */
1086 unsigned int me_numreaders; /**< max numreaders set by this env */
1087 MDB_dbi me_numdbs; /**< number of DBs opened */
1088 MDB_dbi me_maxdbs; /**< size of the DB table */
1089 MDB_PID_T me_pid; /**< process ID of this env */
1090 char *me_path; /**< path to the DB files */
1091 char *me_map; /**< the memory map of the data file */
1092 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1093 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
1094 void *me_pbuf; /**< scratch area for DUPSORT put() */
1095 MDB_txn *me_txn; /**< current write transaction */
1096 size_t me_mapsize; /**< size of the data memory map */
1097 off_t me_size; /**< current file size */
1098 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1099 MDB_dbx *me_dbxs; /**< array of static DB info */
1100 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1101 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1102 pthread_key_t me_txkey; /**< thread-key for readers */
1103 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1104 # define me_pglast me_pgstate.mf_pglast
1105 # define me_pghead me_pgstate.mf_pghead
1106 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1107 /** IDL of pages that became unused in a write txn */
1108 MDB_IDL me_free_pgs;
1109 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1110 MDB_ID2L me_dirty_list;
1111 /** Max number of freelist items that can fit in a single overflow page */
1113 /** Max size of a node on a page */
1114 unsigned int me_nodemax;
1115 #if !(MDB_MAXKEYSIZE)
1116 unsigned int me_maxkey; /**< max size of a key */
1118 int me_live_reader; /**< have liveness lock in reader table */
1120 int me_pidquery; /**< Used in OpenProcess */
1121 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
1123 #elif defined(MDB_USE_POSIX_SEM)
1124 sem_t *me_rmutex; /* Shared mutexes are not supported */
1127 void *me_userctx; /**< User-settable context */
1128 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1131 /** Nested transaction */
1132 typedef struct MDB_ntxn {
1133 MDB_txn mnt_txn; /**< the transaction */
1134 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1137 /** max number of pages to commit in one writev() call */
1138 #define MDB_COMMIT_PAGES 64
1139 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1140 #undef MDB_COMMIT_PAGES
1141 #define MDB_COMMIT_PAGES IOV_MAX
1144 /** max bytes to write in one call */
1145 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1147 /** Check \b txn and \b dbi arguments to a function */
1148 #define TXN_DBI_EXIST(txn, dbi) \
1149 ((txn) && (dbi) < (txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & DB_VALID))
1151 /** Check for misused \b dbi handles */
1152 #define TXN_DBI_CHANGED(txn, dbi) \
1153 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1155 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1156 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1157 static int mdb_page_touch(MDB_cursor *mc);
1159 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1160 static int mdb_page_search_root(MDB_cursor *mc,
1161 MDB_val *key, int modify);
1162 #define MDB_PS_MODIFY 1
1163 #define MDB_PS_ROOTONLY 2
1164 #define MDB_PS_FIRST 4
1165 #define MDB_PS_LAST 8
1166 static int mdb_page_search(MDB_cursor *mc,
1167 MDB_val *key, int flags);
1168 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1170 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1171 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1172 pgno_t newpgno, unsigned int nflags);
1174 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1175 static int mdb_env_pick_meta(const MDB_env *env);
1176 static int mdb_env_write_meta(MDB_txn *txn);
1177 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1178 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1180 static void mdb_env_close0(MDB_env *env, int excl);
1182 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1183 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1184 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1185 static void mdb_node_del(MDB_cursor *mc, int ksize);
1186 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1187 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1188 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1189 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1190 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1192 static int mdb_rebalance(MDB_cursor *mc);
1193 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1195 static void mdb_cursor_pop(MDB_cursor *mc);
1196 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1198 static int mdb_cursor_del0(MDB_cursor *mc);
1199 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1200 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1201 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1202 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1203 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1205 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1206 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1208 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1209 static void mdb_xcursor_init0(MDB_cursor *mc);
1210 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1212 static int mdb_drop0(MDB_cursor *mc, int subs);
1213 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1216 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1220 static SECURITY_DESCRIPTOR mdb_null_sd;
1221 static SECURITY_ATTRIBUTES mdb_all_sa;
1222 static int mdb_sec_inited;
1225 /** Return the library version info. */
1227 mdb_version(int *major, int *minor, int *patch)
1229 if (major) *major = MDB_VERSION_MAJOR;
1230 if (minor) *minor = MDB_VERSION_MINOR;
1231 if (patch) *patch = MDB_VERSION_PATCH;
1232 return MDB_VERSION_STRING;
1235 /** Table of descriptions for LMDB @ref errors */
1236 static char *const mdb_errstr[] = {
1237 "MDB_KEYEXIST: Key/data pair already exists",
1238 "MDB_NOTFOUND: No matching key/data pair found",
1239 "MDB_PAGE_NOTFOUND: Requested page not found",
1240 "MDB_CORRUPTED: Located page was wrong type",
1241 "MDB_PANIC: Update of meta page failed",
1242 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1243 "MDB_INVALID: File is not an LMDB file",
1244 "MDB_MAP_FULL: Environment mapsize limit reached",
1245 "MDB_DBS_FULL: Environment maxdbs limit reached",
1246 "MDB_READERS_FULL: Environment maxreaders limit reached",
1247 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1248 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1249 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1250 "MDB_PAGE_FULL: Internal error - page has no more space",
1251 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1252 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1253 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1254 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1255 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1256 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1260 mdb_strerror(int err)
1263 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1264 * This works as long as no function between the call to mdb_strerror
1265 * and the actual use of the message uses more than 4K of stack.
1268 char buf[1024], *ptr = buf;
1272 return ("Successful return: 0");
1274 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1275 i = err - MDB_KEYEXIST;
1276 return mdb_errstr[i];
1280 /* These are the C-runtime error codes we use. The comment indicates
1281 * their numeric value, and the Win32 error they would correspond to
1282 * if the error actually came from a Win32 API. A major mess, we should
1283 * have used LMDB-specific error codes for everything.
1286 case ENOENT: /* 2, FILE_NOT_FOUND */
1287 case EIO: /* 5, ACCESS_DENIED */
1288 case ENOMEM: /* 12, INVALID_ACCESS */
1289 case EACCES: /* 13, INVALID_DATA */
1290 case EBUSY: /* 16, CURRENT_DIRECTORY */
1291 case EINVAL: /* 22, BAD_COMMAND */
1292 case ENOSPC: /* 28, OUT_OF_PAPER */
1293 return strerror(err);
1298 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1299 FORMAT_MESSAGE_IGNORE_INSERTS,
1300 NULL, err, 0, ptr, sizeof(buf), pad);
1303 return strerror(err);
1307 /** assert(3) variant in cursor context */
1308 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1309 /** assert(3) variant in transaction context */
1310 #define mdb_tassert(mc, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1311 /** assert(3) variant in environment context */
1312 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1315 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1316 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1319 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1320 const char *func, const char *file, int line)
1323 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1324 file, line, expr_txt, func);
1325 if (env->me_assert_func)
1326 env->me_assert_func(env, buf);
1327 fprintf(stderr, "%s\n", buf);
1331 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1335 /** Return the page number of \b mp which may be sub-page, for debug output */
1337 mdb_dbg_pgno(MDB_page *mp)
1340 COPY_PGNO(ret, mp->mp_pgno);
1344 /** Display a key in hexadecimal and return the address of the result.
1345 * @param[in] key the key to display
1346 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1347 * @return The key in hexadecimal form.
1350 mdb_dkey(MDB_val *key, char *buf)
1353 unsigned char *c = key->mv_data;
1359 if (key->mv_size > DKBUF_MAXKEYSIZE)
1360 return "MDB_MAXKEYSIZE";
1361 /* may want to make this a dynamic check: if the key is mostly
1362 * printable characters, print it as-is instead of converting to hex.
1366 for (i=0; i<key->mv_size; i++)
1367 ptr += sprintf(ptr, "%02x", *c++);
1369 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1375 mdb_leafnode_type(MDB_node *n)
1377 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1378 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1379 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1382 /** Display all the keys in the page. */
1384 mdb_page_list(MDB_page *mp)
1386 pgno_t pgno = mdb_dbg_pgno(mp);
1387 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1389 unsigned int i, nkeys, nsize, total = 0;
1393 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1394 case P_BRANCH: type = "Branch page"; break;
1395 case P_LEAF: type = "Leaf page"; break;
1396 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1397 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1398 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1400 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1401 pgno, mp->mp_pages, state);
1404 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1405 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1408 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1412 nkeys = NUMKEYS(mp);
1413 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1415 for (i=0; i<nkeys; i++) {
1416 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1417 key.mv_size = nsize = mp->mp_pad;
1418 key.mv_data = LEAF2KEY(mp, i, nsize);
1420 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1423 node = NODEPTR(mp, i);
1424 key.mv_size = node->mn_ksize;
1425 key.mv_data = node->mn_data;
1426 nsize = NODESIZE + key.mv_size;
1427 if (IS_BRANCH(mp)) {
1428 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1432 if (F_ISSET(node->mn_flags, F_BIGDATA))
1433 nsize += sizeof(pgno_t);
1435 nsize += NODEDSZ(node);
1437 nsize += sizeof(indx_t);
1438 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1439 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1441 total = EVEN(total);
1443 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1444 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1448 mdb_cursor_chk(MDB_cursor *mc)
1454 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1455 for (i=0; i<mc->mc_top; i++) {
1457 node = NODEPTR(mp, mc->mc_ki[i]);
1458 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1461 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1467 /** Count all the pages in each DB and in the freelist
1468 * and make sure it matches the actual number of pages
1470 * All named DBs must be open for a correct count.
1472 static void mdb_audit(MDB_txn *txn)
1476 MDB_ID freecount, count;
1481 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1482 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1483 freecount += *(MDB_ID *)data.mv_data;
1484 mdb_tassert(txn, rc == MDB_NOTFOUND);
1487 for (i = 0; i<txn->mt_numdbs; i++) {
1489 if (!(txn->mt_dbflags[i] & DB_VALID))
1491 mdb_cursor_init(&mc, txn, i, &mx);
1492 if (txn->mt_dbs[i].md_root == P_INVALID)
1494 count += txn->mt_dbs[i].md_branch_pages +
1495 txn->mt_dbs[i].md_leaf_pages +
1496 txn->mt_dbs[i].md_overflow_pages;
1497 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1498 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1499 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1502 mp = mc.mc_pg[mc.mc_top];
1503 for (j=0; j<NUMKEYS(mp); j++) {
1504 MDB_node *leaf = NODEPTR(mp, j);
1505 if (leaf->mn_flags & F_SUBDATA) {
1507 memcpy(&db, NODEDATA(leaf), sizeof(db));
1508 count += db.md_branch_pages + db.md_leaf_pages +
1509 db.md_overflow_pages;
1513 mdb_tassert(txn, rc == MDB_NOTFOUND);
1516 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1517 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1518 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1524 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1526 return txn->mt_dbxs[dbi].md_cmp(a, b);
1530 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1532 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1535 /** Allocate memory for a page.
1536 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1539 mdb_page_malloc(MDB_txn *txn, unsigned num)
1541 MDB_env *env = txn->mt_env;
1542 MDB_page *ret = env->me_dpages;
1543 size_t psize = env->me_psize, sz = psize, off;
1544 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1545 * For a single page alloc, we init everything after the page header.
1546 * For multi-page, we init the final page; if the caller needed that
1547 * many pages they will be filling in at least up to the last page.
1551 VGMEMP_ALLOC(env, ret, sz);
1552 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1553 env->me_dpages = ret->mp_next;
1556 psize -= off = PAGEHDRSZ;
1561 if ((ret = malloc(sz)) != NULL) {
1562 VGMEMP_ALLOC(env, ret, sz);
1563 if (!(env->me_flags & MDB_NOMEMINIT)) {
1564 memset((char *)ret + off, 0, psize);
1568 txn->mt_flags |= MDB_TXN_ERROR;
1572 /** Free a single page.
1573 * Saves single pages to a list, for future reuse.
1574 * (This is not used for multi-page overflow pages.)
1577 mdb_page_free(MDB_env *env, MDB_page *mp)
1579 mp->mp_next = env->me_dpages;
1580 VGMEMP_FREE(env, mp);
1581 env->me_dpages = mp;
1584 /** Free a dirty page */
1586 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1588 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1589 mdb_page_free(env, dp);
1591 /* large pages just get freed directly */
1592 VGMEMP_FREE(env, dp);
1597 /** Return all dirty pages to dpage list */
1599 mdb_dlist_free(MDB_txn *txn)
1601 MDB_env *env = txn->mt_env;
1602 MDB_ID2L dl = txn->mt_u.dirty_list;
1603 unsigned i, n = dl[0].mid;
1605 for (i = 1; i <= n; i++) {
1606 mdb_dpage_free(env, dl[i].mptr);
1611 /** Loosen or free a single page.
1612 * Saves single pages to a list for future reuse
1613 * in this same txn. It has been pulled from the freeDB
1614 * and already resides on the dirty list, but has been
1615 * deleted. Use these pages first before pulling again
1618 * If the page wasn't dirtied in this txn, just add it
1619 * to this txn's free list.
1622 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1625 pgno_t pgno = mp->mp_pgno;
1627 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1628 if (mc->mc_txn->mt_parent) {
1629 MDB_ID2 *dl = mc->mc_txn->mt_u.dirty_list;
1630 /* If txn has a parent, make sure the page is in our
1634 unsigned x = mdb_mid2l_search(dl, pgno);
1635 if (x <= dl[0].mid && dl[x].mid == pgno) {
1636 if (mp != dl[x].mptr) { /* bad cursor? */
1637 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1638 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
1639 return MDB_CORRUPTED;
1646 /* no parent txn, so it's just ours */
1651 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1653 NEXT_LOOSE_PAGE(mp) = mc->mc_txn->mt_loose_pgs;
1654 mc->mc_txn->mt_loose_pgs = mp;
1655 mp->mp_flags |= P_LOOSE;
1657 int rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, pgno);
1665 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1666 * @param[in] mc A cursor handle for the current operation.
1667 * @param[in] pflags Flags of the pages to update:
1668 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1669 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1670 * @return 0 on success, non-zero on failure.
1673 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1675 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1676 MDB_txn *txn = mc->mc_txn;
1682 int rc = MDB_SUCCESS, level;
1684 /* Mark pages seen by cursors */
1685 if (mc->mc_flags & C_UNTRACK)
1686 mc = NULL; /* will find mc in mt_cursors */
1687 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1688 for (; mc; mc=mc->mc_next) {
1689 if (!(mc->mc_flags & C_INITIALIZED))
1691 for (m3 = mc;; m3 = &mx->mx_cursor) {
1693 for (j=0; j<m3->mc_snum; j++) {
1695 if ((mp->mp_flags & Mask) == pflags)
1696 mp->mp_flags ^= P_KEEP;
1698 mx = m3->mc_xcursor;
1699 /* Proceed to mx if it is at a sub-database */
1700 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1702 if (! (mp && (mp->mp_flags & P_LEAF)))
1704 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1705 if (!(leaf->mn_flags & F_SUBDATA))
1714 /* Mark dirty root pages */
1715 for (i=0; i<txn->mt_numdbs; i++) {
1716 if (txn->mt_dbflags[i] & DB_DIRTY) {
1717 pgno_t pgno = txn->mt_dbs[i].md_root;
1718 if (pgno == P_INVALID)
1720 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1722 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1723 dp->mp_flags ^= P_KEEP;
1731 static int mdb_page_flush(MDB_txn *txn, int keep);
1733 /** Spill pages from the dirty list back to disk.
1734 * This is intended to prevent running into #MDB_TXN_FULL situations,
1735 * but note that they may still occur in a few cases:
1736 * 1) our estimate of the txn size could be too small. Currently this
1737 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1738 * 2) child txns may run out of space if their parents dirtied a
1739 * lot of pages and never spilled them. TODO: we probably should do
1740 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1741 * the parent's dirty_room is below a given threshold.
1743 * Otherwise, if not using nested txns, it is expected that apps will
1744 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1745 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1746 * If the txn never references them again, they can be left alone.
1747 * If the txn only reads them, they can be used without any fuss.
1748 * If the txn writes them again, they can be dirtied immediately without
1749 * going thru all of the work of #mdb_page_touch(). Such references are
1750 * handled by #mdb_page_unspill().
1752 * Also note, we never spill DB root pages, nor pages of active cursors,
1753 * because we'll need these back again soon anyway. And in nested txns,
1754 * we can't spill a page in a child txn if it was already spilled in a
1755 * parent txn. That would alter the parent txns' data even though
1756 * the child hasn't committed yet, and we'd have no way to undo it if
1757 * the child aborted.
1759 * @param[in] m0 cursor A cursor handle identifying the transaction and
1760 * database for which we are checking space.
1761 * @param[in] key For a put operation, the key being stored.
1762 * @param[in] data For a put operation, the data being stored.
1763 * @return 0 on success, non-zero on failure.
1766 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1768 MDB_txn *txn = m0->mc_txn;
1770 MDB_ID2L dl = txn->mt_u.dirty_list;
1771 unsigned int i, j, need;
1774 if (m0->mc_flags & C_SUB)
1777 /* Estimate how much space this op will take */
1778 i = m0->mc_db->md_depth;
1779 /* Named DBs also dirty the main DB */
1780 if (m0->mc_dbi > MAIN_DBI)
1781 i += txn->mt_dbs[MAIN_DBI].md_depth;
1782 /* For puts, roughly factor in the key+data size */
1784 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1785 i += i; /* double it for good measure */
1788 if (txn->mt_dirty_room > i)
1791 if (!txn->mt_spill_pgs) {
1792 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1793 if (!txn->mt_spill_pgs)
1796 /* purge deleted slots */
1797 MDB_IDL sl = txn->mt_spill_pgs;
1798 unsigned int num = sl[0];
1800 for (i=1; i<=num; i++) {
1807 /* Preserve pages which may soon be dirtied again */
1808 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1811 /* Less aggressive spill - we originally spilled the entire dirty list,
1812 * with a few exceptions for cursor pages and DB root pages. But this
1813 * turns out to be a lot of wasted effort because in a large txn many
1814 * of those pages will need to be used again. So now we spill only 1/8th
1815 * of the dirty pages. Testing revealed this to be a good tradeoff,
1816 * better than 1/2, 1/4, or 1/10.
1818 if (need < MDB_IDL_UM_MAX / 8)
1819 need = MDB_IDL_UM_MAX / 8;
1821 /* Save the page IDs of all the pages we're flushing */
1822 /* flush from the tail forward, this saves a lot of shifting later on. */
1823 for (i=dl[0].mid; i && need; i--) {
1824 MDB_ID pn = dl[i].mid << 1;
1826 if (dp->mp_flags & (P_LOOSE|P_KEEP))
1828 /* Can't spill twice, make sure it's not already in a parent's
1831 if (txn->mt_parent) {
1833 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1834 if (tx2->mt_spill_pgs) {
1835 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1836 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1837 dp->mp_flags |= P_KEEP;
1845 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1849 mdb_midl_sort(txn->mt_spill_pgs);
1851 /* Flush the spilled part of dirty list */
1852 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1855 /* Reset any dirty pages we kept that page_flush didn't see */
1856 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1859 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1863 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1865 mdb_find_oldest(MDB_txn *txn)
1868 txnid_t mr, oldest = txn->mt_txnid - 1;
1869 if (txn->mt_env->me_txns) {
1870 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1871 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1882 /** Add a page to the txn's dirty list */
1884 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1887 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
1889 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1890 insert = mdb_mid2l_append;
1892 insert = mdb_mid2l_insert;
1894 mid.mid = mp->mp_pgno;
1896 rc = insert(txn->mt_u.dirty_list, &mid);
1897 mdb_tassert(txn, rc == 0);
1898 txn->mt_dirty_room--;
1901 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1902 * me_pghead and mt_next_pgno.
1904 * If there are free pages available from older transactions, they
1905 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1906 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1907 * and move me_pglast to say which records were consumed. Only this
1908 * function can create me_pghead and move me_pglast/mt_next_pgno.
1909 * @param[in] mc cursor A cursor handle identifying the transaction and
1910 * database for which we are allocating.
1911 * @param[in] num the number of pages to allocate.
1912 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1913 * will always be satisfied by a single contiguous chunk of memory.
1914 * @return 0 on success, non-zero on failure.
1917 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1919 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1920 /* Get at most <Max_retries> more freeDB records once me_pghead
1921 * has enough pages. If not enough, use new pages from the map.
1922 * If <Paranoid> and mc is updating the freeDB, only get new
1923 * records if me_pghead is empty. Then the freelist cannot play
1924 * catch-up with itself by growing while trying to save it.
1926 enum { Paranoid = 1, Max_retries = 500 };
1928 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1930 int rc, retry = num * 20;
1931 MDB_txn *txn = mc->mc_txn;
1932 MDB_env *env = txn->mt_env;
1933 pgno_t pgno, *mop = env->me_pghead;
1934 unsigned i, j, k, mop_len = mop ? mop[0] : 0, n2 = num-1;
1936 txnid_t oldest = 0, last;
1940 /* If there are any loose pages, just use them */
1941 if (num == 1 && txn->mt_loose_pgs) {
1942 np = txn->mt_loose_pgs;
1943 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
1944 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
1952 /* If our dirty list is already full, we can't do anything */
1953 if (txn->mt_dirty_room == 0) {
1958 for (op = MDB_FIRST;; op = MDB_NEXT) {
1961 pgno_t *idl, old_id, new_id;
1963 /* Seek a big enough contiguous page range. Prefer
1964 * pages at the tail, just truncating the list.
1970 if (mop[i-n2] == pgno+n2)
1977 if (op == MDB_FIRST) { /* 1st iteration */
1978 /* Prepare to fetch more and coalesce */
1979 oldest = mdb_find_oldest(txn);
1980 last = env->me_pglast;
1981 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1984 key.mv_data = &last; /* will look up last+1 */
1985 key.mv_size = sizeof(last);
1987 if (Paranoid && mc->mc_dbi == FREE_DBI)
1990 if (Paranoid && retry < 0 && mop_len)
1994 /* Do not fetch more if the record will be too recent */
1997 rc = mdb_cursor_get(&m2, &key, NULL, op);
1999 if (rc == MDB_NOTFOUND)
2003 last = *(txnid_t*)key.mv_data;
2006 np = m2.mc_pg[m2.mc_top];
2007 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2008 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
2011 idl = (MDB_ID *) data.mv_data;
2014 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2019 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2021 mop = env->me_pghead;
2023 env->me_pglast = last;
2025 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2026 last, txn->mt_dbs[FREE_DBI].md_root, i));
2028 DPRINTF(("IDL %"Z"u", idl[k]));
2030 /* Merge in descending sorted order */
2033 mop[0] = (pgno_t)-1;
2037 for (; old_id < new_id; old_id = mop[--j])
2044 /* Use new pages from the map when nothing suitable in the freeDB */
2046 pgno = txn->mt_next_pgno;
2047 if (pgno + num >= env->me_maxpg) {
2048 DPUTS("DB size maxed out");
2054 if (env->me_flags & MDB_WRITEMAP) {
2055 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2057 if (!(np = mdb_page_malloc(txn, num))) {
2063 mop[0] = mop_len -= num;
2064 /* Move any stragglers down */
2065 for (j = i-num; j < mop_len; )
2066 mop[++j] = mop[++i];
2068 txn->mt_next_pgno = pgno + num;
2071 mdb_page_dirty(txn, np);
2077 txn->mt_flags |= MDB_TXN_ERROR;
2081 /** Copy the used portions of a non-overflow page.
2082 * @param[in] dst page to copy into
2083 * @param[in] src page to copy from
2084 * @param[in] psize size of a page
2087 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2089 enum { Align = sizeof(pgno_t) };
2090 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2092 /* If page isn't full, just copy the used portion. Adjust
2093 * alignment so memcpy may copy words instead of bytes.
2095 if ((unused &= -Align) && !IS_LEAF2(src)) {
2096 upper = (upper + PAGEBASE) & -Align;
2097 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2098 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2101 memcpy(dst, src, psize - unused);
2105 /** Pull a page off the txn's spill list, if present.
2106 * If a page being referenced was spilled to disk in this txn, bring
2107 * it back and make it dirty/writable again.
2108 * @param[in] txn the transaction handle.
2109 * @param[in] mp the page being referenced. It must not be dirty.
2110 * @param[out] ret the writable page, if any. ret is unchanged if
2111 * mp wasn't spilled.
2114 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2116 MDB_env *env = txn->mt_env;
2119 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2121 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2122 if (!tx2->mt_spill_pgs)
2124 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2125 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2128 if (txn->mt_dirty_room == 0)
2129 return MDB_TXN_FULL;
2130 if (IS_OVERFLOW(mp))
2134 if (env->me_flags & MDB_WRITEMAP) {
2137 np = mdb_page_malloc(txn, num);
2141 memcpy(np, mp, num * env->me_psize);
2143 mdb_page_copy(np, mp, env->me_psize);
2146 /* If in current txn, this page is no longer spilled.
2147 * If it happens to be the last page, truncate the spill list.
2148 * Otherwise mark it as deleted by setting the LSB.
2150 if (x == txn->mt_spill_pgs[0])
2151 txn->mt_spill_pgs[0]--;
2153 txn->mt_spill_pgs[x] |= 1;
2154 } /* otherwise, if belonging to a parent txn, the
2155 * page remains spilled until child commits
2158 mdb_page_dirty(txn, np);
2159 np->mp_flags |= P_DIRTY;
2167 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2168 * @param[in] mc cursor pointing to the page to be touched
2169 * @return 0 on success, non-zero on failure.
2172 mdb_page_touch(MDB_cursor *mc)
2174 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2175 MDB_txn *txn = mc->mc_txn;
2176 MDB_cursor *m2, *m3;
2180 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2181 if (txn->mt_flags & MDB_TXN_SPILLS) {
2183 rc = mdb_page_unspill(txn, mp, &np);
2189 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2190 (rc = mdb_page_alloc(mc, 1, &np)))
2193 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2194 mp->mp_pgno, pgno));
2195 mdb_cassert(mc, mp->mp_pgno != pgno);
2196 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2197 /* Update the parent page, if any, to point to the new page */
2199 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2200 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2201 SETPGNO(node, pgno);
2203 mc->mc_db->md_root = pgno;
2205 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2206 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2208 /* If txn has a parent, make sure the page is in our
2212 unsigned x = mdb_mid2l_search(dl, pgno);
2213 if (x <= dl[0].mid && dl[x].mid == pgno) {
2214 if (mp != dl[x].mptr) { /* bad cursor? */
2215 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2216 txn->mt_flags |= MDB_TXN_ERROR;
2217 return MDB_CORRUPTED;
2222 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2224 np = mdb_page_malloc(txn, 1);
2229 rc = mdb_mid2l_insert(dl, &mid);
2230 mdb_cassert(mc, rc == 0);
2235 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2237 np->mp_flags |= P_DIRTY;
2240 /* Adjust cursors pointing to mp */
2241 mc->mc_pg[mc->mc_top] = np;
2242 m2 = txn->mt_cursors[mc->mc_dbi];
2243 if (mc->mc_flags & C_SUB) {
2244 for (; m2; m2=m2->mc_next) {
2245 m3 = &m2->mc_xcursor->mx_cursor;
2246 if (m3->mc_snum < mc->mc_snum) continue;
2247 if (m3->mc_pg[mc->mc_top] == mp)
2248 m3->mc_pg[mc->mc_top] = np;
2251 for (; m2; m2=m2->mc_next) {
2252 if (m2->mc_snum < mc->mc_snum) continue;
2253 if (m2->mc_pg[mc->mc_top] == mp) {
2254 m2->mc_pg[mc->mc_top] = np;
2255 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2257 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2259 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2260 if (!(leaf->mn_flags & F_SUBDATA))
2261 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2269 txn->mt_flags |= MDB_TXN_ERROR;
2274 mdb_env_sync(MDB_env *env, int force)
2277 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2278 if (env->me_flags & MDB_WRITEMAP) {
2279 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2280 ? MS_ASYNC : MS_SYNC;
2281 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2284 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2288 if (MDB_FDATASYNC(env->me_fd))
2295 /** Back up parent txn's cursors, then grab the originals for tracking */
2297 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2299 MDB_cursor *mc, *bk;
2304 for (i = src->mt_numdbs; --i >= 0; ) {
2305 if ((mc = src->mt_cursors[i]) != NULL) {
2306 size = sizeof(MDB_cursor);
2308 size += sizeof(MDB_xcursor);
2309 for (; mc; mc = bk->mc_next) {
2315 mc->mc_db = &dst->mt_dbs[i];
2316 /* Kill pointers into src - and dst to reduce abuse: The
2317 * user may not use mc until dst ends. Otherwise we'd...
2319 mc->mc_txn = NULL; /* ...set this to dst */
2320 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2321 if ((mx = mc->mc_xcursor) != NULL) {
2322 *(MDB_xcursor *)(bk+1) = *mx;
2323 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2325 mc->mc_next = dst->mt_cursors[i];
2326 dst->mt_cursors[i] = mc;
2333 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2334 * @param[in] txn the transaction handle.
2335 * @param[in] merge true to keep changes to parent cursors, false to revert.
2336 * @return 0 on success, non-zero on failure.
2339 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2341 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2345 for (i = txn->mt_numdbs; --i >= 0; ) {
2346 for (mc = cursors[i]; mc; mc = next) {
2348 if ((bk = mc->mc_backup) != NULL) {
2350 /* Commit changes to parent txn */
2351 mc->mc_next = bk->mc_next;
2352 mc->mc_backup = bk->mc_backup;
2353 mc->mc_txn = bk->mc_txn;
2354 mc->mc_db = bk->mc_db;
2355 mc->mc_dbflag = bk->mc_dbflag;
2356 if ((mx = mc->mc_xcursor) != NULL)
2357 mx->mx_cursor.mc_txn = bk->mc_txn;
2359 /* Abort nested txn */
2361 if ((mx = mc->mc_xcursor) != NULL)
2362 *mx = *(MDB_xcursor *)(bk+1);
2366 /* Only malloced cursors are permanently tracked. */
2374 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2377 mdb_txn_reset0(MDB_txn *txn, const char *act);
2379 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2385 Pidset = F_SETLK, Pidcheck = F_GETLK
2389 /** Set or check a pid lock. Set returns 0 on success.
2390 * Check returns 0 if the process is certainly dead, nonzero if it may
2391 * be alive (the lock exists or an error happened so we do not know).
2393 * On Windows Pidset is a no-op, we merely check for the existence
2394 * of the process with the given pid. On POSIX we use a single byte
2395 * lock on the lockfile, set at an offset equal to the pid.
2398 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2400 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2403 if (op == Pidcheck) {
2404 h = OpenProcess(env->me_pidquery, FALSE, pid);
2405 /* No documented "no such process" code, but other program use this: */
2407 return ErrCode() != ERROR_INVALID_PARAMETER;
2408 /* A process exists until all handles to it close. Has it exited? */
2409 ret = WaitForSingleObject(h, 0) != 0;
2416 struct flock lock_info;
2417 memset(&lock_info, 0, sizeof(lock_info));
2418 lock_info.l_type = F_WRLCK;
2419 lock_info.l_whence = SEEK_SET;
2420 lock_info.l_start = pid;
2421 lock_info.l_len = 1;
2422 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2423 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2425 } else if ((rc = ErrCode()) == EINTR) {
2433 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2434 * @param[in] txn the transaction handle to initialize
2435 * @return 0 on success, non-zero on failure.
2438 mdb_txn_renew0(MDB_txn *txn)
2440 MDB_env *env = txn->mt_env;
2441 MDB_txninfo *ti = env->me_txns;
2445 int rc, new_notls = 0;
2448 txn->mt_numdbs = env->me_numdbs;
2449 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2451 if (txn->mt_flags & MDB_TXN_RDONLY) {
2453 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2454 txn->mt_txnid = meta->mm_txnid;
2455 txn->mt_u.reader = NULL;
2457 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2458 pthread_getspecific(env->me_txkey);
2460 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2461 return MDB_BAD_RSLOT;
2463 MDB_PID_T pid = env->me_pid;
2464 MDB_THR_T tid = pthread_self();
2466 if (!env->me_live_reader) {
2467 rc = mdb_reader_pid(env, Pidset, pid);
2470 env->me_live_reader = 1;
2474 nr = ti->mti_numreaders;
2475 for (i=0; i<nr; i++)
2476 if (ti->mti_readers[i].mr_pid == 0)
2478 if (i == env->me_maxreaders) {
2479 UNLOCK_MUTEX_R(env);
2480 return MDB_READERS_FULL;
2482 ti->mti_readers[i].mr_pid = pid;
2483 ti->mti_readers[i].mr_tid = tid;
2485 ti->mti_numreaders = ++nr;
2486 /* Save numreaders for un-mutexed mdb_env_close() */
2487 env->me_numreaders = nr;
2488 UNLOCK_MUTEX_R(env);
2490 r = &ti->mti_readers[i];
2491 new_notls = (env->me_flags & MDB_NOTLS);
2492 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2497 txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
2498 txn->mt_u.reader = r;
2499 meta = env->me_metas[txn->mt_txnid & 1];
2505 txn->mt_txnid = ti->mti_txnid;
2506 meta = env->me_metas[txn->mt_txnid & 1];
2508 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2509 txn->mt_txnid = meta->mm_txnid;
2513 if (txn->mt_txnid == mdb_debug_start)
2516 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2517 txn->mt_u.dirty_list = env->me_dirty_list;
2518 txn->mt_u.dirty_list[0].mid = 0;
2519 txn->mt_free_pgs = env->me_free_pgs;
2520 txn->mt_free_pgs[0] = 0;
2521 txn->mt_spill_pgs = NULL;
2523 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2526 /* Copy the DB info and flags */
2527 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2529 /* Moved to here to avoid a data race in read TXNs */
2530 txn->mt_next_pgno = meta->mm_last_pg+1;
2532 for (i=2; i<txn->mt_numdbs; i++) {
2533 x = env->me_dbflags[i];
2534 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2535 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2537 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2539 /* If we didn't ask for a resize, but the size grew, fail */
2540 if (!(env->me_flags & MDB_RESIZING)
2541 && env->me_mapsize < meta->mm_mapsize) {
2542 mdb_txn_reset0(txn, "renew0-mapfail");
2544 txn->mt_u.reader->mr_pid = 0;
2545 txn->mt_u.reader = NULL;
2547 return MDB_MAP_RESIZED;
2554 mdb_txn_renew(MDB_txn *txn)
2558 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2561 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2562 DPUTS("environment had fatal error, must shutdown!");
2566 rc = mdb_txn_renew0(txn);
2567 if (rc == MDB_SUCCESS) {
2568 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2569 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2570 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2576 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2580 int rc, size, tsize = sizeof(MDB_txn);
2582 if (env->me_flags & MDB_FATAL_ERROR) {
2583 DPUTS("environment had fatal error, must shutdown!");
2586 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2589 /* Nested transactions: Max 1 child, write txns only, no writemap */
2590 if (parent->mt_child ||
2591 (flags & MDB_RDONLY) ||
2592 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2593 (env->me_flags & MDB_WRITEMAP))
2595 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2597 tsize = sizeof(MDB_ntxn);
2599 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2600 if (!(flags & MDB_RDONLY)) {
2601 size += env->me_maxdbs * sizeof(MDB_cursor *);
2602 /* child txns use parent's dbiseqs */
2604 size += env->me_maxdbs * sizeof(unsigned int);
2607 if ((txn = calloc(1, size)) == NULL) {
2608 DPRINTF(("calloc: %s", strerror(errno)));
2611 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2612 if (flags & MDB_RDONLY) {
2613 txn->mt_flags |= MDB_TXN_RDONLY;
2614 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2615 txn->mt_dbiseqs = env->me_dbiseqs;
2617 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2619 txn->mt_dbiseqs = parent->mt_dbiseqs;
2620 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2622 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
2623 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
2630 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2631 if (!txn->mt_u.dirty_list ||
2632 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2634 free(txn->mt_u.dirty_list);
2638 txn->mt_txnid = parent->mt_txnid;
2639 txn->mt_dirty_room = parent->mt_dirty_room;
2640 txn->mt_u.dirty_list[0].mid = 0;
2641 txn->mt_spill_pgs = NULL;
2642 txn->mt_next_pgno = parent->mt_next_pgno;
2643 parent->mt_child = txn;
2644 txn->mt_parent = parent;
2645 txn->mt_numdbs = parent->mt_numdbs;
2646 txn->mt_flags = parent->mt_flags;
2647 txn->mt_dbxs = parent->mt_dbxs;
2648 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2649 /* Copy parent's mt_dbflags, but clear DB_NEW */
2650 for (i=0; i<txn->mt_numdbs; i++)
2651 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2653 ntxn = (MDB_ntxn *)txn;
2654 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2655 if (env->me_pghead) {
2656 size = MDB_IDL_SIZEOF(env->me_pghead);
2657 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2659 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2664 rc = mdb_cursor_shadow(parent, txn);
2666 mdb_txn_reset0(txn, "beginchild-fail");
2668 rc = mdb_txn_renew0(txn);
2674 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2675 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2676 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2683 mdb_txn_env(MDB_txn *txn)
2685 if(!txn) return NULL;
2689 /** Export or close DBI handles opened in this txn. */
2691 mdb_dbis_update(MDB_txn *txn, int keep)
2694 MDB_dbi n = txn->mt_numdbs;
2695 MDB_env *env = txn->mt_env;
2696 unsigned char *tdbflags = txn->mt_dbflags;
2698 for (i = n; --i >= 2;) {
2699 if (tdbflags[i] & DB_NEW) {
2701 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2703 char *ptr = env->me_dbxs[i].md_name.mv_data;
2705 env->me_dbxs[i].md_name.mv_data = NULL;
2706 env->me_dbxs[i].md_name.mv_size = 0;
2707 env->me_dbflags[i] = 0;
2708 env->me_dbiseqs[i]++;
2714 if (keep && env->me_numdbs < n)
2718 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2719 * May be called twice for readonly txns: First reset it, then abort.
2720 * @param[in] txn the transaction handle to reset
2721 * @param[in] act why the transaction is being reset
2724 mdb_txn_reset0(MDB_txn *txn, const char *act)
2726 MDB_env *env = txn->mt_env;
2728 /* Close any DBI handles opened in this txn */
2729 mdb_dbis_update(txn, 0);
2731 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2732 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2733 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2735 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2736 if (txn->mt_u.reader) {
2737 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2738 if (!(env->me_flags & MDB_NOTLS))
2739 txn->mt_u.reader = NULL; /* txn does not own reader */
2741 txn->mt_numdbs = 0; /* close nothing if called again */
2742 txn->mt_dbxs = NULL; /* mark txn as reset */
2744 mdb_cursors_close(txn, 0);
2746 if (!(env->me_flags & MDB_WRITEMAP)) {
2747 mdb_dlist_free(txn);
2749 mdb_midl_free(env->me_pghead);
2751 if (txn->mt_parent) {
2752 txn->mt_parent->mt_child = NULL;
2753 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2754 mdb_midl_free(txn->mt_free_pgs);
2755 mdb_midl_free(txn->mt_spill_pgs);
2756 free(txn->mt_u.dirty_list);
2760 if (mdb_midl_shrink(&txn->mt_free_pgs))
2761 env->me_free_pgs = txn->mt_free_pgs;
2762 env->me_pghead = NULL;
2766 /* The writer mutex was locked in mdb_txn_begin. */
2768 UNLOCK_MUTEX_W(env);
2773 mdb_txn_reset(MDB_txn *txn)
2778 /* This call is only valid for read-only txns */
2779 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2782 mdb_txn_reset0(txn, "reset");
2786 mdb_txn_abort(MDB_txn *txn)
2792 mdb_txn_abort(txn->mt_child);
2794 mdb_txn_reset0(txn, "abort");
2795 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2796 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2797 txn->mt_u.reader->mr_pid = 0;
2802 /** Save the freelist as of this transaction to the freeDB.
2803 * This changes the freelist. Keep trying until it stabilizes.
2806 mdb_freelist_save(MDB_txn *txn)
2808 /* env->me_pghead[] can grow and shrink during this call.
2809 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2810 * Page numbers cannot disappear from txn->mt_free_pgs[].
2813 MDB_env *env = txn->mt_env;
2814 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2815 txnid_t pglast = 0, head_id = 0;
2816 pgno_t freecnt = 0, *free_pgs, *mop;
2817 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2819 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2821 if (env->me_pghead) {
2822 /* Make sure first page of freeDB is touched and on freelist */
2823 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2824 if (rc && rc != MDB_NOTFOUND)
2828 /* Dispose of loose pages. Usually they will have all
2829 * been used up by the time we get here.
2831 if (txn->mt_loose_pgs) {
2832 MDB_page *mp = txn->mt_loose_pgs;
2833 /* Just return them to freeDB */
2834 if (env->me_pghead) {
2836 mop = env->me_pghead;
2837 for (; mp; mp = NEXT_LOOSE_PAGE(mp)) {
2838 pgno_t pg = mp->mp_pgno;
2840 for (i = mop[0]; i && mop[i] < pg; i--)
2846 /* Oh well, they were wasted. Put on freelist */
2847 for (; mp; mp = NEXT_LOOSE_PAGE(mp)) {
2848 mdb_midl_append(&txn->mt_free_pgs, mp->mp_pgno);
2851 txn->mt_loose_pgs = NULL;
2854 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2855 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2856 ? SSIZE_MAX : maxfree_1pg;
2859 /* Come back here after each Put() in case freelist changed */
2864 /* If using records from freeDB which we have not yet
2865 * deleted, delete them and any we reserved for me_pghead.
2867 while (pglast < env->me_pglast) {
2868 rc = mdb_cursor_first(&mc, &key, NULL);
2871 pglast = head_id = *(txnid_t *)key.mv_data;
2872 total_room = head_room = 0;
2873 mdb_tassert(txn, pglast <= env->me_pglast);
2874 rc = mdb_cursor_del(&mc, 0);
2879 /* Save the IDL of pages freed by this txn, to a single record */
2880 if (freecnt < txn->mt_free_pgs[0]) {
2882 /* Make sure last page of freeDB is touched and on freelist */
2883 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2884 if (rc && rc != MDB_NOTFOUND)
2887 free_pgs = txn->mt_free_pgs;
2888 /* Write to last page of freeDB */
2889 key.mv_size = sizeof(txn->mt_txnid);
2890 key.mv_data = &txn->mt_txnid;
2892 freecnt = free_pgs[0];
2893 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2894 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2897 /* Retry if mt_free_pgs[] grew during the Put() */
2898 free_pgs = txn->mt_free_pgs;
2899 } while (freecnt < free_pgs[0]);
2900 mdb_midl_sort(free_pgs);
2901 memcpy(data.mv_data, free_pgs, data.mv_size);
2904 unsigned int i = free_pgs[0];
2905 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2906 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2908 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2914 mop = env->me_pghead;
2915 mop_len = mop ? mop[0] : 0;
2917 /* Reserve records for me_pghead[]. Split it if multi-page,
2918 * to avoid searching freeDB for a page range. Use keys in
2919 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2921 if (total_room >= mop_len) {
2922 if (total_room == mop_len || --more < 0)
2924 } else if (head_room >= maxfree_1pg && head_id > 1) {
2925 /* Keep current record (overflow page), add a new one */
2929 /* (Re)write {key = head_id, IDL length = head_room} */
2930 total_room -= head_room;
2931 head_room = mop_len - total_room;
2932 if (head_room > maxfree_1pg && head_id > 1) {
2933 /* Overflow multi-page for part of me_pghead */
2934 head_room /= head_id; /* amortize page sizes */
2935 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2936 } else if (head_room < 0) {
2937 /* Rare case, not bothering to delete this record */
2940 key.mv_size = sizeof(head_id);
2941 key.mv_data = &head_id;
2942 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2943 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2946 /* IDL is initially empty, zero out at least the length */
2947 pgs = (pgno_t *)data.mv_data;
2948 j = head_room > clean_limit ? head_room : 0;
2952 total_room += head_room;
2955 /* Fill in the reserved me_pghead records */
2961 rc = mdb_cursor_first(&mc, &key, &data);
2962 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2963 txnid_t id = *(txnid_t *)key.mv_data;
2964 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2967 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
2969 if (len > mop_len) {
2971 data.mv_size = (len + 1) * sizeof(MDB_ID);
2973 data.mv_data = mop -= len;
2976 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
2978 if (rc || !(mop_len -= len))
2985 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
2986 * @param[in] txn the transaction that's being committed
2987 * @param[in] keep number of initial pages in dirty_list to keep dirty.
2988 * @return 0 on success, non-zero on failure.
2991 mdb_page_flush(MDB_txn *txn, int keep)
2993 MDB_env *env = txn->mt_env;
2994 MDB_ID2L dl = txn->mt_u.dirty_list;
2995 unsigned psize = env->me_psize, j;
2996 int i, pagecount = dl[0].mid, rc;
2997 size_t size = 0, pos = 0;
2999 MDB_page *dp = NULL;
3003 struct iovec iov[MDB_COMMIT_PAGES];
3004 ssize_t wpos = 0, wsize = 0, wres;
3005 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3011 if (env->me_flags & MDB_WRITEMAP) {
3012 /* Clear dirty flags */
3013 while (++i <= pagecount) {
3015 /* Don't flush this page yet */
3016 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3017 dp->mp_flags &= ~P_KEEP;
3021 dp->mp_flags &= ~P_DIRTY;
3026 /* Write the pages */
3028 if (++i <= pagecount) {
3030 /* Don't flush this page yet */
3031 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3032 dp->mp_flags &= ~P_KEEP;
3037 /* clear dirty flag */
3038 dp->mp_flags &= ~P_DIRTY;
3041 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3046 /* Windows actually supports scatter/gather I/O, but only on
3047 * unbuffered file handles. Since we're relying on the OS page
3048 * cache for all our data, that's self-defeating. So we just
3049 * write pages one at a time. We use the ov structure to set
3050 * the write offset, to at least save the overhead of a Seek
3053 DPRINTF(("committing page %"Z"u", pgno));
3054 memset(&ov, 0, sizeof(ov));
3055 ov.Offset = pos & 0xffffffff;
3056 ov.OffsetHigh = pos >> 16 >> 16;
3057 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3059 DPRINTF(("WriteFile: %d", rc));
3063 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3064 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3066 /* Write previous page(s) */
3067 #ifdef MDB_USE_PWRITEV
3068 wres = pwritev(env->me_fd, iov, n, wpos);
3071 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3073 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3075 DPRINTF(("lseek: %s", strerror(rc)));
3078 wres = writev(env->me_fd, iov, n);
3081 if (wres != wsize) {
3084 DPRINTF(("Write error: %s", strerror(rc)));
3086 rc = EIO; /* TODO: Use which error code? */
3087 DPUTS("short write, filesystem full?");
3098 DPRINTF(("committing page %"Z"u", pgno));
3099 next_pos = pos + size;
3100 iov[n].iov_len = size;
3101 iov[n].iov_base = (char *)dp;
3107 for (i = keep; ++i <= pagecount; ) {
3109 /* This is a page we skipped above */
3112 dl[j].mid = dp->mp_pgno;
3115 mdb_dpage_free(env, dp);
3120 txn->mt_dirty_room += i - j;
3126 mdb_txn_commit(MDB_txn *txn)
3132 if (txn == NULL || txn->mt_env == NULL)
3135 if (txn->mt_child) {
3136 rc = mdb_txn_commit(txn->mt_child);
3137 txn->mt_child = NULL;
3144 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3145 mdb_dbis_update(txn, 1);
3146 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
3151 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
3152 DPUTS("error flag is set, can't commit");
3154 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3159 if (txn->mt_parent) {
3160 MDB_txn *parent = txn->mt_parent;
3164 unsigned x, y, len, ps_len;
3166 /* Append our free list to parent's */
3167 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3170 mdb_midl_free(txn->mt_free_pgs);
3171 /* Failures after this must either undo the changes
3172 * to the parent or set MDB_TXN_ERROR in the parent.
3175 parent->mt_next_pgno = txn->mt_next_pgno;
3176 parent->mt_flags = txn->mt_flags;
3178 /* Merge our cursors into parent's and close them */
3179 mdb_cursors_close(txn, 1);
3181 /* Update parent's DB table. */
3182 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3183 parent->mt_numdbs = txn->mt_numdbs;
3184 parent->mt_dbflags[0] = txn->mt_dbflags[0];
3185 parent->mt_dbflags[1] = txn->mt_dbflags[1];
3186 for (i=2; i<txn->mt_numdbs; i++) {
3187 /* preserve parent's DB_NEW status */
3188 x = parent->mt_dbflags[i] & DB_NEW;
3189 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3192 dst = parent->mt_u.dirty_list;
3193 src = txn->mt_u.dirty_list;
3194 /* Remove anything in our dirty list from parent's spill list */
3195 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3197 pspill[0] = (pgno_t)-1;
3198 /* Mark our dirty pages as deleted in parent spill list */
3199 for (i=0, len=src[0].mid; ++i <= len; ) {
3200 MDB_ID pn = src[i].mid << 1;
3201 while (pn > pspill[x])
3203 if (pn == pspill[x]) {
3208 /* Squash deleted pagenums if we deleted any */
3209 for (x=y; ++x <= ps_len; )
3210 if (!(pspill[x] & 1))
3211 pspill[++y] = pspill[x];
3215 /* Find len = length of merging our dirty list with parent's */
3217 dst[0].mid = 0; /* simplify loops */
3218 if (parent->mt_parent) {
3219 len = x + src[0].mid;
3220 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3221 for (i = x; y && i; y--) {
3222 pgno_t yp = src[y].mid;
3223 while (yp < dst[i].mid)
3225 if (yp == dst[i].mid) {
3230 } else { /* Simplify the above for single-ancestor case */
3231 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3233 /* Merge our dirty list with parent's */
3235 for (i = len; y; dst[i--] = src[y--]) {
3236 pgno_t yp = src[y].mid;
3237 while (yp < dst[x].mid)
3238 dst[i--] = dst[x--];
3239 if (yp == dst[x].mid)
3240 free(dst[x--].mptr);
3242 mdb_tassert(txn, i == x);
3244 free(txn->mt_u.dirty_list);
3245 parent->mt_dirty_room = txn->mt_dirty_room;
3246 if (txn->mt_spill_pgs) {
3247 if (parent->mt_spill_pgs) {
3248 /* TODO: Prevent failure here, so parent does not fail */
3249 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3251 parent->mt_flags |= MDB_TXN_ERROR;
3252 mdb_midl_free(txn->mt_spill_pgs);
3253 mdb_midl_sort(parent->mt_spill_pgs);
3255 parent->mt_spill_pgs = txn->mt_spill_pgs;
3259 /* Append our loose page list to parent's */
3260 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(lp))
3262 *lp = txn->mt_loose_pgs;
3264 parent->mt_child = NULL;
3265 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3270 if (txn != env->me_txn) {
3271 DPUTS("attempt to commit unknown transaction");
3276 mdb_cursors_close(txn, 0);
3278 if (!txn->mt_u.dirty_list[0].mid &&
3279 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS))) {
3280 if ((env->me_flags & MDB_RESIZING)
3281 && (rc = mdb_env_write_meta(txn))) {
3287 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3288 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3290 /* Update DB root pointers */
3291 if (txn->mt_numdbs > 2) {
3295 data.mv_size = sizeof(MDB_db);
3297 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3298 for (i = 2; i < txn->mt_numdbs; i++) {
3299 if (txn->mt_dbflags[i] & DB_DIRTY) {
3300 if (TXN_DBI_CHANGED(txn, i)) {
3304 data.mv_data = &txn->mt_dbs[i];
3305 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
3312 rc = mdb_freelist_save(txn);
3316 mdb_midl_free(env->me_pghead);
3317 env->me_pghead = NULL;
3318 if (mdb_midl_shrink(&txn->mt_free_pgs))
3319 env->me_free_pgs = txn->mt_free_pgs;
3325 if ((rc = mdb_page_flush(txn, 0)) ||
3326 (rc = mdb_env_write_meta(txn)))
3332 mdb_dbis_update(txn, 1);
3335 UNLOCK_MUTEX_W(env);
3345 /** Read the environment parameters of a DB environment before
3346 * mapping it into memory.
3347 * @param[in] env the environment handle
3348 * @param[out] meta address of where to store the meta information
3349 * @return 0 on success, non-zero on failure.
3352 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3358 enum { Size = sizeof(pbuf) };
3360 /* We don't know the page size yet, so use a minimum value.
3361 * Read both meta pages so we can use the latest one.
3364 for (i=off=0; i<2; i++, off = meta->mm_psize) {
3368 memset(&ov, 0, sizeof(ov));
3370 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3371 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3374 rc = pread(env->me_fd, &pbuf, Size, off);
3377 if (rc == 0 && off == 0)
3379 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3380 DPRINTF(("read: %s", mdb_strerror(rc)));
3384 p = (MDB_page *)&pbuf;
3386 if (!F_ISSET(p->mp_flags, P_META)) {
3387 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3392 if (m->mm_magic != MDB_MAGIC) {
3393 DPUTS("meta has invalid magic");
3397 if (m->mm_version != MDB_DATA_VERSION) {
3398 DPRINTF(("database is version %u, expected version %u",
3399 m->mm_version, MDB_DATA_VERSION));
3400 return MDB_VERSION_MISMATCH;
3403 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3410 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3412 meta->mm_magic = MDB_MAGIC;
3413 meta->mm_version = MDB_DATA_VERSION;
3414 meta->mm_mapsize = env->me_mapsize;
3415 meta->mm_psize = env->me_psize;
3416 meta->mm_last_pg = 1;
3417 meta->mm_flags = env->me_flags & 0xffff;
3418 meta->mm_flags |= MDB_INTEGERKEY;
3419 meta->mm_dbs[0].md_root = P_INVALID;
3420 meta->mm_dbs[1].md_root = P_INVALID;
3423 /** Write the environment parameters of a freshly created DB environment.
3424 * @param[in] env the environment handle
3425 * @param[out] meta address of where to store the meta information
3426 * @return 0 on success, non-zero on failure.
3429 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3437 memset(&ov, 0, sizeof(ov));
3438 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3440 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3443 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3444 len = pwrite(fd, ptr, size, pos); \
3445 rc = (len >= 0); } while(0)
3448 DPUTS("writing new meta page");
3450 psize = env->me_psize;
3452 mdb_env_init_meta0(env, meta);
3454 p = calloc(2, psize);
3456 p->mp_flags = P_META;
3457 *(MDB_meta *)METADATA(p) = *meta;
3459 q = (MDB_page *)((char *)p + psize);
3461 q->mp_flags = P_META;
3462 *(MDB_meta *)METADATA(q) = *meta;
3464 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3467 else if ((unsigned) len == psize * 2)
3475 /** Update the environment info to commit a transaction.
3476 * @param[in] txn the transaction that's being committed
3477 * @return 0 on success, non-zero on failure.
3480 mdb_env_write_meta(MDB_txn *txn)
3482 MDB_env *env = txn->mt_env;
3483 MDB_meta meta, metab, *mp;
3485 int rc, len, toggle;
3494 /* Sync data and previous metapage before writing a new metapage */
3495 if ((rc = mdb_env_sync(env, 0)) != MDB_SUCCESS)
3498 toggle = txn->mt_txnid & 1;
3499 DPRINTF(("writing meta page %d for root page %"Z"u",
3500 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3502 mp = env->me_metas[toggle];
3504 if (env->me_flags & MDB_WRITEMAP) {
3505 /* Persist any changes of mapsize config */
3506 if (env->me_flags & MDB_RESIZING) {
3507 mp->mm_mapsize = env->me_mapsize;
3508 env->me_flags ^= MDB_RESIZING;
3510 mp->mm_dbs[0] = txn->mt_dbs[0];
3511 mp->mm_dbs[1] = txn->mt_dbs[1];
3512 mp->mm_last_pg = txn->mt_next_pgno - 1;
3513 mp->mm_txnid = txn->mt_txnid;
3514 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3515 unsigned meta_size = env->me_psize;
3516 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3519 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3520 if (meta_size < env->me_os_psize)
3521 meta_size += meta_size;
3526 if (MDB_MSYNC(ptr, meta_size, rc)) {
3533 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3534 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3536 ptr = (char *)&meta;
3537 if (env->me_flags & MDB_RESIZING) {
3538 /* Persist any changes of mapsize config */
3539 meta.mm_mapsize = env->me_mapsize;
3540 off = offsetof(MDB_meta, mm_mapsize);
3541 env->me_flags ^= MDB_RESIZING;
3543 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
3545 len = sizeof(MDB_meta) - off;
3548 meta.mm_dbs[0] = txn->mt_dbs[0];
3549 meta.mm_dbs[1] = txn->mt_dbs[1];
3550 meta.mm_last_pg = txn->mt_next_pgno - 1;
3551 meta.mm_txnid = txn->mt_txnid;
3554 off += env->me_psize;
3557 /* Write to the SYNC fd */
3558 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3559 env->me_fd : env->me_mfd;
3562 memset(&ov, 0, sizeof(ov));
3564 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3568 rc = pwrite(mfd, ptr, len, off);
3571 rc = rc < 0 ? ErrCode() : EIO;
3572 DPUTS("write failed, disk error?");
3573 /* On a failure, the pagecache still contains the new data.
3574 * Write some old data back, to prevent it from being used.
3575 * Use the non-SYNC fd; we know it will fail anyway.
3577 meta.mm_last_pg = metab.mm_last_pg;
3578 meta.mm_txnid = metab.mm_txnid;
3580 memset(&ov, 0, sizeof(ov));
3582 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3584 r2 = pwrite(env->me_fd, ptr, len, off);
3585 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3588 env->me_flags |= MDB_FATAL_ERROR;
3592 /* Memory ordering issues are irrelevant; since the entire writer
3593 * is wrapped by wmutex, all of these changes will become visible
3594 * after the wmutex is unlocked. Since the DB is multi-version,
3595 * readers will get consistent data regardless of how fresh or
3596 * how stale their view of these values is.
3599 env->me_txns->mti_txnid = txn->mt_txnid;
3604 /** Check both meta pages to see which one is newer.
3605 * @param[in] env the environment handle
3606 * @return meta toggle (0 or 1).
3609 mdb_env_pick_meta(const MDB_env *env)
3611 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3615 mdb_env_create(MDB_env **env)
3619 e = calloc(1, sizeof(MDB_env));
3623 e->me_maxreaders = DEFAULT_READERS;
3624 e->me_maxdbs = e->me_numdbs = 2;
3625 e->me_fd = INVALID_HANDLE_VALUE;
3626 e->me_lfd = INVALID_HANDLE_VALUE;
3627 e->me_mfd = INVALID_HANDLE_VALUE;
3628 #ifdef MDB_USE_POSIX_SEM
3629 e->me_rmutex = SEM_FAILED;
3630 e->me_wmutex = SEM_FAILED;
3632 e->me_pid = getpid();
3633 GET_PAGESIZE(e->me_os_psize);
3634 VGMEMP_CREATE(e,0,0);
3640 mdb_env_map(MDB_env *env, void *addr)
3643 unsigned int flags = env->me_flags;
3647 LONG sizelo, sizehi;
3650 if (flags & MDB_RDONLY) {
3651 /* Don't set explicit map size, use whatever exists */
3656 msize = env->me_mapsize;
3657 sizelo = msize & 0xffffffff;
3658 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3660 /* Windows won't create mappings for zero length files.
3661 * and won't map more than the file size.
3662 * Just set the maxsize right now.
3664 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3665 || !SetEndOfFile(env->me_fd)
3666 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3670 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3671 PAGE_READWRITE : PAGE_READONLY,
3672 sizehi, sizelo, NULL);
3675 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3676 FILE_MAP_WRITE : FILE_MAP_READ,
3678 rc = env->me_map ? 0 : ErrCode();
3683 int prot = PROT_READ;
3684 if (flags & MDB_WRITEMAP) {
3686 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3689 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3691 if (env->me_map == MAP_FAILED) {
3696 if (flags & MDB_NORDAHEAD) {
3697 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3699 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3701 #ifdef POSIX_MADV_RANDOM
3702 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3703 #endif /* POSIX_MADV_RANDOM */
3704 #endif /* MADV_RANDOM */
3708 /* Can happen because the address argument to mmap() is just a
3709 * hint. mmap() can pick another, e.g. if the range is in use.
3710 * The MAP_FIXED flag would prevent that, but then mmap could
3711 * instead unmap existing pages to make room for the new map.
3713 if (addr && env->me_map != addr)
3714 return EBUSY; /* TODO: Make a new MDB_* error code? */
3716 p = (MDB_page *)env->me_map;
3717 env->me_metas[0] = METADATA(p);
3718 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3724 mdb_env_set_mapsize(MDB_env *env, size_t size)
3726 /* If env is already open, caller is responsible for making
3727 * sure there are no active txns.
3735 size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3737 if (size < env->me_mapsize) {
3738 /* If the configured size is smaller, make sure it's
3739 * still big enough. Silently round up to minimum if not.
3741 size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3745 /* nothing actually changed */
3746 if (size == env->me_mapsize)
3750 munmap(env->me_map, env->me_mapsize);
3751 env->me_mapsize = size;
3752 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3753 rc = mdb_env_map(env, old);
3757 env->me_flags |= MDB_RESIZING;
3759 env->me_mapsize = size;
3761 env->me_maxpg = env->me_mapsize / env->me_psize;
3766 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3770 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3775 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3777 if (env->me_map || readers < 1)
3779 env->me_maxreaders = readers;
3784 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3786 if (!env || !readers)
3788 *readers = env->me_maxreaders;
3792 /** Further setup required for opening an LMDB environment
3795 mdb_env_open2(MDB_env *env)
3797 unsigned int flags = env->me_flags;
3798 int i, newenv = 0, rc;
3802 /* See if we should use QueryLimited */
3804 if ((rc & 0xff) > 5)
3805 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3807 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3810 memset(&meta, 0, sizeof(meta));
3812 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3815 DPUTS("new mdbenv");
3817 env->me_psize = env->me_os_psize;
3818 if (env->me_psize > MAX_PAGESIZE)
3819 env->me_psize = MAX_PAGESIZE;
3821 env->me_psize = meta.mm_psize;
3824 /* Was a mapsize configured? */
3825 if (!env->me_mapsize) {
3826 /* If this is a new environment, take the default,
3827 * else use the size recorded in the existing env.
3829 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3831 if (env->me_mapsize < meta.mm_mapsize) {
3832 /* If the configured size is smaller, make sure it's
3833 * still big enough. Silently round up to minimum if not.
3835 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3836 if (env->me_mapsize < minsize)
3837 env->me_mapsize = minsize;
3839 if (env->me_mapsize != meta.mm_mapsize)
3840 env->me_flags |= MDB_RESIZING;
3843 rc = mdb_env_map(env, meta.mm_address);
3848 if (flags & MDB_FIXEDMAP)
3849 meta.mm_address = env->me_map;
3850 i = mdb_env_init_meta(env, &meta);
3851 if (i != MDB_SUCCESS) {
3856 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3857 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
3859 #if !(MDB_MAXKEYSIZE)
3860 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
3862 env->me_maxpg = env->me_mapsize / env->me_psize;
3866 int toggle = mdb_env_pick_meta(env);
3867 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3869 DPRINTF(("opened database version %u, pagesize %u",
3870 env->me_metas[0]->mm_version, env->me_psize));
3871 DPRINTF(("using meta page %d", toggle));
3872 DPRINTF(("depth: %u", db->md_depth));
3873 DPRINTF(("entries: %"Z"u", db->md_entries));
3874 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
3875 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
3876 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3877 DPRINTF(("root: %"Z"u", db->md_root));
3885 /** Release a reader thread's slot in the reader lock table.
3886 * This function is called automatically when a thread exits.
3887 * @param[in] ptr This points to the slot in the reader lock table.
3890 mdb_env_reader_dest(void *ptr)
3892 MDB_reader *reader = ptr;
3898 /** Junk for arranging thread-specific callbacks on Windows. This is
3899 * necessarily platform and compiler-specific. Windows supports up
3900 * to 1088 keys. Let's assume nobody opens more than 64 environments
3901 * in a single process, for now. They can override this if needed.
3903 #ifndef MAX_TLS_KEYS
3904 #define MAX_TLS_KEYS 64
3906 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3907 static int mdb_tls_nkeys;
3909 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3913 case DLL_PROCESS_ATTACH: break;
3914 case DLL_THREAD_ATTACH: break;
3915 case DLL_THREAD_DETACH:
3916 for (i=0; i<mdb_tls_nkeys; i++) {
3917 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3919 mdb_env_reader_dest(r);
3923 case DLL_PROCESS_DETACH: break;
3928 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3930 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3934 /* Force some symbol references.
3935 * _tls_used forces the linker to create the TLS directory if not already done
3936 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3938 #pragma comment(linker, "/INCLUDE:_tls_used")
3939 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3940 #pragma const_seg(".CRT$XLB")
3941 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
3942 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3945 #pragma comment(linker, "/INCLUDE:__tls_used")
3946 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3947 #pragma data_seg(".CRT$XLB")
3948 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3950 #endif /* WIN 32/64 */
3951 #endif /* !__GNUC__ */
3954 /** Downgrade the exclusive lock on the region back to shared */
3956 mdb_env_share_locks(MDB_env *env, int *excl)
3958 int rc = 0, toggle = mdb_env_pick_meta(env);
3960 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3965 /* First acquire a shared lock. The Unlock will
3966 * then release the existing exclusive lock.
3968 memset(&ov, 0, sizeof(ov));
3969 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3972 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3978 struct flock lock_info;
3979 /* The shared lock replaces the existing lock */
3980 memset((void *)&lock_info, 0, sizeof(lock_info));
3981 lock_info.l_type = F_RDLCK;
3982 lock_info.l_whence = SEEK_SET;
3983 lock_info.l_start = 0;
3984 lock_info.l_len = 1;
3985 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3986 (rc = ErrCode()) == EINTR) ;
3987 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3994 /** Try to get exlusive lock, otherwise shared.
3995 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3998 mdb_env_excl_lock(MDB_env *env, int *excl)
4002 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4006 memset(&ov, 0, sizeof(ov));
4007 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4014 struct flock lock_info;
4015 memset((void *)&lock_info, 0, sizeof(lock_info));
4016 lock_info.l_type = F_WRLCK;
4017 lock_info.l_whence = SEEK_SET;
4018 lock_info.l_start = 0;
4019 lock_info.l_len = 1;
4020 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4021 (rc = ErrCode()) == EINTR) ;
4025 # ifdef MDB_USE_POSIX_SEM
4026 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
4029 lock_info.l_type = F_RDLCK;
4030 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4031 (rc = ErrCode()) == EINTR) ;
4041 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4043 * @(#) $Revision: 5.1 $
4044 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4045 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4047 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4051 * Please do not copyright this code. This code is in the public domain.
4053 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4054 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4055 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4056 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4057 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4058 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4059 * PERFORMANCE OF THIS SOFTWARE.
4062 * chongo <Landon Curt Noll> /\oo/\
4063 * http://www.isthe.com/chongo/
4065 * Share and Enjoy! :-)
4068 typedef unsigned long long mdb_hash_t;
4069 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4071 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4072 * @param[in] val value to hash
4073 * @param[in] hval initial value for hash
4074 * @return 64 bit hash
4076 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4077 * hval arg on the first call.
4080 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4082 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4083 unsigned char *end = s + val->mv_size;
4085 * FNV-1a hash each octet of the string
4088 /* xor the bottom with the current octet */
4089 hval ^= (mdb_hash_t)*s++;
4091 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4092 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4093 (hval << 7) + (hval << 8) + (hval << 40);
4095 /* return our new hash value */
4099 /** Hash the string and output the encoded hash.
4100 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4101 * very short name limits. We don't care about the encoding being reversible,
4102 * we just want to preserve as many bits of the input as possible in a
4103 * small printable string.
4104 * @param[in] str string to hash
4105 * @param[out] encbuf an array of 11 chars to hold the hash
4107 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4110 mdb_pack85(unsigned long l, char *out)
4114 for (i=0; i<5; i++) {
4115 *out++ = mdb_a85[l % 85];
4121 mdb_hash_enc(MDB_val *val, char *encbuf)
4123 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4125 mdb_pack85(h, encbuf);
4126 mdb_pack85(h>>32, encbuf+5);
4131 /** Open and/or initialize the lock region for the environment.
4132 * @param[in] env The LMDB environment.
4133 * @param[in] lpath The pathname of the file used for the lock region.
4134 * @param[in] mode The Unix permissions for the file, if we create it.
4135 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
4136 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4137 * @return 0 on success, non-zero on failure.
4140 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4143 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4145 # define MDB_ERRCODE_ROFS EROFS
4146 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4147 # define MDB_CLOEXEC O_CLOEXEC
4150 # define MDB_CLOEXEC 0
4157 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
4158 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4159 FILE_ATTRIBUTE_NORMAL, NULL);
4161 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4163 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4165 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4170 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4171 /* Lose record locks when exec*() */
4172 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4173 fcntl(env->me_lfd, F_SETFD, fdflags);
4176 if (!(env->me_flags & MDB_NOTLS)) {
4177 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4180 env->me_flags |= MDB_ENV_TXKEY;
4182 /* Windows TLS callbacks need help finding their TLS info. */
4183 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4187 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4191 /* Try to get exclusive lock. If we succeed, then
4192 * nobody is using the lock region and we should initialize it.
4194 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4197 size = GetFileSize(env->me_lfd, NULL);
4199 size = lseek(env->me_lfd, 0, SEEK_END);
4200 if (size == -1) goto fail_errno;
4202 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4203 if (size < rsize && *excl > 0) {
4205 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4206 || !SetEndOfFile(env->me_lfd))
4209 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4213 size = rsize - sizeof(MDB_txninfo);
4214 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4219 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4221 if (!mh) goto fail_errno;
4222 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4224 if (!env->me_txns) goto fail_errno;
4226 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4228 if (m == MAP_FAILED) goto fail_errno;
4234 BY_HANDLE_FILE_INFORMATION stbuf;
4243 if (!mdb_sec_inited) {
4244 InitializeSecurityDescriptor(&mdb_null_sd,
4245 SECURITY_DESCRIPTOR_REVISION);
4246 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4247 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4248 mdb_all_sa.bInheritHandle = FALSE;
4249 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4252 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4253 idbuf.volume = stbuf.dwVolumeSerialNumber;
4254 idbuf.nhigh = stbuf.nFileIndexHigh;
4255 idbuf.nlow = stbuf.nFileIndexLow;
4256 val.mv_data = &idbuf;
4257 val.mv_size = sizeof(idbuf);
4258 mdb_hash_enc(&val, encbuf);
4259 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4260 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4261 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4262 if (!env->me_rmutex) goto fail_errno;
4263 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4264 if (!env->me_wmutex) goto fail_errno;
4265 #elif defined(MDB_USE_POSIX_SEM)
4274 #if defined(__NetBSD__)
4275 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4277 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4278 idbuf.dev = stbuf.st_dev;
4279 idbuf.ino = stbuf.st_ino;
4280 val.mv_data = &idbuf;
4281 val.mv_size = sizeof(idbuf);
4282 mdb_hash_enc(&val, encbuf);
4283 #ifdef MDB_SHORT_SEMNAMES
4284 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4286 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4287 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4288 /* Clean up after a previous run, if needed: Try to
4289 * remove both semaphores before doing anything else.
4291 sem_unlink(env->me_txns->mti_rmname);
4292 sem_unlink(env->me_txns->mti_wmname);
4293 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4294 O_CREAT|O_EXCL, mode, 1);
4295 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4296 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4297 O_CREAT|O_EXCL, mode, 1);
4298 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4299 #else /* MDB_USE_POSIX_SEM */
4300 pthread_mutexattr_t mattr;
4302 if ((rc = pthread_mutexattr_init(&mattr))
4303 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4304 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
4305 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
4307 pthread_mutexattr_destroy(&mattr);
4308 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4310 env->me_txns->mti_magic = MDB_MAGIC;
4311 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4312 env->me_txns->mti_txnid = 0;
4313 env->me_txns->mti_numreaders = 0;
4316 if (env->me_txns->mti_magic != MDB_MAGIC) {
4317 DPUTS("lock region has invalid magic");
4321 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4322 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4323 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4324 rc = MDB_VERSION_MISMATCH;
4328 if (rc && rc != EACCES && rc != EAGAIN) {
4332 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4333 if (!env->me_rmutex) goto fail_errno;
4334 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4335 if (!env->me_wmutex) goto fail_errno;
4336 #elif defined(MDB_USE_POSIX_SEM)
4337 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4338 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4339 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4340 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4351 /** The name of the lock file in the DB environment */
4352 #define LOCKNAME "/lock.mdb"
4353 /** The name of the data file in the DB environment */
4354 #define DATANAME "/data.mdb"
4355 /** The suffix of the lock file when no subdir is used */
4356 #define LOCKSUFF "-lock"
4357 /** Only a subset of the @ref mdb_env flags can be changed
4358 * at runtime. Changing other flags requires closing the
4359 * environment and re-opening it with the new flags.
4361 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4362 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP| \
4363 MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4365 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4366 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4370 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4372 int oflags, rc, len, excl = -1;
4373 char *lpath, *dpath;
4375 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4379 if (flags & MDB_NOSUBDIR) {
4380 rc = len + sizeof(LOCKSUFF) + len + 1;
4382 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4387 if (flags & MDB_NOSUBDIR) {
4388 dpath = lpath + len + sizeof(LOCKSUFF);
4389 sprintf(lpath, "%s" LOCKSUFF, path);
4390 strcpy(dpath, path);
4392 dpath = lpath + len + sizeof(LOCKNAME);
4393 sprintf(lpath, "%s" LOCKNAME, path);
4394 sprintf(dpath, "%s" DATANAME, path);
4398 flags |= env->me_flags;
4399 if (flags & MDB_RDONLY) {
4400 /* silently ignore WRITEMAP when we're only getting read access */
4401 flags &= ~MDB_WRITEMAP;
4403 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4404 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4407 env->me_flags = flags |= MDB_ENV_ACTIVE;
4411 env->me_path = strdup(path);
4412 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4413 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4414 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4415 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4420 /* For RDONLY, get lockfile after we know datafile exists */
4421 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4422 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4428 if (F_ISSET(flags, MDB_RDONLY)) {
4429 oflags = GENERIC_READ;
4430 len = OPEN_EXISTING;
4432 oflags = GENERIC_READ|GENERIC_WRITE;
4435 mode = FILE_ATTRIBUTE_NORMAL;
4436 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4437 NULL, len, mode, NULL);
4439 if (F_ISSET(flags, MDB_RDONLY))
4442 oflags = O_RDWR | O_CREAT;
4444 env->me_fd = open(dpath, oflags, mode);
4446 if (env->me_fd == INVALID_HANDLE_VALUE) {
4451 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4452 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4457 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4458 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4459 env->me_mfd = env->me_fd;
4461 /* Synchronous fd for meta writes. Needed even with
4462 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4465 len = OPEN_EXISTING;
4466 env->me_mfd = CreateFile(dpath, oflags,
4467 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4468 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4471 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4473 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4478 DPRINTF(("opened dbenv %p", (void *) env));
4480 rc = mdb_env_share_locks(env, &excl);
4484 if (!((flags & MDB_RDONLY) ||
4485 (env->me_pbuf = calloc(1, env->me_psize))))
4491 mdb_env_close0(env, excl);
4497 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4499 mdb_env_close0(MDB_env *env, int excl)
4503 if (!(env->me_flags & MDB_ENV_ACTIVE))
4506 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4507 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4508 free(env->me_dbxs[i].md_name.mv_data);
4511 free(env->me_dbiseqs);
4512 free(env->me_dbflags);
4515 free(env->me_dirty_list);
4516 mdb_midl_free(env->me_free_pgs);
4518 if (env->me_flags & MDB_ENV_TXKEY) {
4519 pthread_key_delete(env->me_txkey);
4521 /* Delete our key from the global list */
4522 for (i=0; i<mdb_tls_nkeys; i++)
4523 if (mdb_tls_keys[i] == env->me_txkey) {
4524 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4532 munmap(env->me_map, env->me_mapsize);
4534 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4535 (void) close(env->me_mfd);
4536 if (env->me_fd != INVALID_HANDLE_VALUE)
4537 (void) close(env->me_fd);
4539 MDB_PID_T pid = env->me_pid;
4540 /* Clearing readers is done in this function because
4541 * me_txkey with its destructor must be disabled first.
4543 for (i = env->me_numreaders; --i >= 0; )
4544 if (env->me_txns->mti_readers[i].mr_pid == pid)
4545 env->me_txns->mti_readers[i].mr_pid = 0;
4547 if (env->me_rmutex) {
4548 CloseHandle(env->me_rmutex);
4549 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4551 /* Windows automatically destroys the mutexes when
4552 * the last handle closes.
4554 #elif defined(MDB_USE_POSIX_SEM)
4555 if (env->me_rmutex != SEM_FAILED) {
4556 sem_close(env->me_rmutex);
4557 if (env->me_wmutex != SEM_FAILED)
4558 sem_close(env->me_wmutex);
4559 /* If we have the filelock: If we are the
4560 * only remaining user, clean up semaphores.
4563 mdb_env_excl_lock(env, &excl);
4565 sem_unlink(env->me_txns->mti_rmname);
4566 sem_unlink(env->me_txns->mti_wmname);
4570 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4572 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4575 /* Unlock the lockfile. Windows would have unlocked it
4576 * after closing anyway, but not necessarily at once.
4578 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4581 (void) close(env->me_lfd);
4584 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4589 mdb_env_close(MDB_env *env)
4596 VGMEMP_DESTROY(env);
4597 while ((dp = env->me_dpages) != NULL) {
4598 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4599 env->me_dpages = dp->mp_next;
4603 mdb_env_close0(env, 0);
4607 /** Compare two items pointing at aligned size_t's */
4609 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4611 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4612 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4615 /** Compare two items pointing at aligned unsigned int's */
4617 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4619 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4620 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4623 /** Compare two items pointing at unsigned ints of unknown alignment.
4624 * Nodes and keys are guaranteed to be 2-byte aligned.
4627 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4629 #if BYTE_ORDER == LITTLE_ENDIAN
4630 unsigned short *u, *c;
4633 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4634 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4637 } while(!x && u > (unsigned short *)a->mv_data);
4640 unsigned short *u, *c, *end;
4643 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4644 u = (unsigned short *)a->mv_data;
4645 c = (unsigned short *)b->mv_data;
4648 } while(!x && u < end);
4653 /** Compare two items pointing at size_t's of unknown alignment. */
4654 #ifdef MISALIGNED_OK
4655 # define mdb_cmp_clong mdb_cmp_long
4657 # define mdb_cmp_clong mdb_cmp_cint
4660 /** Compare two items lexically */
4662 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4669 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4675 diff = memcmp(a->mv_data, b->mv_data, len);
4676 return diff ? diff : len_diff<0 ? -1 : len_diff;
4679 /** Compare two items in reverse byte order */
4681 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4683 const unsigned char *p1, *p2, *p1_lim;
4687 p1_lim = (const unsigned char *)a->mv_data;
4688 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4689 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4691 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4697 while (p1 > p1_lim) {
4698 diff = *--p1 - *--p2;
4702 return len_diff<0 ? -1 : len_diff;
4705 /** Search for key within a page, using binary search.
4706 * Returns the smallest entry larger or equal to the key.
4707 * If exactp is non-null, stores whether the found entry was an exact match
4708 * in *exactp (1 or 0).
4709 * Updates the cursor index with the index of the found entry.
4710 * If no entry larger or equal to the key is found, returns NULL.
4713 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4715 unsigned int i = 0, nkeys;
4718 MDB_page *mp = mc->mc_pg[mc->mc_top];
4719 MDB_node *node = NULL;
4724 nkeys = NUMKEYS(mp);
4726 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4727 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4730 low = IS_LEAF(mp) ? 0 : 1;
4732 cmp = mc->mc_dbx->md_cmp;
4734 /* Branch pages have no data, so if using integer keys,
4735 * alignment is guaranteed. Use faster mdb_cmp_int.
4737 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4738 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4745 nodekey.mv_size = mc->mc_db->md_pad;
4746 node = NODEPTR(mp, 0); /* fake */
4747 while (low <= high) {
4748 i = (low + high) >> 1;
4749 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4750 rc = cmp(key, &nodekey);
4751 DPRINTF(("found leaf index %u [%s], rc = %i",
4752 i, DKEY(&nodekey), rc));
4761 while (low <= high) {
4762 i = (low + high) >> 1;
4764 node = NODEPTR(mp, i);
4765 nodekey.mv_size = NODEKSZ(node);
4766 nodekey.mv_data = NODEKEY(node);
4768 rc = cmp(key, &nodekey);
4771 DPRINTF(("found leaf index %u [%s], rc = %i",
4772 i, DKEY(&nodekey), rc));
4774 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4775 i, DKEY(&nodekey), NODEPGNO(node), rc));
4786 if (rc > 0) { /* Found entry is less than the key. */
4787 i++; /* Skip to get the smallest entry larger than key. */
4789 node = NODEPTR(mp, i);
4792 *exactp = (rc == 0 && nkeys > 0);
4793 /* store the key index */
4794 mc->mc_ki[mc->mc_top] = i;
4796 /* There is no entry larger or equal to the key. */
4799 /* nodeptr is fake for LEAF2 */
4805 mdb_cursor_adjust(MDB_cursor *mc, func)
4809 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4810 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4817 /** Pop a page off the top of the cursor's stack. */
4819 mdb_cursor_pop(MDB_cursor *mc)
4823 MDB_page *top = mc->mc_pg[mc->mc_top];
4829 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4830 DDBI(mc), (void *) mc));
4834 /** Push a page onto the top of the cursor's stack. */
4836 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4838 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4839 DDBI(mc), (void *) mc));
4841 if (mc->mc_snum >= CURSOR_STACK) {
4842 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4843 return MDB_CURSOR_FULL;
4846 mc->mc_top = mc->mc_snum++;
4847 mc->mc_pg[mc->mc_top] = mp;
4848 mc->mc_ki[mc->mc_top] = 0;
4853 /** Find the address of the page corresponding to a given page number.
4854 * @param[in] txn the transaction for this access.
4855 * @param[in] pgno the page number for the page to retrieve.
4856 * @param[out] ret address of a pointer where the page's address will be stored.
4857 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4858 * @return 0 on success, non-zero on failure.
4861 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4863 MDB_env *env = txn->mt_env;
4867 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
4871 MDB_ID2L dl = tx2->mt_u.dirty_list;
4873 /* Spilled pages were dirtied in this txn and flushed
4874 * because the dirty list got full. Bring this page
4875 * back in from the map (but don't unspill it here,
4876 * leave that unless page_touch happens again).
4878 if (tx2->mt_spill_pgs) {
4879 MDB_ID pn = pgno << 1;
4880 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
4881 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
4882 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4887 unsigned x = mdb_mid2l_search(dl, pgno);
4888 if (x <= dl[0].mid && dl[x].mid == pgno) {
4894 } while ((tx2 = tx2->mt_parent) != NULL);
4897 if (pgno < txn->mt_next_pgno) {
4899 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4901 DPRINTF(("page %"Z"u not found", pgno));
4902 txn->mt_flags |= MDB_TXN_ERROR;
4903 return MDB_PAGE_NOTFOUND;
4913 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
4914 * The cursor is at the root page, set up the rest of it.
4917 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
4919 MDB_page *mp = mc->mc_pg[mc->mc_top];
4923 while (IS_BRANCH(mp)) {
4927 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
4928 mdb_cassert(mc, NUMKEYS(mp) > 1);
4929 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
4931 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
4933 if (flags & MDB_PS_LAST)
4934 i = NUMKEYS(mp) - 1;
4937 node = mdb_node_search(mc, key, &exact);
4939 i = NUMKEYS(mp) - 1;
4941 i = mc->mc_ki[mc->mc_top];
4943 mdb_cassert(mc, i > 0);
4947 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
4950 mdb_cassert(mc, i < NUMKEYS(mp));
4951 node = NODEPTR(mp, i);
4953 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4956 mc->mc_ki[mc->mc_top] = i;
4957 if ((rc = mdb_cursor_push(mc, mp)))
4960 if (flags & MDB_PS_MODIFY) {
4961 if ((rc = mdb_page_touch(mc)) != 0)
4963 mp = mc->mc_pg[mc->mc_top];
4968 DPRINTF(("internal error, index points to a %02X page!?",
4970 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4971 return MDB_CORRUPTED;
4974 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
4975 key ? DKEY(key) : "null"));
4976 mc->mc_flags |= C_INITIALIZED;
4977 mc->mc_flags &= ~C_EOF;
4982 /** Search for the lowest key under the current branch page.
4983 * This just bypasses a NUMKEYS check in the current page
4984 * before calling mdb_page_search_root(), because the callers
4985 * are all in situations where the current page is known to
4989 mdb_page_search_lowest(MDB_cursor *mc)
4991 MDB_page *mp = mc->mc_pg[mc->mc_top];
4992 MDB_node *node = NODEPTR(mp, 0);
4995 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4998 mc->mc_ki[mc->mc_top] = 0;
4999 if ((rc = mdb_cursor_push(mc, mp)))
5001 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5004 /** Search for the page a given key should be in.
5005 * Push it and its parent pages on the cursor stack.
5006 * @param[in,out] mc the cursor for this operation.
5007 * @param[in] key the key to search for, or NULL for first/last page.
5008 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5009 * are touched (updated with new page numbers).
5010 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5011 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5012 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5013 * @return 0 on success, non-zero on failure.
5016 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5021 /* Make sure the txn is still viable, then find the root from
5022 * the txn's db table and set it as the root of the cursor's stack.
5024 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
5025 DPUTS("transaction has failed, must abort");
5028 /* Make sure we're using an up-to-date root */
5029 if (*mc->mc_dbflag & DB_STALE) {
5031 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5033 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5034 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5041 MDB_node *leaf = mdb_node_search(&mc2,
5042 &mc->mc_dbx->md_name, &exact);
5044 return MDB_NOTFOUND;
5045 rc = mdb_node_read(mc->mc_txn, leaf, &data);
5048 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5050 /* The txn may not know this DBI, or another process may
5051 * have dropped and recreated the DB with other flags.
5053 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5054 return MDB_INCOMPATIBLE;
5055 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5057 *mc->mc_dbflag &= ~DB_STALE;
5059 root = mc->mc_db->md_root;
5061 if (root == P_INVALID) { /* Tree is empty. */
5062 DPUTS("tree is empty");
5063 return MDB_NOTFOUND;
5067 mdb_cassert(mc, root > 1);
5068 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5069 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
5075 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5076 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5078 if (flags & MDB_PS_MODIFY) {
5079 if ((rc = mdb_page_touch(mc)))
5083 if (flags & MDB_PS_ROOTONLY)
5086 return mdb_page_search_root(mc, key, flags);
5090 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5092 MDB_txn *txn = mc->mc_txn;
5093 pgno_t pg = mp->mp_pgno;
5094 unsigned x = 0, ovpages = mp->mp_pages;
5095 MDB_env *env = txn->mt_env;
5096 MDB_IDL sl = txn->mt_spill_pgs;
5097 MDB_ID pn = pg << 1;
5100 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5101 /* If the page is dirty or on the spill list we just acquired it,
5102 * so we should give it back to our current free list, if any.
5103 * Otherwise put it onto the list of pages we freed in this txn.
5105 * Won't create me_pghead: me_pglast must be inited along with it.
5106 * Unsupported in nested txns: They would need to hide the page
5107 * range in ancestor txns' dirty and spilled lists.
5109 if (env->me_pghead &&
5111 ((mp->mp_flags & P_DIRTY) ||
5112 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5116 MDB_ID2 *dl, ix, iy;
5117 rc = mdb_midl_need(&env->me_pghead, ovpages);
5120 if (!(mp->mp_flags & P_DIRTY)) {
5121 /* This page is no longer spilled */
5128 /* Remove from dirty list */
5129 dl = txn->mt_u.dirty_list;
5131 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5137 mdb_cassert(mc, x > 1);
5139 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5140 txn->mt_flags |= MDB_TXN_ERROR;
5141 return MDB_CORRUPTED;
5144 if (!(env->me_flags & MDB_WRITEMAP))
5145 mdb_dpage_free(env, mp);
5147 /* Insert in me_pghead */
5148 mop = env->me_pghead;
5149 j = mop[0] + ovpages;
5150 for (i = mop[0]; i && mop[i] < pg; i--)
5156 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5160 mc->mc_db->md_overflow_pages -= ovpages;
5164 /** Return the data associated with a given node.
5165 * @param[in] txn The transaction for this operation.
5166 * @param[in] leaf The node being read.
5167 * @param[out] data Updated to point to the node's data.
5168 * @return 0 on success, non-zero on failure.
5171 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5173 MDB_page *omp; /* overflow page */
5177 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5178 data->mv_size = NODEDSZ(leaf);
5179 data->mv_data = NODEDATA(leaf);
5183 /* Read overflow data.
5185 data->mv_size = NODEDSZ(leaf);
5186 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5187 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5188 DPRINTF(("read overflow page %"Z"u failed", pgno));
5191 data->mv_data = METADATA(omp);
5197 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5198 MDB_val *key, MDB_val *data)
5205 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5207 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
5210 if (txn->mt_flags & MDB_TXN_ERROR)
5213 mdb_cursor_init(&mc, txn, dbi, &mx);
5214 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5217 /** Find a sibling for a page.
5218 * Replaces the page at the top of the cursor's stack with the
5219 * specified sibling, if one exists.
5220 * @param[in] mc The cursor for this operation.
5221 * @param[in] move_right Non-zero if the right sibling is requested,
5222 * otherwise the left sibling.
5223 * @return 0 on success, non-zero on failure.
5226 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5232 if (mc->mc_snum < 2) {
5233 return MDB_NOTFOUND; /* root has no siblings */
5237 DPRINTF(("parent page is page %"Z"u, index %u",
5238 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5240 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5241 : (mc->mc_ki[mc->mc_top] == 0)) {
5242 DPRINTF(("no more keys left, moving to %s sibling",
5243 move_right ? "right" : "left"));
5244 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5245 /* undo cursor_pop before returning */
5252 mc->mc_ki[mc->mc_top]++;
5254 mc->mc_ki[mc->mc_top]--;
5255 DPRINTF(("just moving to %s index key %u",
5256 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5258 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5260 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5261 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5262 /* mc will be inconsistent if caller does mc_snum++ as above */
5263 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5267 mdb_cursor_push(mc, mp);
5269 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5274 /** Move the cursor to the next data item. */
5276 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5282 if (mc->mc_flags & C_EOF) {
5283 return MDB_NOTFOUND;
5286 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5288 mp = mc->mc_pg[mc->mc_top];
5290 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5291 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5292 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5293 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5294 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5295 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5296 if (rc == MDB_SUCCESS)
5297 MDB_GET_KEY(leaf, key);
5302 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5303 if (op == MDB_NEXT_DUP)
5304 return MDB_NOTFOUND;
5308 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5309 mdb_dbg_pgno(mp), (void *) mc));
5310 if (mc->mc_flags & C_DEL)
5313 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5314 DPUTS("=====> move to next sibling page");
5315 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5316 mc->mc_flags |= C_EOF;
5319 mp = mc->mc_pg[mc->mc_top];
5320 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5322 mc->mc_ki[mc->mc_top]++;
5325 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5326 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5329 key->mv_size = mc->mc_db->md_pad;
5330 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5334 mdb_cassert(mc, IS_LEAF(mp));
5335 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5337 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5338 mdb_xcursor_init1(mc, leaf);
5341 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5344 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5345 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5346 if (rc != MDB_SUCCESS)
5351 MDB_GET_KEY(leaf, key);
5355 /** Move the cursor to the previous data item. */
5357 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5363 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5365 mp = mc->mc_pg[mc->mc_top];
5367 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5368 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5369 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5370 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5371 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5372 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5373 if (rc == MDB_SUCCESS)
5374 MDB_GET_KEY(leaf, key);
5378 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5379 if (op == MDB_PREV_DUP)
5380 return MDB_NOTFOUND;
5385 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5386 mdb_dbg_pgno(mp), (void *) mc));
5388 if (mc->mc_ki[mc->mc_top] == 0) {
5389 DPUTS("=====> move to prev sibling page");
5390 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5393 mp = mc->mc_pg[mc->mc_top];
5394 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5395 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5397 mc->mc_ki[mc->mc_top]--;
5399 mc->mc_flags &= ~C_EOF;
5401 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5402 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5405 key->mv_size = mc->mc_db->md_pad;
5406 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5410 mdb_cassert(mc, IS_LEAF(mp));
5411 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5413 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5414 mdb_xcursor_init1(mc, leaf);
5417 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5420 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5421 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5422 if (rc != MDB_SUCCESS)
5427 MDB_GET_KEY(leaf, key);
5431 /** Set the cursor on a specific data item. */
5433 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5434 MDB_cursor_op op, int *exactp)
5438 MDB_node *leaf = NULL;
5441 if (key->mv_size == 0)
5442 return MDB_BAD_VALSIZE;
5445 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5447 /* See if we're already on the right page */
5448 if (mc->mc_flags & C_INITIALIZED) {
5451 mp = mc->mc_pg[mc->mc_top];
5453 mc->mc_ki[mc->mc_top] = 0;
5454 return MDB_NOTFOUND;
5456 if (mp->mp_flags & P_LEAF2) {
5457 nodekey.mv_size = mc->mc_db->md_pad;
5458 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5460 leaf = NODEPTR(mp, 0);
5461 MDB_GET_KEY2(leaf, nodekey);
5463 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5465 /* Probably happens rarely, but first node on the page
5466 * was the one we wanted.
5468 mc->mc_ki[mc->mc_top] = 0;
5475 unsigned int nkeys = NUMKEYS(mp);
5477 if (mp->mp_flags & P_LEAF2) {
5478 nodekey.mv_data = LEAF2KEY(mp,
5479 nkeys-1, nodekey.mv_size);
5481 leaf = NODEPTR(mp, nkeys-1);
5482 MDB_GET_KEY2(leaf, nodekey);
5484 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5486 /* last node was the one we wanted */
5487 mc->mc_ki[mc->mc_top] = nkeys-1;
5493 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5494 /* This is definitely the right page, skip search_page */
5495 if (mp->mp_flags & P_LEAF2) {
5496 nodekey.mv_data = LEAF2KEY(mp,
5497 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5499 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5500 MDB_GET_KEY2(leaf, nodekey);
5502 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5504 /* current node was the one we wanted */
5514 /* If any parents have right-sibs, search.
5515 * Otherwise, there's nothing further.
5517 for (i=0; i<mc->mc_top; i++)
5519 NUMKEYS(mc->mc_pg[i])-1)
5521 if (i == mc->mc_top) {
5522 /* There are no other pages */
5523 mc->mc_ki[mc->mc_top] = nkeys;
5524 return MDB_NOTFOUND;
5528 /* There are no other pages */
5529 mc->mc_ki[mc->mc_top] = 0;
5530 if (op == MDB_SET_RANGE && !exactp) {
5534 return MDB_NOTFOUND;
5538 rc = mdb_page_search(mc, key, 0);
5539 if (rc != MDB_SUCCESS)
5542 mp = mc->mc_pg[mc->mc_top];
5543 mdb_cassert(mc, IS_LEAF(mp));
5546 leaf = mdb_node_search(mc, key, exactp);
5547 if (exactp != NULL && !*exactp) {
5548 /* MDB_SET specified and not an exact match. */
5549 return MDB_NOTFOUND;
5553 DPUTS("===> inexact leaf not found, goto sibling");
5554 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5555 return rc; /* no entries matched */
5556 mp = mc->mc_pg[mc->mc_top];
5557 mdb_cassert(mc, IS_LEAF(mp));
5558 leaf = NODEPTR(mp, 0);
5562 mc->mc_flags |= C_INITIALIZED;
5563 mc->mc_flags &= ~C_EOF;
5566 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5567 key->mv_size = mc->mc_db->md_pad;
5568 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5573 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5574 mdb_xcursor_init1(mc, leaf);
5577 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5578 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5579 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5582 if (op == MDB_GET_BOTH) {
5588 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5589 if (rc != MDB_SUCCESS)
5592 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5594 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5596 rc = mc->mc_dbx->md_dcmp(data, &d2);
5598 if (op == MDB_GET_BOTH || rc > 0)
5599 return MDB_NOTFOUND;
5606 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5607 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5612 /* The key already matches in all other cases */
5613 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5614 MDB_GET_KEY(leaf, key);
5615 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5620 /** Move the cursor to the first item in the database. */
5622 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5628 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5630 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5631 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5632 if (rc != MDB_SUCCESS)
5635 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5637 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5638 mc->mc_flags |= C_INITIALIZED;
5639 mc->mc_flags &= ~C_EOF;
5641 mc->mc_ki[mc->mc_top] = 0;
5643 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5644 key->mv_size = mc->mc_db->md_pad;
5645 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5650 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5651 mdb_xcursor_init1(mc, leaf);
5652 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5656 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5660 MDB_GET_KEY(leaf, key);
5664 /** Move the cursor to the last item in the database. */
5666 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5672 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5674 if (!(mc->mc_flags & C_EOF)) {
5676 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5677 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5678 if (rc != MDB_SUCCESS)
5681 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5684 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5685 mc->mc_flags |= C_INITIALIZED|C_EOF;
5686 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5688 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5689 key->mv_size = mc->mc_db->md_pad;
5690 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5695 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5696 mdb_xcursor_init1(mc, leaf);
5697 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5701 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5706 MDB_GET_KEY(leaf, key);
5711 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5716 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5721 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5725 case MDB_GET_CURRENT:
5726 if (!(mc->mc_flags & C_INITIALIZED)) {
5729 MDB_page *mp = mc->mc_pg[mc->mc_top];
5730 int nkeys = NUMKEYS(mp);
5731 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5732 mc->mc_ki[mc->mc_top] = nkeys;
5738 key->mv_size = mc->mc_db->md_pad;
5739 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5741 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5742 MDB_GET_KEY(leaf, key);
5744 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5745 if (mc->mc_flags & C_DEL)
5746 mdb_xcursor_init1(mc, leaf);
5747 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5749 rc = mdb_node_read(mc->mc_txn, leaf, data);
5756 case MDB_GET_BOTH_RANGE:
5761 if (mc->mc_xcursor == NULL) {
5762 rc = MDB_INCOMPATIBLE;
5772 rc = mdb_cursor_set(mc, key, data, op,
5773 op == MDB_SET_RANGE ? NULL : &exact);
5776 case MDB_GET_MULTIPLE:
5777 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5781 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5782 rc = MDB_INCOMPATIBLE;
5786 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5787 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5790 case MDB_NEXT_MULTIPLE:
5795 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5796 rc = MDB_INCOMPATIBLE;
5799 if (!(mc->mc_flags & C_INITIALIZED))
5800 rc = mdb_cursor_first(mc, key, data);
5802 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5803 if (rc == MDB_SUCCESS) {
5804 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5807 mx = &mc->mc_xcursor->mx_cursor;
5808 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5810 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5811 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5819 case MDB_NEXT_NODUP:
5820 if (!(mc->mc_flags & C_INITIALIZED))
5821 rc = mdb_cursor_first(mc, key, data);
5823 rc = mdb_cursor_next(mc, key, data, op);
5827 case MDB_PREV_NODUP:
5828 if (!(mc->mc_flags & C_INITIALIZED)) {
5829 rc = mdb_cursor_last(mc, key, data);
5832 mc->mc_flags |= C_INITIALIZED;
5833 mc->mc_ki[mc->mc_top]++;
5835 rc = mdb_cursor_prev(mc, key, data, op);
5838 rc = mdb_cursor_first(mc, key, data);
5841 mfunc = mdb_cursor_first;
5843 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5847 if (mc->mc_xcursor == NULL) {
5848 rc = MDB_INCOMPATIBLE;
5851 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5855 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
5858 rc = mdb_cursor_last(mc, key, data);
5861 mfunc = mdb_cursor_last;
5864 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
5869 if (mc->mc_flags & C_DEL)
5870 mc->mc_flags ^= C_DEL;
5875 /** Touch all the pages in the cursor stack. Set mc_top.
5876 * Makes sure all the pages are writable, before attempting a write operation.
5877 * @param[in] mc The cursor to operate on.
5880 mdb_cursor_touch(MDB_cursor *mc)
5882 int rc = MDB_SUCCESS;
5884 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5887 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5889 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5890 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5893 *mc->mc_dbflag |= DB_DIRTY;
5898 rc = mdb_page_touch(mc);
5899 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
5900 mc->mc_top = mc->mc_snum-1;
5905 /** Do not spill pages to disk if txn is getting full, may fail instead */
5906 #define MDB_NOSPILL 0x8000
5909 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5912 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5914 MDB_node *leaf = NULL;
5917 MDB_val xdata, *rdata, dkey, olddata;
5919 int do_sub = 0, insert_key, insert_data;
5920 unsigned int mcount = 0, dcount = 0, nospill;
5923 unsigned int nflags;
5926 if (mc == NULL || key == NULL)
5929 env = mc->mc_txn->mt_env;
5931 /* Check this first so counter will always be zero on any
5934 if (flags & MDB_MULTIPLE) {
5935 dcount = data[1].mv_size;
5936 data[1].mv_size = 0;
5937 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5938 return MDB_INCOMPATIBLE;
5941 nospill = flags & MDB_NOSPILL;
5942 flags &= ~MDB_NOSPILL;
5944 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
5945 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
5947 if (key->mv_size-1 >= ENV_MAXKEY(env))
5948 return MDB_BAD_VALSIZE;
5950 #if SIZE_MAX > MAXDATASIZE
5951 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
5952 return MDB_BAD_VALSIZE;
5954 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
5955 return MDB_BAD_VALSIZE;
5958 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
5959 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
5963 if (flags == MDB_CURRENT) {
5964 if (!(mc->mc_flags & C_INITIALIZED))
5967 } else if (mc->mc_db->md_root == P_INVALID) {
5968 /* new database, cursor has nothing to point to */
5971 mc->mc_flags &= ~C_INITIALIZED;
5976 if (flags & MDB_APPEND) {
5978 rc = mdb_cursor_last(mc, &k2, &d2);
5980 rc = mc->mc_dbx->md_cmp(key, &k2);
5983 mc->mc_ki[mc->mc_top]++;
5985 /* new key is <= last key */
5990 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5992 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5993 DPRINTF(("duplicate key [%s]", DKEY(key)));
5995 return MDB_KEYEXIST;
5997 if (rc && rc != MDB_NOTFOUND)
6001 if (mc->mc_flags & C_DEL)
6002 mc->mc_flags ^= C_DEL;
6004 /* Cursor is positioned, check for room in the dirty list */
6006 if (flags & MDB_MULTIPLE) {
6008 xdata.mv_size = data->mv_size * dcount;
6012 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6016 if (rc == MDB_NO_ROOT) {
6018 /* new database, write a root leaf page */
6019 DPUTS("allocating new root leaf page");
6020 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6023 mdb_cursor_push(mc, np);
6024 mc->mc_db->md_root = np->mp_pgno;
6025 mc->mc_db->md_depth++;
6026 *mc->mc_dbflag |= DB_DIRTY;
6027 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6029 np->mp_flags |= P_LEAF2;
6030 mc->mc_flags |= C_INITIALIZED;
6032 /* make sure all cursor pages are writable */
6033 rc2 = mdb_cursor_touch(mc);
6038 insert_key = insert_data = rc;
6040 /* The key does not exist */
6041 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6042 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6043 LEAFSIZE(key, data) > env->me_nodemax)
6045 /* Too big for a node, insert in sub-DB. Set up an empty
6046 * "old sub-page" for prep_subDB to expand to a full page.
6048 fp_flags = P_LEAF|P_DIRTY;
6050 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6051 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6052 olddata.mv_size = PAGEHDRSZ;
6056 /* there's only a key anyway, so this is a no-op */
6057 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6059 unsigned int ksize = mc->mc_db->md_pad;
6060 if (key->mv_size != ksize)
6061 return MDB_BAD_VALSIZE;
6062 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6063 memcpy(ptr, key->mv_data, ksize);
6068 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6069 olddata.mv_size = NODEDSZ(leaf);
6070 olddata.mv_data = NODEDATA(leaf);
6073 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6074 /* Prepare (sub-)page/sub-DB to accept the new item,
6075 * if needed. fp: old sub-page or a header faking
6076 * it. mp: new (sub-)page. offset: growth in page
6077 * size. xdata: node data with new page or DB.
6079 unsigned i, offset = 0;
6080 mp = fp = xdata.mv_data = env->me_pbuf;
6081 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6083 /* Was a single item before, must convert now */
6084 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6085 /* Just overwrite the current item */
6086 if (flags == MDB_CURRENT)
6089 #if UINT_MAX < SIZE_MAX
6090 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6091 mc->mc_dbx->md_dcmp = mdb_cmp_clong;
6093 /* does data match? */
6094 if (!mc->mc_dbx->md_dcmp(data, &olddata)) {
6095 if (flags & MDB_NODUPDATA)
6096 return MDB_KEYEXIST;
6101 /* Back up original data item */
6102 dkey.mv_size = olddata.mv_size;
6103 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6105 /* Make sub-page header for the dup items, with dummy body */
6106 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6107 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6108 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6109 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6110 fp->mp_flags |= P_LEAF2;
6111 fp->mp_pad = data->mv_size;
6112 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6114 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6115 (dkey.mv_size & 1) + (data->mv_size & 1);
6117 fp->mp_upper = xdata.mv_size - PAGEBASE;
6118 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6119 } else if (leaf->mn_flags & F_SUBDATA) {
6120 /* Data is on sub-DB, just store it */
6121 flags |= F_DUPDATA|F_SUBDATA;
6124 /* Data is on sub-page */
6125 fp = olddata.mv_data;
6128 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6129 offset = EVEN(NODESIZE + sizeof(indx_t) +
6133 offset = fp->mp_pad;
6134 if (SIZELEFT(fp) < offset) {
6135 offset *= 4; /* space for 4 more */
6138 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6140 fp->mp_flags |= P_DIRTY;
6141 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6142 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6146 xdata.mv_size = olddata.mv_size + offset;
6149 fp_flags = fp->mp_flags;
6150 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6151 /* Too big for a sub-page, convert to sub-DB */
6152 fp_flags &= ~P_SUBP;
6154 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6155 fp_flags |= P_LEAF2;
6156 dummy.md_pad = fp->mp_pad;
6157 dummy.md_flags = MDB_DUPFIXED;
6158 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6159 dummy.md_flags |= MDB_INTEGERKEY;
6165 dummy.md_branch_pages = 0;
6166 dummy.md_leaf_pages = 1;
6167 dummy.md_overflow_pages = 0;
6168 dummy.md_entries = NUMKEYS(fp);
6169 xdata.mv_size = sizeof(MDB_db);
6170 xdata.mv_data = &dummy;
6171 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6173 offset = env->me_psize - olddata.mv_size;
6174 flags |= F_DUPDATA|F_SUBDATA;
6175 dummy.md_root = mp->mp_pgno;
6178 mp->mp_flags = fp_flags | P_DIRTY;
6179 mp->mp_pad = fp->mp_pad;
6180 mp->mp_lower = fp->mp_lower;
6181 mp->mp_upper = fp->mp_upper + offset;
6182 if (fp_flags & P_LEAF2) {
6183 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6185 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6186 olddata.mv_size - fp->mp_upper - PAGEBASE);
6187 for (i=0; i<NUMKEYS(fp); i++)
6188 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6196 mdb_node_del(mc, 0);
6200 /* overflow page overwrites need special handling */
6201 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6204 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6206 memcpy(&pg, olddata.mv_data, sizeof(pg));
6207 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6209 ovpages = omp->mp_pages;
6211 /* Is the ov page large enough? */
6212 if (ovpages >= dpages) {
6213 if (!(omp->mp_flags & P_DIRTY) &&
6214 (level || (env->me_flags & MDB_WRITEMAP)))
6216 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6219 level = 0; /* dirty in this txn or clean */
6222 if (omp->mp_flags & P_DIRTY) {
6223 /* yes, overwrite it. Note in this case we don't
6224 * bother to try shrinking the page if the new data
6225 * is smaller than the overflow threshold.
6228 /* It is writable only in a parent txn */
6229 size_t sz = (size_t) env->me_psize * ovpages, off;
6230 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6236 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6237 mdb_cassert(mc, rc2 == 0);
6238 if (!(flags & MDB_RESERVE)) {
6239 /* Copy end of page, adjusting alignment so
6240 * compiler may copy words instead of bytes.
6242 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6243 memcpy((size_t *)((char *)np + off),
6244 (size_t *)((char *)omp + off), sz - off);
6247 memcpy(np, omp, sz); /* Copy beginning of page */
6250 SETDSZ(leaf, data->mv_size);
6251 if (F_ISSET(flags, MDB_RESERVE))
6252 data->mv_data = METADATA(omp);
6254 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6258 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6260 } else if (data->mv_size == olddata.mv_size) {
6261 /* same size, just replace it. Note that we could
6262 * also reuse this node if the new data is smaller,
6263 * but instead we opt to shrink the node in that case.
6265 if (F_ISSET(flags, MDB_RESERVE))
6266 data->mv_data = olddata.mv_data;
6267 else if (!(mc->mc_flags & C_SUB))
6268 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6270 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6273 mdb_node_del(mc, 0);
6279 nflags = flags & NODE_ADD_FLAGS;
6280 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6281 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6282 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6283 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6285 nflags |= MDB_SPLIT_REPLACE;
6286 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6288 /* There is room already in this leaf page. */
6289 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6290 if (rc == 0 && insert_key) {
6291 /* Adjust other cursors pointing to mp */
6292 MDB_cursor *m2, *m3;
6293 MDB_dbi dbi = mc->mc_dbi;
6294 unsigned i = mc->mc_top;
6295 MDB_page *mp = mc->mc_pg[i];
6297 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6298 if (mc->mc_flags & C_SUB)
6299 m3 = &m2->mc_xcursor->mx_cursor;
6302 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6303 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6310 if (rc == MDB_SUCCESS) {
6311 /* Now store the actual data in the child DB. Note that we're
6312 * storing the user data in the keys field, so there are strict
6313 * size limits on dupdata. The actual data fields of the child
6314 * DB are all zero size.
6322 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6323 if (flags & MDB_CURRENT) {
6324 xflags = MDB_CURRENT|MDB_NOSPILL;
6326 mdb_xcursor_init1(mc, leaf);
6327 xflags = (flags & MDB_NODUPDATA) ?
6328 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6330 /* converted, write the original data first */
6332 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6336 /* Adjust other cursors pointing to mp */
6338 unsigned i = mc->mc_top;
6339 MDB_page *mp = mc->mc_pg[i];
6341 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6342 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6343 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6344 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6345 mdb_xcursor_init1(m2, leaf);
6349 /* we've done our job */
6352 ecount = mc->mc_xcursor->mx_db.md_entries;
6353 if (flags & MDB_APPENDDUP)
6354 xflags |= MDB_APPEND;
6355 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6356 if (flags & F_SUBDATA) {
6357 void *db = NODEDATA(leaf);
6358 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6360 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6362 /* Increment count unless we just replaced an existing item. */
6364 mc->mc_db->md_entries++;
6366 /* Invalidate txn if we created an empty sub-DB */
6369 /* If we succeeded and the key didn't exist before,
6370 * make sure the cursor is marked valid.
6372 mc->mc_flags |= C_INITIALIZED;
6374 if (flags & MDB_MULTIPLE) {
6377 /* let caller know how many succeeded, if any */
6378 data[1].mv_size = mcount;
6379 if (mcount < dcount) {
6380 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6381 insert_key = insert_data = 0;
6388 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6391 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6396 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6402 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6403 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6405 if (!(mc->mc_flags & C_INITIALIZED))
6408 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6409 return MDB_NOTFOUND;
6411 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6414 rc = mdb_cursor_touch(mc);
6418 mp = mc->mc_pg[mc->mc_top];
6421 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6423 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6424 if (flags & MDB_NODUPDATA) {
6425 /* mdb_cursor_del0() will subtract the final entry */
6426 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6428 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6429 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6431 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6434 /* If sub-DB still has entries, we're done */
6435 if (mc->mc_xcursor->mx_db.md_entries) {
6436 if (leaf->mn_flags & F_SUBDATA) {
6437 /* update subDB info */
6438 void *db = NODEDATA(leaf);
6439 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6442 /* shrink fake page */
6443 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6444 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6445 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6446 /* fix other sub-DB cursors pointed at this fake page */
6447 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6448 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6449 if (m2->mc_pg[mc->mc_top] == mp &&
6450 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6451 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6454 mc->mc_db->md_entries--;
6455 mc->mc_flags |= C_DEL;
6458 /* otherwise fall thru and delete the sub-DB */
6461 if (leaf->mn_flags & F_SUBDATA) {
6462 /* add all the child DB's pages to the free list */
6463 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6469 /* add overflow pages to free list */
6470 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6474 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6475 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6476 (rc = mdb_ovpage_free(mc, omp)))
6481 return mdb_cursor_del0(mc);
6484 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6488 /** Allocate and initialize new pages for a database.
6489 * @param[in] mc a cursor on the database being added to.
6490 * @param[in] flags flags defining what type of page is being allocated.
6491 * @param[in] num the number of pages to allocate. This is usually 1,
6492 * unless allocating overflow pages for a large record.
6493 * @param[out] mp Address of a page, or NULL on failure.
6494 * @return 0 on success, non-zero on failure.
6497 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6502 if ((rc = mdb_page_alloc(mc, num, &np)))
6504 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6505 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6506 np->mp_flags = flags | P_DIRTY;
6507 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
6508 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
6511 mc->mc_db->md_branch_pages++;
6512 else if (IS_LEAF(np))
6513 mc->mc_db->md_leaf_pages++;
6514 else if (IS_OVERFLOW(np)) {
6515 mc->mc_db->md_overflow_pages += num;
6523 /** Calculate the size of a leaf node.
6524 * The size depends on the environment's page size; if a data item
6525 * is too large it will be put onto an overflow page and the node
6526 * size will only include the key and not the data. Sizes are always
6527 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6528 * of the #MDB_node headers.
6529 * @param[in] env The environment handle.
6530 * @param[in] key The key for the node.
6531 * @param[in] data The data for the node.
6532 * @return The number of bytes needed to store the node.
6535 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6539 sz = LEAFSIZE(key, data);
6540 if (sz > env->me_nodemax) {
6541 /* put on overflow page */
6542 sz -= data->mv_size - sizeof(pgno_t);
6545 return EVEN(sz + sizeof(indx_t));
6548 /** Calculate the size of a branch node.
6549 * The size should depend on the environment's page size but since
6550 * we currently don't support spilling large keys onto overflow
6551 * pages, it's simply the size of the #MDB_node header plus the
6552 * size of the key. Sizes are always rounded up to an even number
6553 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6554 * @param[in] env The environment handle.
6555 * @param[in] key The key for the node.
6556 * @return The number of bytes needed to store the node.
6559 mdb_branch_size(MDB_env *env, MDB_val *key)
6564 if (sz > env->me_nodemax) {
6565 /* put on overflow page */
6566 /* not implemented */
6567 /* sz -= key->size - sizeof(pgno_t); */
6570 return sz + sizeof(indx_t);
6573 /** Add a node to the page pointed to by the cursor.
6574 * @param[in] mc The cursor for this operation.
6575 * @param[in] indx The index on the page where the new node should be added.
6576 * @param[in] key The key for the new node.
6577 * @param[in] data The data for the new node, if any.
6578 * @param[in] pgno The page number, if adding a branch node.
6579 * @param[in] flags Flags for the node.
6580 * @return 0 on success, non-zero on failure. Possible errors are:
6582 * <li>ENOMEM - failed to allocate overflow pages for the node.
6583 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6584 * should never happen since all callers already calculate the
6585 * page's free space before calling this function.
6589 mdb_node_add(MDB_cursor *mc, indx_t indx,
6590 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6593 size_t node_size = NODESIZE;
6597 MDB_page *mp = mc->mc_pg[mc->mc_top];
6598 MDB_page *ofp = NULL; /* overflow page */
6601 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
6603 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6604 IS_LEAF(mp) ? "leaf" : "branch",
6605 IS_SUBP(mp) ? "sub-" : "",
6606 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
6607 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6610 /* Move higher keys up one slot. */
6611 int ksize = mc->mc_db->md_pad, dif;
6612 char *ptr = LEAF2KEY(mp, indx, ksize);
6613 dif = NUMKEYS(mp) - indx;
6615 memmove(ptr+ksize, ptr, dif*ksize);
6616 /* insert new key */
6617 memcpy(ptr, key->mv_data, ksize);
6619 /* Just using these for counting */
6620 mp->mp_lower += sizeof(indx_t);
6621 mp->mp_upper -= ksize - sizeof(indx_t);
6625 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6627 node_size += key->mv_size;
6629 mdb_cassert(mc, data);
6630 if (F_ISSET(flags, F_BIGDATA)) {
6631 /* Data already on overflow page. */
6632 node_size += sizeof(pgno_t);
6633 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
6634 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6636 /* Put data on overflow page. */
6637 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6638 data->mv_size, node_size+data->mv_size));
6639 node_size = EVEN(node_size + sizeof(pgno_t));
6640 if ((ssize_t)node_size > room)
6642 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6644 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6648 node_size += data->mv_size;
6651 node_size = EVEN(node_size);
6652 if ((ssize_t)node_size > room)
6656 /* Move higher pointers up one slot. */
6657 for (i = NUMKEYS(mp); i > indx; i--)
6658 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6660 /* Adjust free space offsets. */
6661 ofs = mp->mp_upper - node_size;
6662 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
6663 mp->mp_ptrs[indx] = ofs;
6665 mp->mp_lower += sizeof(indx_t);
6667 /* Write the node data. */
6668 node = NODEPTR(mp, indx);
6669 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6670 node->mn_flags = flags;
6672 SETDSZ(node,data->mv_size);
6677 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6680 mdb_cassert(mc, key);
6682 if (F_ISSET(flags, F_BIGDATA))
6683 memcpy(node->mn_data + key->mv_size, data->mv_data,
6685 else if (F_ISSET(flags, MDB_RESERVE))
6686 data->mv_data = node->mn_data + key->mv_size;
6688 memcpy(node->mn_data + key->mv_size, data->mv_data,
6691 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6693 if (F_ISSET(flags, MDB_RESERVE))
6694 data->mv_data = METADATA(ofp);
6696 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6703 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6704 mdb_dbg_pgno(mp), NUMKEYS(mp)));
6705 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6706 DPRINTF(("node size = %"Z"u", node_size));
6707 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6708 return MDB_PAGE_FULL;
6711 /** Delete the specified node from a page.
6712 * @param[in] mc Cursor pointing to the node to delete.
6713 * @param[in] ksize The size of a node. Only used if the page is
6714 * part of a #MDB_DUPFIXED database.
6717 mdb_node_del(MDB_cursor *mc, int ksize)
6719 MDB_page *mp = mc->mc_pg[mc->mc_top];
6720 indx_t indx = mc->mc_ki[mc->mc_top];
6722 indx_t i, j, numkeys, ptr;
6726 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6727 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
6728 numkeys = NUMKEYS(mp);
6729 mdb_cassert(mc, indx < numkeys);
6732 int x = numkeys - 1 - indx;
6733 base = LEAF2KEY(mp, indx, ksize);
6735 memmove(base, base + ksize, x * ksize);
6736 mp->mp_lower -= sizeof(indx_t);
6737 mp->mp_upper += ksize - sizeof(indx_t);
6741 node = NODEPTR(mp, indx);
6742 sz = NODESIZE + node->mn_ksize;
6744 if (F_ISSET(node->mn_flags, F_BIGDATA))
6745 sz += sizeof(pgno_t);
6747 sz += NODEDSZ(node);
6751 ptr = mp->mp_ptrs[indx];
6752 for (i = j = 0; i < numkeys; i++) {
6754 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6755 if (mp->mp_ptrs[i] < ptr)
6756 mp->mp_ptrs[j] += sz;
6761 base = (char *)mp + mp->mp_upper + PAGEBASE;
6762 memmove(base + sz, base, ptr - mp->mp_upper);
6764 mp->mp_lower -= sizeof(indx_t);
6768 /** Compact the main page after deleting a node on a subpage.
6769 * @param[in] mp The main page to operate on.
6770 * @param[in] indx The index of the subpage on the main page.
6773 mdb_node_shrink(MDB_page *mp, indx_t indx)
6779 indx_t i, numkeys, ptr;
6781 node = NODEPTR(mp, indx);
6782 sp = (MDB_page *)NODEDATA(node);
6783 delta = SIZELEFT(sp);
6784 xp = (MDB_page *)((char *)sp + delta);
6786 /* shift subpage upward */
6788 nsize = NUMKEYS(sp) * sp->mp_pad;
6790 return; /* do not make the node uneven-sized */
6791 memmove(METADATA(xp), METADATA(sp), nsize);
6794 numkeys = NUMKEYS(sp);
6795 for (i=numkeys-1; i>=0; i--)
6796 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6798 xp->mp_upper = sp->mp_lower;
6799 xp->mp_lower = sp->mp_lower;
6800 xp->mp_flags = sp->mp_flags;
6801 xp->mp_pad = sp->mp_pad;
6802 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6804 nsize = NODEDSZ(node) - delta;
6805 SETDSZ(node, nsize);
6807 /* shift lower nodes upward */
6808 ptr = mp->mp_ptrs[indx];
6809 numkeys = NUMKEYS(mp);
6810 for (i = 0; i < numkeys; i++) {
6811 if (mp->mp_ptrs[i] <= ptr)
6812 mp->mp_ptrs[i] += delta;
6815 base = (char *)mp + mp->mp_upper + PAGEBASE;
6816 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6817 mp->mp_upper += delta;
6820 /** Initial setup of a sorted-dups cursor.
6821 * Sorted duplicates are implemented as a sub-database for the given key.
6822 * The duplicate data items are actually keys of the sub-database.
6823 * Operations on the duplicate data items are performed using a sub-cursor
6824 * initialized when the sub-database is first accessed. This function does
6825 * the preliminary setup of the sub-cursor, filling in the fields that
6826 * depend only on the parent DB.
6827 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6830 mdb_xcursor_init0(MDB_cursor *mc)
6832 MDB_xcursor *mx = mc->mc_xcursor;
6834 mx->mx_cursor.mc_xcursor = NULL;
6835 mx->mx_cursor.mc_txn = mc->mc_txn;
6836 mx->mx_cursor.mc_db = &mx->mx_db;
6837 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6838 mx->mx_cursor.mc_dbi = mc->mc_dbi;
6839 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6840 mx->mx_cursor.mc_snum = 0;
6841 mx->mx_cursor.mc_top = 0;
6842 mx->mx_cursor.mc_flags = C_SUB;
6843 mx->mx_dbx.md_name.mv_size = 0;
6844 mx->mx_dbx.md_name.mv_data = NULL;
6845 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6846 mx->mx_dbx.md_dcmp = NULL;
6847 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6850 /** Final setup of a sorted-dups cursor.
6851 * Sets up the fields that depend on the data from the main cursor.
6852 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6853 * @param[in] node The data containing the #MDB_db record for the
6854 * sorted-dup database.
6857 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6859 MDB_xcursor *mx = mc->mc_xcursor;
6861 if (node->mn_flags & F_SUBDATA) {
6862 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6863 mx->mx_cursor.mc_pg[0] = 0;
6864 mx->mx_cursor.mc_snum = 0;
6865 mx->mx_cursor.mc_top = 0;
6866 mx->mx_cursor.mc_flags = C_SUB;
6868 MDB_page *fp = NODEDATA(node);
6869 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6870 mx->mx_db.md_flags = 0;
6871 mx->mx_db.md_depth = 1;
6872 mx->mx_db.md_branch_pages = 0;
6873 mx->mx_db.md_leaf_pages = 1;
6874 mx->mx_db.md_overflow_pages = 0;
6875 mx->mx_db.md_entries = NUMKEYS(fp);
6876 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6877 mx->mx_cursor.mc_snum = 1;
6878 mx->mx_cursor.mc_top = 0;
6879 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6880 mx->mx_cursor.mc_pg[0] = fp;
6881 mx->mx_cursor.mc_ki[0] = 0;
6882 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6883 mx->mx_db.md_flags = MDB_DUPFIXED;
6884 mx->mx_db.md_pad = fp->mp_pad;
6885 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6886 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6889 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
6890 mx->mx_db.md_root));
6891 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
6892 #if UINT_MAX < SIZE_MAX
6893 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6894 mx->mx_dbx.md_cmp = mdb_cmp_clong;
6898 /** Initialize a cursor for a given transaction and database. */
6900 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6903 mc->mc_backup = NULL;
6906 mc->mc_db = &txn->mt_dbs[dbi];
6907 mc->mc_dbx = &txn->mt_dbxs[dbi];
6908 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6913 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6914 mdb_tassert(txn, mx != NULL);
6915 mc->mc_xcursor = mx;
6916 mdb_xcursor_init0(mc);
6918 mc->mc_xcursor = NULL;
6920 if (*mc->mc_dbflag & DB_STALE) {
6921 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6926 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6929 size_t size = sizeof(MDB_cursor);
6931 if (!ret || !TXN_DBI_EXIST(txn, dbi))
6934 if (txn->mt_flags & MDB_TXN_ERROR)
6937 /* Allow read access to the freelist */
6938 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6941 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6942 size += sizeof(MDB_xcursor);
6944 if ((mc = malloc(size)) != NULL) {
6945 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6946 if (txn->mt_cursors) {
6947 mc->mc_next = txn->mt_cursors[dbi];
6948 txn->mt_cursors[dbi] = mc;
6949 mc->mc_flags |= C_UNTRACK;
6961 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6963 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi))
6966 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6969 if (txn->mt_flags & MDB_TXN_ERROR)
6972 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6976 /* Return the count of duplicate data items for the current key */
6978 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6982 if (mc == NULL || countp == NULL)
6985 if (mc->mc_xcursor == NULL)
6986 return MDB_INCOMPATIBLE;
6988 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
6991 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6992 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6995 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
6998 *countp = mc->mc_xcursor->mx_db.md_entries;
7004 mdb_cursor_close(MDB_cursor *mc)
7006 if (mc && !mc->mc_backup) {
7007 /* remove from txn, if tracked */
7008 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7009 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7010 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7012 *prev = mc->mc_next;
7019 mdb_cursor_txn(MDB_cursor *mc)
7021 if (!mc) return NULL;
7026 mdb_cursor_dbi(MDB_cursor *mc)
7031 /** Replace the key for a branch node with a new key.
7032 * @param[in] mc Cursor pointing to the node to operate on.
7033 * @param[in] key The new key to use.
7034 * @return 0 on success, non-zero on failure.
7037 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7043 int delta, ksize, oksize;
7044 indx_t ptr, i, numkeys, indx;
7047 indx = mc->mc_ki[mc->mc_top];
7048 mp = mc->mc_pg[mc->mc_top];
7049 node = NODEPTR(mp, indx);
7050 ptr = mp->mp_ptrs[indx];
7054 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7055 k2.mv_data = NODEKEY(node);
7056 k2.mv_size = node->mn_ksize;
7057 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7059 mdb_dkey(&k2, kbuf2),
7065 /* Sizes must be 2-byte aligned. */
7066 ksize = EVEN(key->mv_size);
7067 oksize = EVEN(node->mn_ksize);
7068 delta = ksize - oksize;
7070 /* Shift node contents if EVEN(key length) changed. */
7072 if (delta > 0 && SIZELEFT(mp) < delta) {
7074 /* not enough space left, do a delete and split */
7075 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7076 pgno = NODEPGNO(node);
7077 mdb_node_del(mc, 0);
7078 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7081 numkeys = NUMKEYS(mp);
7082 for (i = 0; i < numkeys; i++) {
7083 if (mp->mp_ptrs[i] <= ptr)
7084 mp->mp_ptrs[i] -= delta;
7087 base = (char *)mp + mp->mp_upper + PAGEBASE;
7088 len = ptr - mp->mp_upper + NODESIZE;
7089 memmove(base - delta, base, len);
7090 mp->mp_upper -= delta;
7092 node = NODEPTR(mp, indx);
7095 /* But even if no shift was needed, update ksize */
7096 if (node->mn_ksize != key->mv_size)
7097 node->mn_ksize = key->mv_size;
7100 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7106 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7108 /** Move a node from csrc to cdst.
7111 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
7118 unsigned short flags;
7122 /* Mark src and dst as dirty. */
7123 if ((rc = mdb_page_touch(csrc)) ||
7124 (rc = mdb_page_touch(cdst)))
7127 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7128 key.mv_size = csrc->mc_db->md_pad;
7129 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7131 data.mv_data = NULL;
7135 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7136 mdb_cassert(csrc, !((size_t)srcnode & 1));
7137 srcpg = NODEPGNO(srcnode);
7138 flags = srcnode->mn_flags;
7139 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7140 unsigned int snum = csrc->mc_snum;
7142 /* must find the lowest key below src */
7143 rc = mdb_page_search_lowest(csrc);
7146 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7147 key.mv_size = csrc->mc_db->md_pad;
7148 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7150 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7151 key.mv_size = NODEKSZ(s2);
7152 key.mv_data = NODEKEY(s2);
7154 csrc->mc_snum = snum--;
7155 csrc->mc_top = snum;
7157 key.mv_size = NODEKSZ(srcnode);
7158 key.mv_data = NODEKEY(srcnode);
7160 data.mv_size = NODEDSZ(srcnode);
7161 data.mv_data = NODEDATA(srcnode);
7163 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7164 unsigned int snum = cdst->mc_snum;
7167 /* must find the lowest key below dst */
7168 mdb_cursor_copy(cdst, &mn);
7169 rc = mdb_page_search_lowest(&mn);
7172 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7173 bkey.mv_size = mn.mc_db->md_pad;
7174 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7176 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7177 bkey.mv_size = NODEKSZ(s2);
7178 bkey.mv_data = NODEKEY(s2);
7180 mn.mc_snum = snum--;
7183 rc = mdb_update_key(&mn, &bkey);
7188 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7189 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7190 csrc->mc_ki[csrc->mc_top],
7192 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7193 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7195 /* Add the node to the destination page.
7197 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7198 if (rc != MDB_SUCCESS)
7201 /* Delete the node from the source page.
7203 mdb_node_del(csrc, key.mv_size);
7206 /* Adjust other cursors pointing to mp */
7207 MDB_cursor *m2, *m3;
7208 MDB_dbi dbi = csrc->mc_dbi;
7209 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
7211 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7212 if (csrc->mc_flags & C_SUB)
7213 m3 = &m2->mc_xcursor->mx_cursor;
7216 if (m3 == csrc) continue;
7217 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
7218 csrc->mc_ki[csrc->mc_top]) {
7219 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7220 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7225 /* Update the parent separators.
7227 if (csrc->mc_ki[csrc->mc_top] == 0) {
7228 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7229 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7230 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7232 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7233 key.mv_size = NODEKSZ(srcnode);
7234 key.mv_data = NODEKEY(srcnode);
7236 DPRINTF(("update separator for source page %"Z"u to [%s]",
7237 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7238 mdb_cursor_copy(csrc, &mn);
7241 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7244 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7246 indx_t ix = csrc->mc_ki[csrc->mc_top];
7247 nullkey.mv_size = 0;
7248 csrc->mc_ki[csrc->mc_top] = 0;
7249 rc = mdb_update_key(csrc, &nullkey);
7250 csrc->mc_ki[csrc->mc_top] = ix;
7251 mdb_cassert(csrc, rc == MDB_SUCCESS);
7255 if (cdst->mc_ki[cdst->mc_top] == 0) {
7256 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7257 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7258 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7260 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7261 key.mv_size = NODEKSZ(srcnode);
7262 key.mv_data = NODEKEY(srcnode);
7264 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7265 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7266 mdb_cursor_copy(cdst, &mn);
7269 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7272 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7274 indx_t ix = cdst->mc_ki[cdst->mc_top];
7275 nullkey.mv_size = 0;
7276 cdst->mc_ki[cdst->mc_top] = 0;
7277 rc = mdb_update_key(cdst, &nullkey);
7278 cdst->mc_ki[cdst->mc_top] = ix;
7279 mdb_cassert(csrc, rc == MDB_SUCCESS);
7286 /** Merge one page into another.
7287 * The nodes from the page pointed to by \b csrc will
7288 * be copied to the page pointed to by \b cdst and then
7289 * the \b csrc page will be freed.
7290 * @param[in] csrc Cursor pointing to the source page.
7291 * @param[in] cdst Cursor pointing to the destination page.
7292 * @return 0 on success, non-zero on failure.
7295 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7297 MDB_page *psrc, *pdst;
7304 psrc = csrc->mc_pg[csrc->mc_top];
7305 pdst = cdst->mc_pg[cdst->mc_top];
7307 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7309 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7310 mdb_cassert(csrc, cdst->mc_snum > 1);
7312 /* Mark dst as dirty. */
7313 if ((rc = mdb_page_touch(cdst)))
7316 /* Move all nodes from src to dst.
7318 j = nkeys = NUMKEYS(pdst);
7319 if (IS_LEAF2(psrc)) {
7320 key.mv_size = csrc->mc_db->md_pad;
7321 key.mv_data = METADATA(psrc);
7322 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7323 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7324 if (rc != MDB_SUCCESS)
7326 key.mv_data = (char *)key.mv_data + key.mv_size;
7329 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7330 srcnode = NODEPTR(psrc, i);
7331 if (i == 0 && IS_BRANCH(psrc)) {
7334 mdb_cursor_copy(csrc, &mn);
7335 /* must find the lowest key below src */
7336 rc = mdb_page_search_lowest(&mn);
7339 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7340 key.mv_size = mn.mc_db->md_pad;
7341 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7343 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7344 key.mv_size = NODEKSZ(s2);
7345 key.mv_data = NODEKEY(s2);
7348 key.mv_size = srcnode->mn_ksize;
7349 key.mv_data = NODEKEY(srcnode);
7352 data.mv_size = NODEDSZ(srcnode);
7353 data.mv_data = NODEDATA(srcnode);
7354 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7355 if (rc != MDB_SUCCESS)
7360 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7361 pdst->mp_pgno, NUMKEYS(pdst),
7362 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7364 /* Unlink the src page from parent and add to free list.
7367 mdb_node_del(csrc, 0);
7368 if (csrc->mc_ki[csrc->mc_top] == 0) {
7370 rc = mdb_update_key(csrc, &key);
7378 psrc = csrc->mc_pg[csrc->mc_top];
7379 /* If not operating on FreeDB, allow this page to be reused
7380 * in this txn. Otherwise just add to free list.
7382 rc = mdb_page_loose(csrc, psrc);
7386 csrc->mc_db->md_leaf_pages--;
7388 csrc->mc_db->md_branch_pages--;
7390 /* Adjust other cursors pointing to mp */
7391 MDB_cursor *m2, *m3;
7392 MDB_dbi dbi = csrc->mc_dbi;
7394 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7395 if (csrc->mc_flags & C_SUB)
7396 m3 = &m2->mc_xcursor->mx_cursor;
7399 if (m3 == csrc) continue;
7400 if (m3->mc_snum < csrc->mc_snum) continue;
7401 if (m3->mc_pg[csrc->mc_top] == psrc) {
7402 m3->mc_pg[csrc->mc_top] = pdst;
7403 m3->mc_ki[csrc->mc_top] += nkeys;
7408 unsigned int snum = cdst->mc_snum;
7409 uint16_t depth = cdst->mc_db->md_depth;
7410 mdb_cursor_pop(cdst);
7411 rc = mdb_rebalance(cdst);
7412 /* Did the tree shrink? */
7413 if (depth > cdst->mc_db->md_depth)
7415 cdst->mc_snum = snum;
7416 cdst->mc_top = snum-1;
7421 /** Copy the contents of a cursor.
7422 * @param[in] csrc The cursor to copy from.
7423 * @param[out] cdst The cursor to copy to.
7426 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7430 cdst->mc_txn = csrc->mc_txn;
7431 cdst->mc_dbi = csrc->mc_dbi;
7432 cdst->mc_db = csrc->mc_db;
7433 cdst->mc_dbx = csrc->mc_dbx;
7434 cdst->mc_snum = csrc->mc_snum;
7435 cdst->mc_top = csrc->mc_top;
7436 cdst->mc_flags = csrc->mc_flags;
7438 for (i=0; i<csrc->mc_snum; i++) {
7439 cdst->mc_pg[i] = csrc->mc_pg[i];
7440 cdst->mc_ki[i] = csrc->mc_ki[i];
7444 /** Rebalance the tree after a delete operation.
7445 * @param[in] mc Cursor pointing to the page where rebalancing
7447 * @return 0 on success, non-zero on failure.
7450 mdb_rebalance(MDB_cursor *mc)
7454 unsigned int ptop, minkeys;
7458 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7459 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7460 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7461 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7462 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7464 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7465 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7466 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7467 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7471 if (mc->mc_snum < 2) {
7472 MDB_page *mp = mc->mc_pg[0];
7474 DPUTS("Can't rebalance a subpage, ignoring");
7477 if (NUMKEYS(mp) == 0) {
7478 DPUTS("tree is completely empty");
7479 mc->mc_db->md_root = P_INVALID;
7480 mc->mc_db->md_depth = 0;
7481 mc->mc_db->md_leaf_pages = 0;
7482 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7485 /* Adjust cursors pointing to mp */
7488 mc->mc_flags &= ~C_INITIALIZED;
7490 MDB_cursor *m2, *m3;
7491 MDB_dbi dbi = mc->mc_dbi;
7493 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7494 if (mc->mc_flags & C_SUB)
7495 m3 = &m2->mc_xcursor->mx_cursor;
7498 if (m3->mc_snum < mc->mc_snum) continue;
7499 if (m3->mc_pg[0] == mp) {
7502 m3->mc_flags &= ~C_INITIALIZED;
7506 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7508 DPUTS("collapsing root page!");
7509 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7512 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7513 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7516 mc->mc_db->md_depth--;
7517 mc->mc_db->md_branch_pages--;
7518 mc->mc_ki[0] = mc->mc_ki[1];
7519 for (i = 1; i<mc->mc_db->md_depth; i++) {
7520 mc->mc_pg[i] = mc->mc_pg[i+1];
7521 mc->mc_ki[i] = mc->mc_ki[i+1];
7524 /* Adjust other cursors pointing to mp */
7525 MDB_cursor *m2, *m3;
7526 MDB_dbi dbi = mc->mc_dbi;
7528 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7529 if (mc->mc_flags & C_SUB)
7530 m3 = &m2->mc_xcursor->mx_cursor;
7533 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7534 if (m3->mc_pg[0] == mp) {
7537 for (i=0; i<m3->mc_snum; i++) {
7538 m3->mc_pg[i] = m3->mc_pg[i+1];
7539 m3->mc_ki[i] = m3->mc_ki[i+1];
7545 DPUTS("root page doesn't need rebalancing");
7549 /* The parent (branch page) must have at least 2 pointers,
7550 * otherwise the tree is invalid.
7552 ptop = mc->mc_top-1;
7553 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
7555 /* Leaf page fill factor is below the threshold.
7556 * Try to move keys from left or right neighbor, or
7557 * merge with a neighbor page.
7562 mdb_cursor_copy(mc, &mn);
7563 mn.mc_xcursor = NULL;
7565 oldki = mc->mc_ki[mc->mc_top];
7566 if (mc->mc_ki[ptop] == 0) {
7567 /* We're the leftmost leaf in our parent.
7569 DPUTS("reading right neighbor");
7571 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7572 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7575 mn.mc_ki[mn.mc_top] = 0;
7576 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7578 /* There is at least one neighbor to the left.
7580 DPUTS("reading left neighbor");
7582 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7583 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7586 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7587 mc->mc_ki[mc->mc_top] = 0;
7590 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7591 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7592 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7594 /* If the neighbor page is above threshold and has enough keys,
7595 * move one key from it. Otherwise we should try to merge them.
7596 * (A branch page must never have less than 2 keys.)
7598 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7599 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
7600 rc = mdb_node_move(&mn, mc);
7601 if (mc->mc_ki[ptop]) {
7605 if (mc->mc_ki[ptop] == 0) {
7606 rc = mdb_page_merge(&mn, mc);
7608 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
7609 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7610 rc = mdb_page_merge(mc, &mn);
7611 mdb_cursor_copy(&mn, mc);
7613 mc->mc_flags &= ~C_EOF;
7615 mc->mc_ki[mc->mc_top] = oldki;
7619 /** Complete a delete operation started by #mdb_cursor_del(). */
7621 mdb_cursor_del0(MDB_cursor *mc)
7628 ki = mc->mc_ki[mc->mc_top];
7629 mdb_node_del(mc, mc->mc_db->md_pad);
7630 mc->mc_db->md_entries--;
7631 rc = mdb_rebalance(mc);
7633 if (rc == MDB_SUCCESS) {
7634 MDB_cursor *m2, *m3;
7635 MDB_dbi dbi = mc->mc_dbi;
7637 mp = mc->mc_pg[mc->mc_top];
7638 nkeys = NUMKEYS(mp);
7640 /* if mc points past last node in page, find next sibling */
7641 if (mc->mc_ki[mc->mc_top] >= nkeys) {
7642 rc = mdb_cursor_sibling(mc, 1);
7643 if (rc == MDB_NOTFOUND) {
7644 mc->mc_flags |= C_EOF;
7649 /* Adjust other cursors pointing to mp */
7650 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
7651 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
7652 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7654 if (m3 == mc || m3->mc_snum < mc->mc_snum)
7656 if (m3->mc_pg[mc->mc_top] == mp) {
7657 if (m3->mc_ki[mc->mc_top] >= ki) {
7658 m3->mc_flags |= C_DEL;
7659 if (m3->mc_ki[mc->mc_top] > ki)
7660 m3->mc_ki[mc->mc_top]--;
7662 if (m3->mc_ki[mc->mc_top] >= nkeys) {
7663 rc = mdb_cursor_sibling(m3, 1);
7664 if (rc == MDB_NOTFOUND) {
7665 m3->mc_flags |= C_EOF;
7671 mc->mc_flags |= C_DEL;
7675 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7680 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7681 MDB_val *key, MDB_val *data)
7683 if (!key || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
7686 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7687 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7689 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7690 /* must ignore any data */
7694 return mdb_del0(txn, dbi, key, data, 0);
7698 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
7699 MDB_val *key, MDB_val *data, unsigned flags)
7704 MDB_val rdata, *xdata;
7708 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7710 mdb_cursor_init(&mc, txn, dbi, &mx);
7719 flags |= MDB_NODUPDATA;
7721 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7723 /* let mdb_page_split know about this cursor if needed:
7724 * delete will trigger a rebalance; if it needs to move
7725 * a node from one page to another, it will have to
7726 * update the parent's separator key(s). If the new sepkey
7727 * is larger than the current one, the parent page may
7728 * run out of space, triggering a split. We need this
7729 * cursor to be consistent until the end of the rebalance.
7731 mc.mc_flags |= C_UNTRACK;
7732 mc.mc_next = txn->mt_cursors[dbi];
7733 txn->mt_cursors[dbi] = &mc;
7734 rc = mdb_cursor_del(&mc, flags);
7735 txn->mt_cursors[dbi] = mc.mc_next;
7740 /** Split a page and insert a new node.
7741 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7742 * The cursor will be updated to point to the actual page and index where
7743 * the node got inserted after the split.
7744 * @param[in] newkey The key for the newly inserted node.
7745 * @param[in] newdata The data for the newly inserted node.
7746 * @param[in] newpgno The page number, if the new node is a branch node.
7747 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7748 * @return 0 on success, non-zero on failure.
7751 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7752 unsigned int nflags)
7755 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7758 int i, j, split_indx, nkeys, pmax;
7759 MDB_env *env = mc->mc_txn->mt_env;
7761 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7762 MDB_page *copy = NULL;
7763 MDB_page *mp, *rp, *pp;
7768 mp = mc->mc_pg[mc->mc_top];
7769 newindx = mc->mc_ki[mc->mc_top];
7770 nkeys = NUMKEYS(mp);
7772 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
7773 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7774 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
7776 /* Create a right sibling. */
7777 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7779 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7781 if (mc->mc_snum < 2) {
7782 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7784 /* shift current top to make room for new parent */
7785 mc->mc_pg[1] = mc->mc_pg[0];
7786 mc->mc_ki[1] = mc->mc_ki[0];
7789 mc->mc_db->md_root = pp->mp_pgno;
7790 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7791 mc->mc_db->md_depth++;
7794 /* Add left (implicit) pointer. */
7795 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7796 /* undo the pre-push */
7797 mc->mc_pg[0] = mc->mc_pg[1];
7798 mc->mc_ki[0] = mc->mc_ki[1];
7799 mc->mc_db->md_root = mp->mp_pgno;
7800 mc->mc_db->md_depth--;
7807 ptop = mc->mc_top-1;
7808 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7811 mc->mc_flags |= C_SPLITTING;
7812 mdb_cursor_copy(mc, &mn);
7813 mn.mc_pg[mn.mc_top] = rp;
7814 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7816 if (nflags & MDB_APPEND) {
7817 mn.mc_ki[mn.mc_top] = 0;
7819 split_indx = newindx;
7823 split_indx = (nkeys+1) / 2;
7828 unsigned int lsize, rsize, ksize;
7829 /* Move half of the keys to the right sibling */
7830 x = mc->mc_ki[mc->mc_top] - split_indx;
7831 ksize = mc->mc_db->md_pad;
7832 split = LEAF2KEY(mp, split_indx, ksize);
7833 rsize = (nkeys - split_indx) * ksize;
7834 lsize = (nkeys - split_indx) * sizeof(indx_t);
7835 mp->mp_lower -= lsize;
7836 rp->mp_lower += lsize;
7837 mp->mp_upper += rsize - lsize;
7838 rp->mp_upper -= rsize - lsize;
7839 sepkey.mv_size = ksize;
7840 if (newindx == split_indx) {
7841 sepkey.mv_data = newkey->mv_data;
7843 sepkey.mv_data = split;
7846 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7847 memcpy(rp->mp_ptrs, split, rsize);
7848 sepkey.mv_data = rp->mp_ptrs;
7849 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7850 memcpy(ins, newkey->mv_data, ksize);
7851 mp->mp_lower += sizeof(indx_t);
7852 mp->mp_upper -= ksize - sizeof(indx_t);
7855 memcpy(rp->mp_ptrs, split, x * ksize);
7856 ins = LEAF2KEY(rp, x, ksize);
7857 memcpy(ins, newkey->mv_data, ksize);
7858 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7859 rp->mp_lower += sizeof(indx_t);
7860 rp->mp_upper -= ksize - sizeof(indx_t);
7861 mc->mc_ki[mc->mc_top] = x;
7862 mc->mc_pg[mc->mc_top] = rp;
7865 int psize, nsize, k;
7866 /* Maximum free space in an empty page */
7867 pmax = env->me_psize - PAGEHDRSZ;
7869 nsize = mdb_leaf_size(env, newkey, newdata);
7871 nsize = mdb_branch_size(env, newkey);
7872 nsize = EVEN(nsize);
7874 /* grab a page to hold a temporary copy */
7875 copy = mdb_page_malloc(mc->mc_txn, 1);
7880 copy->mp_pgno = mp->mp_pgno;
7881 copy->mp_flags = mp->mp_flags;
7882 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
7883 copy->mp_upper = env->me_psize - PAGEBASE;
7885 /* prepare to insert */
7886 for (i=0, j=0; i<nkeys; i++) {
7888 copy->mp_ptrs[j++] = 0;
7890 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
7893 /* When items are relatively large the split point needs
7894 * to be checked, because being off-by-one will make the
7895 * difference between success or failure in mdb_node_add.
7897 * It's also relevant if a page happens to be laid out
7898 * such that one half of its nodes are all "small" and
7899 * the other half of its nodes are "large." If the new
7900 * item is also "large" and falls on the half with
7901 * "large" nodes, it also may not fit.
7903 * As a final tweak, if the new item goes on the last
7904 * spot on the page (and thus, onto the new page), bias
7905 * the split so the new page is emptier than the old page.
7906 * This yields better packing during sequential inserts.
7908 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
7909 /* Find split point */
7911 if (newindx <= split_indx || newindx >= nkeys) {
7913 k = newindx >= nkeys ? nkeys : split_indx+2;
7918 for (; i!=k; i+=j) {
7923 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
7924 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7926 if (F_ISSET(node->mn_flags, F_BIGDATA))
7927 psize += sizeof(pgno_t);
7929 psize += NODEDSZ(node);
7931 psize = EVEN(psize);
7933 if (psize > pmax || i == k-j) {
7934 split_indx = i + (j<0);
7939 if (split_indx == newindx) {
7940 sepkey.mv_size = newkey->mv_size;
7941 sepkey.mv_data = newkey->mv_data;
7943 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
7944 sepkey.mv_size = node->mn_ksize;
7945 sepkey.mv_data = NODEKEY(node);
7950 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
7952 /* Copy separator key to the parent.
7954 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
7958 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7963 if (mn.mc_snum == mc->mc_snum) {
7964 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7965 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7966 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7967 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7972 /* Right page might now have changed parent.
7973 * Check if left page also changed parent.
7975 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7976 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7977 for (i=0; i<ptop; i++) {
7978 mc->mc_pg[i] = mn.mc_pg[i];
7979 mc->mc_ki[i] = mn.mc_ki[i];
7981 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7982 if (mn.mc_ki[ptop]) {
7983 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7985 /* find right page's left sibling */
7986 mc->mc_ki[ptop] = mn.mc_ki[ptop];
7987 mdb_cursor_sibling(mc, 0);
7992 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7995 mc->mc_flags ^= C_SPLITTING;
7996 if (rc != MDB_SUCCESS) {
7999 if (nflags & MDB_APPEND) {
8000 mc->mc_pg[mc->mc_top] = rp;
8001 mc->mc_ki[mc->mc_top] = 0;
8002 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8005 for (i=0; i<mc->mc_top; i++)
8006 mc->mc_ki[i] = mn.mc_ki[i];
8007 } else if (!IS_LEAF2(mp)) {
8009 mc->mc_pg[mc->mc_top] = rp;
8014 rkey.mv_data = newkey->mv_data;
8015 rkey.mv_size = newkey->mv_size;
8021 /* Update index for the new key. */
8022 mc->mc_ki[mc->mc_top] = j;
8024 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8025 rkey.mv_data = NODEKEY(node);
8026 rkey.mv_size = node->mn_ksize;
8028 xdata.mv_data = NODEDATA(node);
8029 xdata.mv_size = NODEDSZ(node);
8032 pgno = NODEPGNO(node);
8033 flags = node->mn_flags;
8036 if (!IS_LEAF(mp) && j == 0) {
8037 /* First branch index doesn't need key data. */
8041 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8047 mc->mc_pg[mc->mc_top] = copy;
8052 } while (i != split_indx);
8054 nkeys = NUMKEYS(copy);
8055 for (i=0; i<nkeys; i++)
8056 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8057 mp->mp_lower = copy->mp_lower;
8058 mp->mp_upper = copy->mp_upper;
8059 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8060 env->me_psize - copy->mp_upper - PAGEBASE);
8062 /* reset back to original page */
8063 if (newindx < split_indx) {
8064 mc->mc_pg[mc->mc_top] = mp;
8065 if (nflags & MDB_RESERVE) {
8066 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
8067 if (!(node->mn_flags & F_BIGDATA))
8068 newdata->mv_data = NODEDATA(node);
8071 mc->mc_pg[mc->mc_top] = rp;
8073 /* Make sure mc_ki is still valid.
8075 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8076 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8077 for (i=0; i<=ptop; i++) {
8078 mc->mc_pg[i] = mn.mc_pg[i];
8079 mc->mc_ki[i] = mn.mc_ki[i];
8086 /* Adjust other cursors pointing to mp */
8087 MDB_cursor *m2, *m3;
8088 MDB_dbi dbi = mc->mc_dbi;
8089 int fixup = NUMKEYS(mp);
8091 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8092 if (mc->mc_flags & C_SUB)
8093 m3 = &m2->mc_xcursor->mx_cursor;
8098 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8100 if (m3->mc_flags & C_SPLITTING)
8105 for (k=m3->mc_top; k>=0; k--) {
8106 m3->mc_ki[k+1] = m3->mc_ki[k];
8107 m3->mc_pg[k+1] = m3->mc_pg[k];
8109 if (m3->mc_ki[0] >= split_indx) {
8114 m3->mc_pg[0] = mc->mc_pg[0];
8118 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8119 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8120 m3->mc_ki[mc->mc_top]++;
8121 if (m3->mc_ki[mc->mc_top] >= fixup) {
8122 m3->mc_pg[mc->mc_top] = rp;
8123 m3->mc_ki[mc->mc_top] -= fixup;
8124 m3->mc_ki[ptop] = mn.mc_ki[ptop];
8126 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8127 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8132 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8135 if (copy) /* tmp page */
8136 mdb_page_free(env, copy);
8138 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8143 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8144 MDB_val *key, MDB_val *data, unsigned int flags)
8149 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8152 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
8155 mdb_cursor_init(&mc, txn, dbi, &mx);
8156 return mdb_cursor_put(&mc, key, data, flags);
8160 #define MDB_WBUF (1024*1024)
8163 /** State needed for a compacting copy. */
8164 typedef struct mdb_copy {
8165 pthread_mutex_t mc_mutex;
8166 pthread_cond_t mc_cond;
8173 pgno_t mc_next_pgno;
8176 volatile int mc_new;
8181 /** Dedicated writer thread for compacting copy. */
8182 static THREAD_RET ESECT
8183 mdb_env_copythr(void *arg)
8187 int toggle = 0, wsize, rc;
8190 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8193 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8196 pthread_mutex_lock(&my->mc_mutex);
8198 pthread_cond_signal(&my->mc_cond);
8201 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8202 if (my->mc_new < 0) {
8207 wsize = my->mc_wlen[toggle];
8208 ptr = my->mc_wbuf[toggle];
8211 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8215 } else if (len > 0) {
8229 /* If there's an overflow page tail, write it too */
8230 if (my->mc_olen[toggle]) {
8231 wsize = my->mc_olen[toggle];
8232 ptr = my->mc_over[toggle];
8233 my->mc_olen[toggle] = 0;
8236 my->mc_wlen[toggle] = 0;
8238 pthread_cond_signal(&my->mc_cond);
8240 pthread_cond_signal(&my->mc_cond);
8241 pthread_mutex_unlock(&my->mc_mutex);
8242 return (THREAD_RET)0;
8246 /** Tell the writer thread there's a buffer ready to write */
8248 mdb_env_cthr_toggle(mdb_copy *my, int st)
8250 int toggle = my->mc_toggle ^ 1;
8251 pthread_mutex_lock(&my->mc_mutex);
8252 if (my->mc_status) {
8253 pthread_mutex_unlock(&my->mc_mutex);
8254 return my->mc_status;
8256 while (my->mc_new == 1)
8257 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8259 my->mc_toggle = toggle;
8260 pthread_cond_signal(&my->mc_cond);
8261 pthread_mutex_unlock(&my->mc_mutex);
8265 /** Depth-first tree traversal for compacting copy. */
8267 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8270 MDB_txn *txn = my->mc_txn;
8272 MDB_page *mo, *mp, *leaf;
8277 /* Empty DB, nothing to do */
8278 if (*pg == P_INVALID)
8285 rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
8288 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8292 /* Make cursor pages writable */
8293 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8297 for (i=0; i<mc.mc_top; i++) {
8298 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8299 mc.mc_pg[i] = (MDB_page *)ptr;
8300 ptr += my->mc_env->me_psize;
8303 /* This is writable space for a leaf page. Usually not needed. */
8304 leaf = (MDB_page *)ptr;
8306 toggle = my->mc_toggle;
8307 while (mc.mc_snum > 0) {
8309 mp = mc.mc_pg[mc.mc_top];
8313 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8314 for (i=0; i<n; i++) {
8315 ni = NODEPTR(mp, i);
8316 if (ni->mn_flags & F_BIGDATA) {
8320 /* Need writable leaf */
8322 mc.mc_pg[mc.mc_top] = leaf;
8323 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8325 ni = NODEPTR(mp, i);
8328 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8329 rc = mdb_page_get(txn, pg, &omp, NULL);
8332 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8333 rc = mdb_env_cthr_toggle(my, 1);
8336 toggle = my->mc_toggle;
8338 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8339 memcpy(mo, omp, my->mc_env->me_psize);
8340 mo->mp_pgno = my->mc_next_pgno;
8341 my->mc_next_pgno += omp->mp_pages;
8342 my->mc_wlen[toggle] += my->mc_env->me_psize;
8343 if (omp->mp_pages > 1) {
8344 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
8345 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
8346 rc = mdb_env_cthr_toggle(my, 1);
8349 toggle = my->mc_toggle;
8351 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
8352 } else if (ni->mn_flags & F_SUBDATA) {
8355 /* Need writable leaf */
8357 mc.mc_pg[mc.mc_top] = leaf;
8358 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8360 ni = NODEPTR(mp, i);
8363 memcpy(&db, NODEDATA(ni), sizeof(db));
8364 my->mc_toggle = toggle;
8365 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
8368 toggle = my->mc_toggle;
8369 memcpy(NODEDATA(ni), &db, sizeof(db));
8374 mc.mc_ki[mc.mc_top]++;
8375 if (mc.mc_ki[mc.mc_top] < n) {
8378 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
8380 rc = mdb_page_get(txn, pg, &mp, NULL);
8385 mc.mc_ki[mc.mc_top] = 0;
8386 if (IS_BRANCH(mp)) {
8387 /* Whenever we advance to a sibling branch page,
8388 * we must proceed all the way down to its first leaf.
8390 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
8393 mc.mc_pg[mc.mc_top] = mp;
8397 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8398 rc = mdb_env_cthr_toggle(my, 1);
8401 toggle = my->mc_toggle;
8403 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8404 mdb_page_copy(mo, mp, my->mc_env->me_psize);
8405 mo->mp_pgno = my->mc_next_pgno++;
8406 my->mc_wlen[toggle] += my->mc_env->me_psize;
8408 /* Update parent if there is one */
8409 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
8410 SETPGNO(ni, mo->mp_pgno);
8411 mdb_cursor_pop(&mc);
8413 /* Otherwise we're done */
8423 /** Copy environment with compaction. */
8425 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
8430 MDB_txn *txn = NULL;
8435 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
8436 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
8437 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_psize);
8438 if (my.mc_wbuf[0] == NULL)
8441 pthread_mutex_init(&my.mc_mutex, NULL);
8442 pthread_cond_init(&my.mc_cond, NULL);
8443 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_psize, MDB_WBUF*2);
8447 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
8452 my.mc_next_pgno = 2;
8458 THREAD_CREATE(thr, mdb_env_copythr, &my);
8460 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8464 mp = (MDB_page *)my.mc_wbuf[0];
8465 memset(mp, 0, 2*env->me_psize);
8467 mp->mp_flags = P_META;
8468 mm = (MDB_meta *)METADATA(mp);
8469 mdb_env_init_meta0(env, mm);
8470 mm->mm_address = env->me_metas[0]->mm_address;
8472 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
8474 mp->mp_flags = P_META;
8475 *(MDB_meta *)METADATA(mp) = *mm;
8476 mm = (MDB_meta *)METADATA(mp);
8478 /* Count the number of free pages, subtract from lastpg to find
8479 * number of active pages
8482 MDB_ID freecount = 0;
8485 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
8486 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
8487 freecount += *(MDB_ID *)data.mv_data;
8488 freecount += txn->mt_dbs[0].md_branch_pages +
8489 txn->mt_dbs[0].md_leaf_pages +
8490 txn->mt_dbs[0].md_overflow_pages;
8492 /* Set metapage 1 */
8493 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
8494 mm->mm_dbs[1] = txn->mt_dbs[1];
8495 mm->mm_dbs[1].md_root = mm->mm_last_pg;
8498 my.mc_wlen[0] = env->me_psize * 2;
8500 pthread_mutex_lock(&my.mc_mutex);
8502 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8503 pthread_mutex_unlock(&my.mc_mutex);
8504 rc = mdb_env_cwalk(&my, &txn->mt_dbs[1].md_root, 0);
8505 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
8506 rc = mdb_env_cthr_toggle(&my, 1);
8507 mdb_env_cthr_toggle(&my, -1);
8508 pthread_mutex_lock(&my.mc_mutex);
8510 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8511 pthread_mutex_unlock(&my.mc_mutex);
8516 CloseHandle(my.mc_cond);
8517 CloseHandle(my.mc_mutex);
8518 _aligned_free(my.mc_wbuf[0]);
8520 pthread_cond_destroy(&my.mc_cond);
8521 pthread_mutex_destroy(&my.mc_mutex);
8522 free(my.mc_wbuf[0]);
8527 /** Copy environment as-is. */
8529 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
8531 MDB_txn *txn = NULL;
8537 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8541 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8544 /* Do the lock/unlock of the reader mutex before starting the
8545 * write txn. Otherwise other read txns could block writers.
8547 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8552 /* We must start the actual read txn after blocking writers */
8553 mdb_txn_reset0(txn, "reset-stage1");
8555 /* Temporarily block writers until we snapshot the meta pages */
8558 rc = mdb_txn_renew0(txn);
8560 UNLOCK_MUTEX_W(env);
8565 wsize = env->me_psize * 2;
8569 DO_WRITE(rc, fd, ptr, w2, len);
8573 } else if (len > 0) {
8579 /* Non-blocking or async handles are not supported */
8585 UNLOCK_MUTEX_W(env);
8590 w2 = txn->mt_next_pgno * env->me_psize;
8593 LARGE_INTEGER fsize;
8594 GetFileSizeEx(env->me_fd, &fsize);
8595 if (w2 > fsize.QuadPart)
8596 w2 = fsize.QuadPart;
8601 fstat(env->me_fd, &st);
8602 if (w2 > (size_t)st.st_size)
8608 if (wsize > MAX_WRITE)
8612 DO_WRITE(rc, fd, ptr, w2, len);
8616 } else if (len > 0) {
8633 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
8635 if (flags & MDB_CP_COMPACT)
8636 return mdb_env_copyfd1(env, fd);
8638 return mdb_env_copyfd0(env, fd);
8642 mdb_env_copyfd(MDB_env *env, HANDLE fd)
8644 return mdb_env_copyfd2(env, fd, 0);
8648 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
8652 HANDLE newfd = INVALID_HANDLE_VALUE;
8654 if (env->me_flags & MDB_NOSUBDIR) {
8655 lpath = (char *)path;
8658 len += sizeof(DATANAME);
8659 lpath = malloc(len);
8662 sprintf(lpath, "%s" DATANAME, path);
8665 /* The destination path must exist, but the destination file must not.
8666 * We don't want the OS to cache the writes, since the source data is
8667 * already in the OS cache.
8670 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
8671 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
8673 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
8675 if (newfd == INVALID_HANDLE_VALUE) {
8681 /* Set O_DIRECT if the file system supports it */
8682 if ((rc = fcntl(newfd, F_GETFL)) != -1)
8683 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
8685 #ifdef F_NOCACHE /* __APPLE__ */
8686 rc = fcntl(newfd, F_NOCACHE, 1);
8693 rc = mdb_env_copyfd2(env, newfd, flags);
8696 if (!(env->me_flags & MDB_NOSUBDIR))
8698 if (newfd != INVALID_HANDLE_VALUE)
8699 if (close(newfd) < 0 && rc == MDB_SUCCESS)
8706 mdb_env_copy(MDB_env *env, const char *path)
8708 return mdb_env_copy2(env, path, 0);
8712 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
8714 if ((flag & CHANGEABLE) != flag)
8717 env->me_flags |= flag;
8719 env->me_flags &= ~flag;
8724 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
8729 *arg = env->me_flags;
8734 mdb_env_set_userctx(MDB_env *env, void *ctx)
8738 env->me_userctx = ctx;
8743 mdb_env_get_userctx(MDB_env *env)
8745 return env ? env->me_userctx : NULL;
8749 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
8754 env->me_assert_func = func;
8760 mdb_env_get_path(MDB_env *env, const char **arg)
8765 *arg = env->me_path;
8770 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
8779 /** Common code for #mdb_stat() and #mdb_env_stat().
8780 * @param[in] env the environment to operate in.
8781 * @param[in] db the #MDB_db record containing the stats to return.
8782 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
8783 * @return 0, this function always succeeds.
8786 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
8788 arg->ms_psize = env->me_psize;
8789 arg->ms_depth = db->md_depth;
8790 arg->ms_branch_pages = db->md_branch_pages;
8791 arg->ms_leaf_pages = db->md_leaf_pages;
8792 arg->ms_overflow_pages = db->md_overflow_pages;
8793 arg->ms_entries = db->md_entries;
8799 mdb_env_stat(MDB_env *env, MDB_stat *arg)
8803 if (env == NULL || arg == NULL)
8806 toggle = mdb_env_pick_meta(env);
8808 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
8812 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
8816 if (env == NULL || arg == NULL)
8819 toggle = mdb_env_pick_meta(env);
8820 arg->me_mapaddr = env->me_metas[toggle]->mm_address;
8821 arg->me_mapsize = env->me_mapsize;
8822 arg->me_maxreaders = env->me_maxreaders;
8824 /* me_numreaders may be zero if this process never used any readers. Use
8825 * the shared numreader count if it exists.
8827 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
8829 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
8830 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
8834 /** Set the default comparison functions for a database.
8835 * Called immediately after a database is opened to set the defaults.
8836 * The user can then override them with #mdb_set_compare() or
8837 * #mdb_set_dupsort().
8838 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
8839 * @param[in] dbi A database handle returned by #mdb_dbi_open()
8842 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
8844 uint16_t f = txn->mt_dbs[dbi].md_flags;
8846 txn->mt_dbxs[dbi].md_cmp =
8847 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
8848 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
8850 txn->mt_dbxs[dbi].md_dcmp =
8851 !(f & MDB_DUPSORT) ? 0 :
8852 ((f & MDB_INTEGERDUP)
8853 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
8854 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
8857 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
8862 int rc, dbflag, exact;
8863 unsigned int unused = 0, seq;
8866 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
8867 mdb_default_cmp(txn, FREE_DBI);
8870 if ((flags & VALID_FLAGS) != flags)
8872 if (txn->mt_flags & MDB_TXN_ERROR)
8878 if (flags & PERSISTENT_FLAGS) {
8879 uint16_t f2 = flags & PERSISTENT_FLAGS;
8880 /* make sure flag changes get committed */
8881 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
8882 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
8883 txn->mt_flags |= MDB_TXN_DIRTY;
8886 mdb_default_cmp(txn, MAIN_DBI);
8890 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
8891 mdb_default_cmp(txn, MAIN_DBI);
8894 /* Is the DB already open? */
8896 for (i=2; i<txn->mt_numdbs; i++) {
8897 if (!txn->mt_dbxs[i].md_name.mv_size) {
8898 /* Remember this free slot */
8899 if (!unused) unused = i;
8902 if (len == txn->mt_dbxs[i].md_name.mv_size &&
8903 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
8909 /* If no free slot and max hit, fail */
8910 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
8911 return MDB_DBS_FULL;
8913 /* Cannot mix named databases with some mainDB flags */
8914 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
8915 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
8917 /* Find the DB info */
8918 dbflag = DB_NEW|DB_VALID;
8921 key.mv_data = (void *)name;
8922 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
8923 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
8924 if (rc == MDB_SUCCESS) {
8925 /* make sure this is actually a DB */
8926 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
8927 if (!(node->mn_flags & F_SUBDATA))
8928 return MDB_INCOMPATIBLE;
8929 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
8930 /* Create if requested */
8932 data.mv_size = sizeof(MDB_db);
8933 data.mv_data = &dummy;
8934 memset(&dummy, 0, sizeof(dummy));
8935 dummy.md_root = P_INVALID;
8936 dummy.md_flags = flags & PERSISTENT_FLAGS;
8937 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
8941 /* OK, got info, add to table */
8942 if (rc == MDB_SUCCESS) {
8943 unsigned int slot = unused ? unused : txn->mt_numdbs;
8944 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
8945 txn->mt_dbxs[slot].md_name.mv_size = len;
8946 txn->mt_dbxs[slot].md_rel = NULL;
8947 txn->mt_dbflags[slot] = dbflag;
8948 /* txn-> and env-> are the same in read txns, use
8949 * tmp variable to avoid undefined assignment
8951 seq = ++txn->mt_env->me_dbiseqs[slot];
8952 txn->mt_dbiseqs[slot] = seq;
8954 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
8956 mdb_default_cmp(txn, slot);
8965 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
8967 if (!arg || !TXN_DBI_EXIST(txn, dbi))
8970 if (txn->mt_flags & MDB_TXN_ERROR)
8973 if (txn->mt_dbflags[dbi] & DB_STALE) {
8976 /* Stale, must read the DB's root. cursor_init does it for us. */
8977 mdb_cursor_init(&mc, txn, dbi, &mx);
8979 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
8982 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
8985 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
8987 ptr = env->me_dbxs[dbi].md_name.mv_data;
8988 /* If there was no name, this was already closed */
8990 env->me_dbxs[dbi].md_name.mv_data = NULL;
8991 env->me_dbxs[dbi].md_name.mv_size = 0;
8992 env->me_dbflags[dbi] = 0;
8993 env->me_dbiseqs[dbi]++;
8998 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9000 /* We could return the flags for the FREE_DBI too but what's the point? */
9001 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9003 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9007 /** Add all the DB's pages to the free list.
9008 * @param[in] mc Cursor on the DB to free.
9009 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9010 * @return 0 on success, non-zero on failure.
9013 mdb_drop0(MDB_cursor *mc, int subs)
9017 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9018 if (rc == MDB_SUCCESS) {
9019 MDB_txn *txn = mc->mc_txn;
9024 /* LEAF2 pages have no nodes, cannot have sub-DBs */
9025 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
9028 mdb_cursor_copy(mc, &mx);
9029 while (mc->mc_snum > 0) {
9030 MDB_page *mp = mc->mc_pg[mc->mc_top];
9031 unsigned n = NUMKEYS(mp);
9033 for (i=0; i<n; i++) {
9034 ni = NODEPTR(mp, i);
9035 if (ni->mn_flags & F_BIGDATA) {
9038 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9039 rc = mdb_page_get(txn, pg, &omp, NULL);
9042 mdb_cassert(mc, IS_OVERFLOW(omp));
9043 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9047 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9048 mdb_xcursor_init1(mc, ni);
9049 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9055 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9057 for (i=0; i<n; i++) {
9059 ni = NODEPTR(mp, i);
9062 mdb_midl_xappend(txn->mt_free_pgs, pg);
9067 mc->mc_ki[mc->mc_top] = i;
9068 rc = mdb_cursor_sibling(mc, 1);
9070 if (rc != MDB_NOTFOUND)
9072 /* no more siblings, go back to beginning
9073 * of previous level.
9077 for (i=1; i<mc->mc_snum; i++) {
9079 mc->mc_pg[i] = mx.mc_pg[i];
9084 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9087 txn->mt_flags |= MDB_TXN_ERROR;
9088 } else if (rc == MDB_NOTFOUND) {
9094 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9096 MDB_cursor *mc, *m2;
9099 if ((unsigned)del > 1 || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9102 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9105 if (dbi > MAIN_DBI && TXN_DBI_CHANGED(txn, dbi))
9108 rc = mdb_cursor_open(txn, dbi, &mc);
9112 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9113 /* Invalidate the dropped DB's cursors */
9114 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9115 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9119 /* Can't delete the main DB */
9120 if (del && dbi > MAIN_DBI) {
9121 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, 0);
9123 txn->mt_dbflags[dbi] = DB_STALE;
9124 mdb_dbi_close(txn->mt_env, dbi);
9126 txn->mt_flags |= MDB_TXN_ERROR;
9129 /* reset the DB record, mark it dirty */
9130 txn->mt_dbflags[dbi] |= DB_DIRTY;
9131 txn->mt_dbs[dbi].md_depth = 0;
9132 txn->mt_dbs[dbi].md_branch_pages = 0;
9133 txn->mt_dbs[dbi].md_leaf_pages = 0;
9134 txn->mt_dbs[dbi].md_overflow_pages = 0;
9135 txn->mt_dbs[dbi].md_entries = 0;
9136 txn->mt_dbs[dbi].md_root = P_INVALID;
9138 txn->mt_flags |= MDB_TXN_DIRTY;
9141 mdb_cursor_close(mc);
9145 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9147 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9150 txn->mt_dbxs[dbi].md_cmp = cmp;
9154 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9156 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9159 txn->mt_dbxs[dbi].md_dcmp = cmp;
9163 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9165 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9168 txn->mt_dbxs[dbi].md_rel = rel;
9172 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9174 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9177 txn->mt_dbxs[dbi].md_relctx = ctx;
9182 mdb_env_get_maxkeysize(MDB_env *env)
9184 return ENV_MAXKEY(env);
9188 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9190 unsigned int i, rdrs;
9193 int rc = 0, first = 1;
9197 if (!env->me_txns) {
9198 return func("(no reader locks)\n", ctx);
9200 rdrs = env->me_txns->mti_numreaders;
9201 mr = env->me_txns->mti_readers;
9202 for (i=0; i<rdrs; i++) {
9204 txnid_t txnid = mr[i].mr_txnid;
9205 sprintf(buf, txnid == (txnid_t)-1 ?
9206 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9207 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9210 rc = func(" pid thread txnid\n", ctx);
9214 rc = func(buf, ctx);
9220 rc = func("(no active readers)\n", ctx);
9225 /** Insert pid into list if not already present.
9226 * return -1 if already present.
9229 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9231 /* binary search of pid in list */
9233 unsigned cursor = 1;
9235 unsigned n = ids[0];
9238 unsigned pivot = n >> 1;
9239 cursor = base + pivot + 1;
9240 val = pid - ids[cursor];
9245 } else if ( val > 0 ) {
9250 /* found, so it's a duplicate */
9259 for (n = ids[0]; n > cursor; n--)
9266 mdb_reader_check(MDB_env *env, int *dead)
9268 unsigned int i, j, rdrs;
9270 MDB_PID_T *pids, pid;
9279 rdrs = env->me_txns->mti_numreaders;
9280 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
9284 mr = env->me_txns->mti_readers;
9285 for (i=0; i<rdrs; i++) {
9286 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
9288 if (mdb_pid_insert(pids, pid) == 0) {
9289 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9291 /* Recheck, a new process may have reused pid */
9292 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9293 for (j=i; j<rdrs; j++)
9294 if (mr[j].mr_pid == pid) {
9295 DPRINTF(("clear stale reader pid %u txn %"Z"d",
9296 (unsigned) pid, mr[j].mr_txnid));
9301 UNLOCK_MUTEX_R(env);