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: Environment mapsize was changed by another process",
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)
1264 return ("Successful return: 0");
1266 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1267 i = err - MDB_KEYEXIST;
1268 return mdb_errstr[i];
1271 return strerror(err);
1274 /** assert(3) variant in cursor context */
1275 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1276 /** assert(3) variant in transaction context */
1277 #define mdb_tassert(mc, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1278 /** assert(3) variant in environment context */
1279 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1282 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1283 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1286 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1287 const char *func, const char *file, int line)
1290 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1291 file, line, expr_txt, func);
1292 if (env->me_assert_func)
1293 env->me_assert_func(env, buf);
1294 fprintf(stderr, "%s\n", buf);
1298 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1302 /** Return the page number of \b mp which may be sub-page, for debug output */
1304 mdb_dbg_pgno(MDB_page *mp)
1307 COPY_PGNO(ret, mp->mp_pgno);
1311 /** Display a key in hexadecimal and return the address of the result.
1312 * @param[in] key the key to display
1313 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1314 * @return The key in hexadecimal form.
1317 mdb_dkey(MDB_val *key, char *buf)
1320 unsigned char *c = key->mv_data;
1326 if (key->mv_size > DKBUF_MAXKEYSIZE)
1327 return "MDB_MAXKEYSIZE";
1328 /* may want to make this a dynamic check: if the key is mostly
1329 * printable characters, print it as-is instead of converting to hex.
1333 for (i=0; i<key->mv_size; i++)
1334 ptr += sprintf(ptr, "%02x", *c++);
1336 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1342 mdb_leafnode_type(MDB_node *n)
1344 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1345 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1346 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1349 /** Display all the keys in the page. */
1351 mdb_page_list(MDB_page *mp)
1353 pgno_t pgno = mdb_dbg_pgno(mp);
1354 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1356 unsigned int i, nkeys, nsize, total = 0;
1360 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1361 case P_BRANCH: type = "Branch page"; break;
1362 case P_LEAF: type = "Leaf page"; break;
1363 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1364 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1365 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1367 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1368 pgno, mp->mp_pages, state);
1371 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1372 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1375 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1379 nkeys = NUMKEYS(mp);
1380 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1382 for (i=0; i<nkeys; i++) {
1383 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1384 key.mv_size = nsize = mp->mp_pad;
1385 key.mv_data = LEAF2KEY(mp, i, nsize);
1387 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1390 node = NODEPTR(mp, i);
1391 key.mv_size = node->mn_ksize;
1392 key.mv_data = node->mn_data;
1393 nsize = NODESIZE + key.mv_size;
1394 if (IS_BRANCH(mp)) {
1395 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1399 if (F_ISSET(node->mn_flags, F_BIGDATA))
1400 nsize += sizeof(pgno_t);
1402 nsize += NODEDSZ(node);
1404 nsize += sizeof(indx_t);
1405 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1406 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1408 total = EVEN(total);
1410 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1411 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1415 mdb_cursor_chk(MDB_cursor *mc)
1421 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1422 for (i=0; i<mc->mc_top; i++) {
1424 node = NODEPTR(mp, mc->mc_ki[i]);
1425 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1428 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1434 /** Count all the pages in each DB and in the freelist
1435 * and make sure it matches the actual number of pages
1437 * All named DBs must be open for a correct count.
1439 static void mdb_audit(MDB_txn *txn)
1443 MDB_ID freecount, count;
1448 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1449 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1450 freecount += *(MDB_ID *)data.mv_data;
1451 mdb_tassert(txn, rc == MDB_NOTFOUND);
1454 for (i = 0; i<txn->mt_numdbs; i++) {
1456 if (!(txn->mt_dbflags[i] & DB_VALID))
1458 mdb_cursor_init(&mc, txn, i, &mx);
1459 if (txn->mt_dbs[i].md_root == P_INVALID)
1461 count += txn->mt_dbs[i].md_branch_pages +
1462 txn->mt_dbs[i].md_leaf_pages +
1463 txn->mt_dbs[i].md_overflow_pages;
1464 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1465 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1466 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1469 mp = mc.mc_pg[mc.mc_top];
1470 for (j=0; j<NUMKEYS(mp); j++) {
1471 MDB_node *leaf = NODEPTR(mp, j);
1472 if (leaf->mn_flags & F_SUBDATA) {
1474 memcpy(&db, NODEDATA(leaf), sizeof(db));
1475 count += db.md_branch_pages + db.md_leaf_pages +
1476 db.md_overflow_pages;
1480 mdb_tassert(txn, rc == MDB_NOTFOUND);
1483 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1484 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1485 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1491 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1493 return txn->mt_dbxs[dbi].md_cmp(a, b);
1497 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1499 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1502 /** Allocate memory for a page.
1503 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1506 mdb_page_malloc(MDB_txn *txn, unsigned num)
1508 MDB_env *env = txn->mt_env;
1509 MDB_page *ret = env->me_dpages;
1510 size_t psize = env->me_psize, sz = psize, off;
1511 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1512 * For a single page alloc, we init everything after the page header.
1513 * For multi-page, we init the final page; if the caller needed that
1514 * many pages they will be filling in at least up to the last page.
1518 VGMEMP_ALLOC(env, ret, sz);
1519 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1520 env->me_dpages = ret->mp_next;
1523 psize -= off = PAGEHDRSZ;
1528 if ((ret = malloc(sz)) != NULL) {
1529 VGMEMP_ALLOC(env, ret, sz);
1530 if (!(env->me_flags & MDB_NOMEMINIT)) {
1531 memset((char *)ret + off, 0, psize);
1535 txn->mt_flags |= MDB_TXN_ERROR;
1539 /** Free a single page.
1540 * Saves single pages to a list, for future reuse.
1541 * (This is not used for multi-page overflow pages.)
1544 mdb_page_free(MDB_env *env, MDB_page *mp)
1546 mp->mp_next = env->me_dpages;
1547 VGMEMP_FREE(env, mp);
1548 env->me_dpages = mp;
1551 /** Free a dirty page */
1553 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1555 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1556 mdb_page_free(env, dp);
1558 /* large pages just get freed directly */
1559 VGMEMP_FREE(env, dp);
1564 /** Return all dirty pages to dpage list */
1566 mdb_dlist_free(MDB_txn *txn)
1568 MDB_env *env = txn->mt_env;
1569 MDB_ID2L dl = txn->mt_u.dirty_list;
1570 unsigned i, n = dl[0].mid;
1572 for (i = 1; i <= n; i++) {
1573 mdb_dpage_free(env, dl[i].mptr);
1578 /** Loosen or free a single page.
1579 * Saves single pages to a list for future reuse
1580 * in this same txn. It has been pulled from the freeDB
1581 * and already resides on the dirty list, but has been
1582 * deleted. Use these pages first before pulling again
1585 * If the page wasn't dirtied in this txn, just add it
1586 * to this txn's free list.
1589 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1592 pgno_t pgno = mp->mp_pgno;
1594 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1595 if (mc->mc_txn->mt_parent) {
1596 MDB_ID2 *dl = mc->mc_txn->mt_u.dirty_list;
1597 /* If txn has a parent, make sure the page is in our
1601 unsigned x = mdb_mid2l_search(dl, pgno);
1602 if (x <= dl[0].mid && dl[x].mid == pgno) {
1603 if (mp != dl[x].mptr) { /* bad cursor? */
1604 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1605 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
1606 return MDB_CORRUPTED;
1613 /* no parent txn, so it's just ours */
1618 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1620 NEXT_LOOSE_PAGE(mp) = mc->mc_txn->mt_loose_pgs;
1621 mc->mc_txn->mt_loose_pgs = mp;
1622 mp->mp_flags |= P_LOOSE;
1624 int rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, pgno);
1632 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1633 * @param[in] mc A cursor handle for the current operation.
1634 * @param[in] pflags Flags of the pages to update:
1635 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1636 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1637 * @return 0 on success, non-zero on failure.
1640 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1642 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1643 MDB_txn *txn = mc->mc_txn;
1649 int rc = MDB_SUCCESS, level;
1651 /* Mark pages seen by cursors */
1652 if (mc->mc_flags & C_UNTRACK)
1653 mc = NULL; /* will find mc in mt_cursors */
1654 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1655 for (; mc; mc=mc->mc_next) {
1656 if (!(mc->mc_flags & C_INITIALIZED))
1658 for (m3 = mc;; m3 = &mx->mx_cursor) {
1660 for (j=0; j<m3->mc_snum; j++) {
1662 if ((mp->mp_flags & Mask) == pflags)
1663 mp->mp_flags ^= P_KEEP;
1665 mx = m3->mc_xcursor;
1666 /* Proceed to mx if it is at a sub-database */
1667 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1669 if (! (mp && (mp->mp_flags & P_LEAF)))
1671 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1672 if (!(leaf->mn_flags & F_SUBDATA))
1681 /* Mark dirty root pages */
1682 for (i=0; i<txn->mt_numdbs; i++) {
1683 if (txn->mt_dbflags[i] & DB_DIRTY) {
1684 pgno_t pgno = txn->mt_dbs[i].md_root;
1685 if (pgno == P_INVALID)
1687 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1689 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1690 dp->mp_flags ^= P_KEEP;
1698 static int mdb_page_flush(MDB_txn *txn, int keep);
1700 /** Spill pages from the dirty list back to disk.
1701 * This is intended to prevent running into #MDB_TXN_FULL situations,
1702 * but note that they may still occur in a few cases:
1703 * 1) our estimate of the txn size could be too small. Currently this
1704 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1705 * 2) child txns may run out of space if their parents dirtied a
1706 * lot of pages and never spilled them. TODO: we probably should do
1707 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1708 * the parent's dirty_room is below a given threshold.
1710 * Otherwise, if not using nested txns, it is expected that apps will
1711 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1712 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1713 * If the txn never references them again, they can be left alone.
1714 * If the txn only reads them, they can be used without any fuss.
1715 * If the txn writes them again, they can be dirtied immediately without
1716 * going thru all of the work of #mdb_page_touch(). Such references are
1717 * handled by #mdb_page_unspill().
1719 * Also note, we never spill DB root pages, nor pages of active cursors,
1720 * because we'll need these back again soon anyway. And in nested txns,
1721 * we can't spill a page in a child txn if it was already spilled in a
1722 * parent txn. That would alter the parent txns' data even though
1723 * the child hasn't committed yet, and we'd have no way to undo it if
1724 * the child aborted.
1726 * @param[in] m0 cursor A cursor handle identifying the transaction and
1727 * database for which we are checking space.
1728 * @param[in] key For a put operation, the key being stored.
1729 * @param[in] data For a put operation, the data being stored.
1730 * @return 0 on success, non-zero on failure.
1733 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1735 MDB_txn *txn = m0->mc_txn;
1737 MDB_ID2L dl = txn->mt_u.dirty_list;
1738 unsigned int i, j, need;
1741 if (m0->mc_flags & C_SUB)
1744 /* Estimate how much space this op will take */
1745 i = m0->mc_db->md_depth;
1746 /* Named DBs also dirty the main DB */
1747 if (m0->mc_dbi > MAIN_DBI)
1748 i += txn->mt_dbs[MAIN_DBI].md_depth;
1749 /* For puts, roughly factor in the key+data size */
1751 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1752 i += i; /* double it for good measure */
1755 if (txn->mt_dirty_room > i)
1758 if (!txn->mt_spill_pgs) {
1759 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1760 if (!txn->mt_spill_pgs)
1763 /* purge deleted slots */
1764 MDB_IDL sl = txn->mt_spill_pgs;
1765 unsigned int num = sl[0];
1767 for (i=1; i<=num; i++) {
1774 /* Preserve pages which may soon be dirtied again */
1775 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1778 /* Less aggressive spill - we originally spilled the entire dirty list,
1779 * with a few exceptions for cursor pages and DB root pages. But this
1780 * turns out to be a lot of wasted effort because in a large txn many
1781 * of those pages will need to be used again. So now we spill only 1/8th
1782 * of the dirty pages. Testing revealed this to be a good tradeoff,
1783 * better than 1/2, 1/4, or 1/10.
1785 if (need < MDB_IDL_UM_MAX / 8)
1786 need = MDB_IDL_UM_MAX / 8;
1788 /* Save the page IDs of all the pages we're flushing */
1789 /* flush from the tail forward, this saves a lot of shifting later on. */
1790 for (i=dl[0].mid; i && need; i--) {
1791 MDB_ID pn = dl[i].mid << 1;
1793 if (dp->mp_flags & (P_LOOSE|P_KEEP))
1795 /* Can't spill twice, make sure it's not already in a parent's
1798 if (txn->mt_parent) {
1800 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1801 if (tx2->mt_spill_pgs) {
1802 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1803 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1804 dp->mp_flags |= P_KEEP;
1812 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1816 mdb_midl_sort(txn->mt_spill_pgs);
1818 /* Flush the spilled part of dirty list */
1819 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1822 /* Reset any dirty pages we kept that page_flush didn't see */
1823 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1826 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1830 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1832 mdb_find_oldest(MDB_txn *txn)
1835 txnid_t mr, oldest = txn->mt_txnid - 1;
1836 if (txn->mt_env->me_txns) {
1837 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1838 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1849 /** Add a page to the txn's dirty list */
1851 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1854 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
1856 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1857 insert = mdb_mid2l_append;
1859 insert = mdb_mid2l_insert;
1861 mid.mid = mp->mp_pgno;
1863 rc = insert(txn->mt_u.dirty_list, &mid);
1864 mdb_tassert(txn, rc == 0);
1865 txn->mt_dirty_room--;
1868 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1869 * me_pghead and mt_next_pgno.
1871 * If there are free pages available from older transactions, they
1872 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1873 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1874 * and move me_pglast to say which records were consumed. Only this
1875 * function can create me_pghead and move me_pglast/mt_next_pgno.
1876 * @param[in] mc cursor A cursor handle identifying the transaction and
1877 * database for which we are allocating.
1878 * @param[in] num the number of pages to allocate.
1879 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1880 * will always be satisfied by a single contiguous chunk of memory.
1881 * @return 0 on success, non-zero on failure.
1884 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1886 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1887 /* Get at most <Max_retries> more freeDB records once me_pghead
1888 * has enough pages. If not enough, use new pages from the map.
1889 * If <Paranoid> and mc is updating the freeDB, only get new
1890 * records if me_pghead is empty. Then the freelist cannot play
1891 * catch-up with itself by growing while trying to save it.
1893 enum { Paranoid = 1, Max_retries = 500 };
1895 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1897 int rc, retry = num * 20;
1898 MDB_txn *txn = mc->mc_txn;
1899 MDB_env *env = txn->mt_env;
1900 pgno_t pgno, *mop = env->me_pghead;
1901 unsigned i, j, k, mop_len = mop ? mop[0] : 0, n2 = num-1;
1903 txnid_t oldest = 0, last;
1907 /* If there are any loose pages, just use them */
1908 if (num == 1 && txn->mt_loose_pgs) {
1909 np = txn->mt_loose_pgs;
1910 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
1911 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
1919 /* If our dirty list is already full, we can't do anything */
1920 if (txn->mt_dirty_room == 0) {
1925 for (op = MDB_FIRST;; op = MDB_NEXT) {
1928 pgno_t *idl, old_id, new_id;
1930 /* Seek a big enough contiguous page range. Prefer
1931 * pages at the tail, just truncating the list.
1937 if (mop[i-n2] == pgno+n2)
1944 if (op == MDB_FIRST) { /* 1st iteration */
1945 /* Prepare to fetch more and coalesce */
1946 oldest = mdb_find_oldest(txn);
1947 last = env->me_pglast;
1948 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1951 key.mv_data = &last; /* will look up last+1 */
1952 key.mv_size = sizeof(last);
1954 if (Paranoid && mc->mc_dbi == FREE_DBI)
1957 if (Paranoid && retry < 0 && mop_len)
1961 /* Do not fetch more if the record will be too recent */
1964 rc = mdb_cursor_get(&m2, &key, NULL, op);
1966 if (rc == MDB_NOTFOUND)
1970 last = *(txnid_t*)key.mv_data;
1973 np = m2.mc_pg[m2.mc_top];
1974 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1975 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1978 idl = (MDB_ID *) data.mv_data;
1981 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
1986 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1988 mop = env->me_pghead;
1990 env->me_pglast = last;
1992 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
1993 last, txn->mt_dbs[FREE_DBI].md_root, i));
1995 DPRINTF(("IDL %"Z"u", idl[k]));
1997 /* Merge in descending sorted order */
2000 mop[0] = (pgno_t)-1;
2004 for (; old_id < new_id; old_id = mop[--j])
2011 /* Use new pages from the map when nothing suitable in the freeDB */
2013 pgno = txn->mt_next_pgno;
2014 if (pgno + num >= env->me_maxpg) {
2015 DPUTS("DB size maxed out");
2021 if (env->me_flags & MDB_WRITEMAP) {
2022 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2024 if (!(np = mdb_page_malloc(txn, num))) {
2030 mop[0] = mop_len -= num;
2031 /* Move any stragglers down */
2032 for (j = i-num; j < mop_len; )
2033 mop[++j] = mop[++i];
2035 txn->mt_next_pgno = pgno + num;
2038 mdb_page_dirty(txn, np);
2044 txn->mt_flags |= MDB_TXN_ERROR;
2048 /** Copy the used portions of a non-overflow page.
2049 * @param[in] dst page to copy into
2050 * @param[in] src page to copy from
2051 * @param[in] psize size of a page
2054 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2056 enum { Align = sizeof(pgno_t) };
2057 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2059 /* If page isn't full, just copy the used portion. Adjust
2060 * alignment so memcpy may copy words instead of bytes.
2062 if ((unused &= -Align) && !IS_LEAF2(src)) {
2063 upper = (upper + PAGEBASE) & -Align;
2064 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2065 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2068 memcpy(dst, src, psize - unused);
2072 /** Pull a page off the txn's spill list, if present.
2073 * If a page being referenced was spilled to disk in this txn, bring
2074 * it back and make it dirty/writable again.
2075 * @param[in] txn the transaction handle.
2076 * @param[in] mp the page being referenced. It must not be dirty.
2077 * @param[out] ret the writable page, if any. ret is unchanged if
2078 * mp wasn't spilled.
2081 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2083 MDB_env *env = txn->mt_env;
2086 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2088 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2089 if (!tx2->mt_spill_pgs)
2091 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2092 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2095 if (txn->mt_dirty_room == 0)
2096 return MDB_TXN_FULL;
2097 if (IS_OVERFLOW(mp))
2101 if (env->me_flags & MDB_WRITEMAP) {
2104 np = mdb_page_malloc(txn, num);
2108 memcpy(np, mp, num * env->me_psize);
2110 mdb_page_copy(np, mp, env->me_psize);
2113 /* If in current txn, this page is no longer spilled.
2114 * If it happens to be the last page, truncate the spill list.
2115 * Otherwise mark it as deleted by setting the LSB.
2117 if (x == txn->mt_spill_pgs[0])
2118 txn->mt_spill_pgs[0]--;
2120 txn->mt_spill_pgs[x] |= 1;
2121 } /* otherwise, if belonging to a parent txn, the
2122 * page remains spilled until child commits
2125 mdb_page_dirty(txn, np);
2126 np->mp_flags |= P_DIRTY;
2134 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2135 * @param[in] mc cursor pointing to the page to be touched
2136 * @return 0 on success, non-zero on failure.
2139 mdb_page_touch(MDB_cursor *mc)
2141 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2142 MDB_txn *txn = mc->mc_txn;
2143 MDB_cursor *m2, *m3;
2147 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2148 if (txn->mt_flags & MDB_TXN_SPILLS) {
2150 rc = mdb_page_unspill(txn, mp, &np);
2156 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2157 (rc = mdb_page_alloc(mc, 1, &np)))
2160 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2161 mp->mp_pgno, pgno));
2162 mdb_cassert(mc, mp->mp_pgno != pgno);
2163 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2164 /* Update the parent page, if any, to point to the new page */
2166 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2167 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2168 SETPGNO(node, pgno);
2170 mc->mc_db->md_root = pgno;
2172 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2173 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2175 /* If txn has a parent, make sure the page is in our
2179 unsigned x = mdb_mid2l_search(dl, pgno);
2180 if (x <= dl[0].mid && dl[x].mid == pgno) {
2181 if (mp != dl[x].mptr) { /* bad cursor? */
2182 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2183 txn->mt_flags |= MDB_TXN_ERROR;
2184 return MDB_CORRUPTED;
2189 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2191 np = mdb_page_malloc(txn, 1);
2196 rc = mdb_mid2l_insert(dl, &mid);
2197 mdb_cassert(mc, rc == 0);
2202 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2204 np->mp_flags |= P_DIRTY;
2207 /* Adjust cursors pointing to mp */
2208 mc->mc_pg[mc->mc_top] = np;
2209 m2 = txn->mt_cursors[mc->mc_dbi];
2210 if (mc->mc_flags & C_SUB) {
2211 for (; m2; m2=m2->mc_next) {
2212 m3 = &m2->mc_xcursor->mx_cursor;
2213 if (m3->mc_snum < mc->mc_snum) continue;
2214 if (m3->mc_pg[mc->mc_top] == mp)
2215 m3->mc_pg[mc->mc_top] = np;
2218 for (; m2; m2=m2->mc_next) {
2219 if (m2->mc_snum < mc->mc_snum) continue;
2220 if (m2->mc_pg[mc->mc_top] == mp) {
2221 m2->mc_pg[mc->mc_top] = np;
2222 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2224 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2226 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2227 if (!(leaf->mn_flags & F_SUBDATA))
2228 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2236 txn->mt_flags |= MDB_TXN_ERROR;
2241 mdb_env_sync(MDB_env *env, int force)
2244 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2245 if (env->me_flags & MDB_WRITEMAP) {
2246 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2247 ? MS_ASYNC : MS_SYNC;
2248 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2251 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2255 if (MDB_FDATASYNC(env->me_fd))
2262 /** Back up parent txn's cursors, then grab the originals for tracking */
2264 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2266 MDB_cursor *mc, *bk;
2271 for (i = src->mt_numdbs; --i >= 0; ) {
2272 if ((mc = src->mt_cursors[i]) != NULL) {
2273 size = sizeof(MDB_cursor);
2275 size += sizeof(MDB_xcursor);
2276 for (; mc; mc = bk->mc_next) {
2282 mc->mc_db = &dst->mt_dbs[i];
2283 /* Kill pointers into src - and dst to reduce abuse: The
2284 * user may not use mc until dst ends. Otherwise we'd...
2286 mc->mc_txn = NULL; /* ...set this to dst */
2287 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2288 if ((mx = mc->mc_xcursor) != NULL) {
2289 *(MDB_xcursor *)(bk+1) = *mx;
2290 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2292 mc->mc_next = dst->mt_cursors[i];
2293 dst->mt_cursors[i] = mc;
2300 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2301 * @param[in] txn the transaction handle.
2302 * @param[in] merge true to keep changes to parent cursors, false to revert.
2303 * @return 0 on success, non-zero on failure.
2306 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2308 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2312 for (i = txn->mt_numdbs; --i >= 0; ) {
2313 for (mc = cursors[i]; mc; mc = next) {
2315 if ((bk = mc->mc_backup) != NULL) {
2317 /* Commit changes to parent txn */
2318 mc->mc_next = bk->mc_next;
2319 mc->mc_backup = bk->mc_backup;
2320 mc->mc_txn = bk->mc_txn;
2321 mc->mc_db = bk->mc_db;
2322 mc->mc_dbflag = bk->mc_dbflag;
2323 if ((mx = mc->mc_xcursor) != NULL)
2324 mx->mx_cursor.mc_txn = bk->mc_txn;
2326 /* Abort nested txn */
2328 if ((mx = mc->mc_xcursor) != NULL)
2329 *mx = *(MDB_xcursor *)(bk+1);
2333 /* Only malloced cursors are permanently tracked. */
2341 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2344 mdb_txn_reset0(MDB_txn *txn, const char *act);
2346 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2352 Pidset = F_SETLK, Pidcheck = F_GETLK
2356 /** Set or check a pid lock. Set returns 0 on success.
2357 * Check returns 0 if the process is certainly dead, nonzero if it may
2358 * be alive (the lock exists or an error happened so we do not know).
2360 * On Windows Pidset is a no-op, we merely check for the existence
2361 * of the process with the given pid. On POSIX we use a single byte
2362 * lock on the lockfile, set at an offset equal to the pid.
2365 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2367 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2370 if (op == Pidcheck) {
2371 h = OpenProcess(env->me_pidquery, FALSE, pid);
2372 /* No documented "no such process" code, but other program use this: */
2374 return ErrCode() != ERROR_INVALID_PARAMETER;
2375 /* A process exists until all handles to it close. Has it exited? */
2376 ret = WaitForSingleObject(h, 0) != 0;
2383 struct flock lock_info;
2384 memset(&lock_info, 0, sizeof(lock_info));
2385 lock_info.l_type = F_WRLCK;
2386 lock_info.l_whence = SEEK_SET;
2387 lock_info.l_start = pid;
2388 lock_info.l_len = 1;
2389 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2390 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2392 } else if ((rc = ErrCode()) == EINTR) {
2400 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2401 * @param[in] txn the transaction handle to initialize
2402 * @return 0 on success, non-zero on failure.
2405 mdb_txn_renew0(MDB_txn *txn)
2407 MDB_env *env = txn->mt_env;
2408 MDB_txninfo *ti = env->me_txns;
2412 int rc, new_notls = 0;
2415 txn->mt_numdbs = env->me_numdbs;
2416 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2418 if (txn->mt_flags & MDB_TXN_RDONLY) {
2420 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2421 txn->mt_txnid = meta->mm_txnid;
2422 txn->mt_u.reader = NULL;
2424 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2425 pthread_getspecific(env->me_txkey);
2427 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2428 return MDB_BAD_RSLOT;
2430 MDB_PID_T pid = env->me_pid;
2431 MDB_THR_T tid = pthread_self();
2433 if (!env->me_live_reader) {
2434 rc = mdb_reader_pid(env, Pidset, pid);
2437 env->me_live_reader = 1;
2441 nr = ti->mti_numreaders;
2442 for (i=0; i<nr; i++)
2443 if (ti->mti_readers[i].mr_pid == 0)
2445 if (i == env->me_maxreaders) {
2446 UNLOCK_MUTEX_R(env);
2447 return MDB_READERS_FULL;
2449 ti->mti_readers[i].mr_pid = pid;
2450 ti->mti_readers[i].mr_tid = tid;
2452 ti->mti_numreaders = ++nr;
2453 /* Save numreaders for un-mutexed mdb_env_close() */
2454 env->me_numreaders = nr;
2455 UNLOCK_MUTEX_R(env);
2457 r = &ti->mti_readers[i];
2458 new_notls = (env->me_flags & MDB_NOTLS);
2459 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2464 txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
2465 txn->mt_u.reader = r;
2466 meta = env->me_metas[txn->mt_txnid & 1];
2472 txn->mt_txnid = ti->mti_txnid;
2473 meta = env->me_metas[txn->mt_txnid & 1];
2475 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2476 txn->mt_txnid = meta->mm_txnid;
2480 if (txn->mt_txnid == mdb_debug_start)
2483 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2484 txn->mt_u.dirty_list = env->me_dirty_list;
2485 txn->mt_u.dirty_list[0].mid = 0;
2486 txn->mt_free_pgs = env->me_free_pgs;
2487 txn->mt_free_pgs[0] = 0;
2488 txn->mt_spill_pgs = NULL;
2490 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2493 /* Copy the DB info and flags */
2494 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2496 /* Moved to here to avoid a data race in read TXNs */
2497 txn->mt_next_pgno = meta->mm_last_pg+1;
2499 for (i=2; i<txn->mt_numdbs; i++) {
2500 x = env->me_dbflags[i];
2501 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2502 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2504 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2506 /* If we didn't ask for a resize, but the size changed, fail */
2507 if (!(env->me_flags & MDB_RESIZING)
2508 && env->me_mapsize != meta->mm_mapsize) {
2509 mdb_txn_reset0(txn, "renew0-mapfail");
2511 txn->mt_u.reader->mr_pid = 0;
2512 txn->mt_u.reader = NULL;
2514 return MDB_MAP_RESIZED;
2521 mdb_txn_renew(MDB_txn *txn)
2525 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2528 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2529 DPUTS("environment had fatal error, must shutdown!");
2533 rc = mdb_txn_renew0(txn);
2534 if (rc == MDB_SUCCESS) {
2535 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2536 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2537 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2543 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2547 int rc, size, tsize = sizeof(MDB_txn);
2549 if (env->me_flags & MDB_FATAL_ERROR) {
2550 DPUTS("environment had fatal error, must shutdown!");
2553 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2556 /* Nested transactions: Max 1 child, write txns only, no writemap */
2557 if (parent->mt_child ||
2558 (flags & MDB_RDONLY) ||
2559 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2560 (env->me_flags & MDB_WRITEMAP))
2562 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2564 tsize = sizeof(MDB_ntxn);
2566 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2567 if (!(flags & MDB_RDONLY)) {
2568 size += env->me_maxdbs * sizeof(MDB_cursor *);
2569 /* child txns use parent's dbiseqs */
2571 size += env->me_maxdbs * sizeof(unsigned int);
2574 if ((txn = calloc(1, size)) == NULL) {
2575 DPRINTF(("calloc: %s", strerror(ErrCode())));
2578 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2579 if (flags & MDB_RDONLY) {
2580 txn->mt_flags |= MDB_TXN_RDONLY;
2581 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2582 txn->mt_dbiseqs = env->me_dbiseqs;
2584 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2586 txn->mt_dbiseqs = parent->mt_dbiseqs;
2587 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2589 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
2590 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
2597 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2598 if (!txn->mt_u.dirty_list ||
2599 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2601 free(txn->mt_u.dirty_list);
2605 txn->mt_txnid = parent->mt_txnid;
2606 txn->mt_dirty_room = parent->mt_dirty_room;
2607 txn->mt_u.dirty_list[0].mid = 0;
2608 txn->mt_spill_pgs = NULL;
2609 txn->mt_next_pgno = parent->mt_next_pgno;
2610 parent->mt_child = txn;
2611 txn->mt_parent = parent;
2612 txn->mt_numdbs = parent->mt_numdbs;
2613 txn->mt_flags = parent->mt_flags;
2614 txn->mt_dbxs = parent->mt_dbxs;
2615 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2616 /* Copy parent's mt_dbflags, but clear DB_NEW */
2617 for (i=0; i<txn->mt_numdbs; i++)
2618 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2620 ntxn = (MDB_ntxn *)txn;
2621 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2622 if (env->me_pghead) {
2623 size = MDB_IDL_SIZEOF(env->me_pghead);
2624 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2626 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2631 rc = mdb_cursor_shadow(parent, txn);
2633 mdb_txn_reset0(txn, "beginchild-fail");
2635 rc = mdb_txn_renew0(txn);
2641 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2642 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2643 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2650 mdb_txn_env(MDB_txn *txn)
2652 if(!txn) return NULL;
2656 /** Export or close DBI handles opened in this txn. */
2658 mdb_dbis_update(MDB_txn *txn, int keep)
2661 MDB_dbi n = txn->mt_numdbs;
2662 MDB_env *env = txn->mt_env;
2663 unsigned char *tdbflags = txn->mt_dbflags;
2665 for (i = n; --i >= 2;) {
2666 if (tdbflags[i] & DB_NEW) {
2668 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2670 char *ptr = env->me_dbxs[i].md_name.mv_data;
2672 env->me_dbxs[i].md_name.mv_data = NULL;
2673 env->me_dbxs[i].md_name.mv_size = 0;
2674 env->me_dbflags[i] = 0;
2675 env->me_dbiseqs[i]++;
2681 if (keep && env->me_numdbs < n)
2685 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2686 * May be called twice for readonly txns: First reset it, then abort.
2687 * @param[in] txn the transaction handle to reset
2688 * @param[in] act why the transaction is being reset
2691 mdb_txn_reset0(MDB_txn *txn, const char *act)
2693 MDB_env *env = txn->mt_env;
2695 /* Close any DBI handles opened in this txn */
2696 mdb_dbis_update(txn, 0);
2698 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2699 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2700 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2702 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2703 if (txn->mt_u.reader) {
2704 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2705 if (!(env->me_flags & MDB_NOTLS))
2706 txn->mt_u.reader = NULL; /* txn does not own reader */
2708 txn->mt_numdbs = 0; /* close nothing if called again */
2709 txn->mt_dbxs = NULL; /* mark txn as reset */
2711 mdb_cursors_close(txn, 0);
2713 if (!(env->me_flags & MDB_WRITEMAP)) {
2714 mdb_dlist_free(txn);
2716 mdb_midl_free(env->me_pghead);
2718 if (txn->mt_parent) {
2719 txn->mt_parent->mt_child = NULL;
2720 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2721 mdb_midl_free(txn->mt_free_pgs);
2722 mdb_midl_free(txn->mt_spill_pgs);
2723 free(txn->mt_u.dirty_list);
2727 if (mdb_midl_shrink(&txn->mt_free_pgs))
2728 env->me_free_pgs = txn->mt_free_pgs;
2729 env->me_pghead = NULL;
2733 /* The writer mutex was locked in mdb_txn_begin. */
2735 UNLOCK_MUTEX_W(env);
2740 mdb_txn_reset(MDB_txn *txn)
2745 /* This call is only valid for read-only txns */
2746 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2749 mdb_txn_reset0(txn, "reset");
2753 mdb_txn_abort(MDB_txn *txn)
2759 mdb_txn_abort(txn->mt_child);
2761 mdb_txn_reset0(txn, "abort");
2762 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2763 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2764 txn->mt_u.reader->mr_pid = 0;
2769 /** Save the freelist as of this transaction to the freeDB.
2770 * This changes the freelist. Keep trying until it stabilizes.
2773 mdb_freelist_save(MDB_txn *txn)
2775 /* env->me_pghead[] can grow and shrink during this call.
2776 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2777 * Page numbers cannot disappear from txn->mt_free_pgs[].
2780 MDB_env *env = txn->mt_env;
2781 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2782 txnid_t pglast = 0, head_id = 0;
2783 pgno_t freecnt = 0, *free_pgs, *mop;
2784 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2786 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2788 if (env->me_pghead) {
2789 /* Make sure first page of freeDB is touched and on freelist */
2790 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2791 if (rc && rc != MDB_NOTFOUND)
2795 /* Dispose of loose pages. Usually they will have all
2796 * been used up by the time we get here.
2798 if (txn->mt_loose_pgs) {
2799 MDB_page *mp = txn->mt_loose_pgs;
2800 /* Just return them to freeDB */
2801 if (env->me_pghead) {
2803 mop = env->me_pghead;
2804 for (; mp; mp = NEXT_LOOSE_PAGE(mp)) {
2805 pgno_t pg = mp->mp_pgno;
2807 for (i = mop[0]; i && mop[i] < pg; i--)
2813 /* Oh well, they were wasted. Put on freelist */
2814 for (; mp; mp = NEXT_LOOSE_PAGE(mp)) {
2815 mdb_midl_append(&txn->mt_free_pgs, mp->mp_pgno);
2818 txn->mt_loose_pgs = NULL;
2821 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2822 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2823 ? SSIZE_MAX : maxfree_1pg;
2826 /* Come back here after each Put() in case freelist changed */
2831 /* If using records from freeDB which we have not yet
2832 * deleted, delete them and any we reserved for me_pghead.
2834 while (pglast < env->me_pglast) {
2835 rc = mdb_cursor_first(&mc, &key, NULL);
2838 pglast = head_id = *(txnid_t *)key.mv_data;
2839 total_room = head_room = 0;
2840 mdb_tassert(txn, pglast <= env->me_pglast);
2841 rc = mdb_cursor_del(&mc, 0);
2846 /* Save the IDL of pages freed by this txn, to a single record */
2847 if (freecnt < txn->mt_free_pgs[0]) {
2849 /* Make sure last page of freeDB is touched and on freelist */
2850 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2851 if (rc && rc != MDB_NOTFOUND)
2854 free_pgs = txn->mt_free_pgs;
2855 /* Write to last page of freeDB */
2856 key.mv_size = sizeof(txn->mt_txnid);
2857 key.mv_data = &txn->mt_txnid;
2859 freecnt = free_pgs[0];
2860 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2861 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2864 /* Retry if mt_free_pgs[] grew during the Put() */
2865 free_pgs = txn->mt_free_pgs;
2866 } while (freecnt < free_pgs[0]);
2867 mdb_midl_sort(free_pgs);
2868 memcpy(data.mv_data, free_pgs, data.mv_size);
2871 unsigned int i = free_pgs[0];
2872 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2873 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2875 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2881 mop = env->me_pghead;
2882 mop_len = mop ? mop[0] : 0;
2884 /* Reserve records for me_pghead[]. Split it if multi-page,
2885 * to avoid searching freeDB for a page range. Use keys in
2886 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2888 if (total_room >= mop_len) {
2889 if (total_room == mop_len || --more < 0)
2891 } else if (head_room >= maxfree_1pg && head_id > 1) {
2892 /* Keep current record (overflow page), add a new one */
2896 /* (Re)write {key = head_id, IDL length = head_room} */
2897 total_room -= head_room;
2898 head_room = mop_len - total_room;
2899 if (head_room > maxfree_1pg && head_id > 1) {
2900 /* Overflow multi-page for part of me_pghead */
2901 head_room /= head_id; /* amortize page sizes */
2902 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2903 } else if (head_room < 0) {
2904 /* Rare case, not bothering to delete this record */
2907 key.mv_size = sizeof(head_id);
2908 key.mv_data = &head_id;
2909 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2910 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2913 /* IDL is initially empty, zero out at least the length */
2914 pgs = (pgno_t *)data.mv_data;
2915 j = head_room > clean_limit ? head_room : 0;
2919 total_room += head_room;
2922 /* Fill in the reserved me_pghead records */
2928 rc = mdb_cursor_first(&mc, &key, &data);
2929 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2930 txnid_t id = *(txnid_t *)key.mv_data;
2931 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2934 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
2936 if (len > mop_len) {
2938 data.mv_size = (len + 1) * sizeof(MDB_ID);
2940 data.mv_data = mop -= len;
2943 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
2945 if (rc || !(mop_len -= len))
2952 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
2953 * @param[in] txn the transaction that's being committed
2954 * @param[in] keep number of initial pages in dirty_list to keep dirty.
2955 * @return 0 on success, non-zero on failure.
2958 mdb_page_flush(MDB_txn *txn, int keep)
2960 MDB_env *env = txn->mt_env;
2961 MDB_ID2L dl = txn->mt_u.dirty_list;
2962 unsigned psize = env->me_psize, j;
2963 int i, pagecount = dl[0].mid, rc;
2964 size_t size = 0, pos = 0;
2966 MDB_page *dp = NULL;
2970 struct iovec iov[MDB_COMMIT_PAGES];
2971 ssize_t wpos = 0, wsize = 0, wres;
2972 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
2978 if (env->me_flags & MDB_WRITEMAP) {
2979 /* Clear dirty flags */
2980 while (++i <= pagecount) {
2982 /* Don't flush this page yet */
2983 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
2984 dp->mp_flags &= ~P_KEEP;
2988 dp->mp_flags &= ~P_DIRTY;
2993 /* Write the pages */
2995 if (++i <= pagecount) {
2997 /* Don't flush this page yet */
2998 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
2999 dp->mp_flags &= ~P_KEEP;
3004 /* clear dirty flag */
3005 dp->mp_flags &= ~P_DIRTY;
3008 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3013 /* Windows actually supports scatter/gather I/O, but only on
3014 * unbuffered file handles. Since we're relying on the OS page
3015 * cache for all our data, that's self-defeating. So we just
3016 * write pages one at a time. We use the ov structure to set
3017 * the write offset, to at least save the overhead of a Seek
3020 DPRINTF(("committing page %"Z"u", pgno));
3021 memset(&ov, 0, sizeof(ov));
3022 ov.Offset = pos & 0xffffffff;
3023 ov.OffsetHigh = pos >> 16 >> 16;
3024 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3026 DPRINTF(("WriteFile: %d", rc));
3030 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3031 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3033 /* Write previous page(s) */
3034 #ifdef MDB_USE_PWRITEV
3035 wres = pwritev(env->me_fd, iov, n, wpos);
3038 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3040 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3042 DPRINTF(("lseek: %s", strerror(rc)));
3045 wres = writev(env->me_fd, iov, n);
3048 if (wres != wsize) {
3051 DPRINTF(("Write error: %s", strerror(rc)));
3053 rc = EIO; /* TODO: Use which error code? */
3054 DPUTS("short write, filesystem full?");
3065 DPRINTF(("committing page %"Z"u", pgno));
3066 next_pos = pos + size;
3067 iov[n].iov_len = size;
3068 iov[n].iov_base = (char *)dp;
3074 for (i = keep; ++i <= pagecount; ) {
3076 /* This is a page we skipped above */
3079 dl[j].mid = dp->mp_pgno;
3082 mdb_dpage_free(env, dp);
3087 txn->mt_dirty_room += i - j;
3093 mdb_txn_commit(MDB_txn *txn)
3099 if (txn == NULL || txn->mt_env == NULL)
3102 if (txn->mt_child) {
3103 rc = mdb_txn_commit(txn->mt_child);
3104 txn->mt_child = NULL;
3111 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3112 mdb_dbis_update(txn, 1);
3113 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
3118 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
3119 DPUTS("error flag is set, can't commit");
3121 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3126 if (txn->mt_parent) {
3127 MDB_txn *parent = txn->mt_parent;
3131 unsigned x, y, len, ps_len;
3133 /* Append our free list to parent's */
3134 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3137 mdb_midl_free(txn->mt_free_pgs);
3138 /* Failures after this must either undo the changes
3139 * to the parent or set MDB_TXN_ERROR in the parent.
3142 parent->mt_next_pgno = txn->mt_next_pgno;
3143 parent->mt_flags = txn->mt_flags;
3145 /* Merge our cursors into parent's and close them */
3146 mdb_cursors_close(txn, 1);
3148 /* Update parent's DB table. */
3149 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3150 parent->mt_numdbs = txn->mt_numdbs;
3151 parent->mt_dbflags[0] = txn->mt_dbflags[0];
3152 parent->mt_dbflags[1] = txn->mt_dbflags[1];
3153 for (i=2; i<txn->mt_numdbs; i++) {
3154 /* preserve parent's DB_NEW status */
3155 x = parent->mt_dbflags[i] & DB_NEW;
3156 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3159 dst = parent->mt_u.dirty_list;
3160 src = txn->mt_u.dirty_list;
3161 /* Remove anything in our dirty list from parent's spill list */
3162 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3164 pspill[0] = (pgno_t)-1;
3165 /* Mark our dirty pages as deleted in parent spill list */
3166 for (i=0, len=src[0].mid; ++i <= len; ) {
3167 MDB_ID pn = src[i].mid << 1;
3168 while (pn > pspill[x])
3170 if (pn == pspill[x]) {
3175 /* Squash deleted pagenums if we deleted any */
3176 for (x=y; ++x <= ps_len; )
3177 if (!(pspill[x] & 1))
3178 pspill[++y] = pspill[x];
3182 /* Find len = length of merging our dirty list with parent's */
3184 dst[0].mid = 0; /* simplify loops */
3185 if (parent->mt_parent) {
3186 len = x + src[0].mid;
3187 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3188 for (i = x; y && i; y--) {
3189 pgno_t yp = src[y].mid;
3190 while (yp < dst[i].mid)
3192 if (yp == dst[i].mid) {
3197 } else { /* Simplify the above for single-ancestor case */
3198 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3200 /* Merge our dirty list with parent's */
3202 for (i = len; y; dst[i--] = src[y--]) {
3203 pgno_t yp = src[y].mid;
3204 while (yp < dst[x].mid)
3205 dst[i--] = dst[x--];
3206 if (yp == dst[x].mid)
3207 free(dst[x--].mptr);
3209 mdb_tassert(txn, i == x);
3211 free(txn->mt_u.dirty_list);
3212 parent->mt_dirty_room = txn->mt_dirty_room;
3213 if (txn->mt_spill_pgs) {
3214 if (parent->mt_spill_pgs) {
3215 /* TODO: Prevent failure here, so parent does not fail */
3216 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3218 parent->mt_flags |= MDB_TXN_ERROR;
3219 mdb_midl_free(txn->mt_spill_pgs);
3220 mdb_midl_sort(parent->mt_spill_pgs);
3222 parent->mt_spill_pgs = txn->mt_spill_pgs;
3226 /* Append our loose page list to parent's */
3227 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(lp))
3229 *lp = txn->mt_loose_pgs;
3231 parent->mt_child = NULL;
3232 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3237 if (txn != env->me_txn) {
3238 DPUTS("attempt to commit unknown transaction");
3243 mdb_cursors_close(txn, 0);
3245 if (!txn->mt_u.dirty_list[0].mid &&
3246 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS))) {
3247 if ((env->me_flags & MDB_RESIZING)
3248 && (rc = mdb_env_write_meta(txn))) {
3254 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3255 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3257 /* Update DB root pointers */
3258 if (txn->mt_numdbs > 2) {
3262 data.mv_size = sizeof(MDB_db);
3264 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3265 for (i = 2; i < txn->mt_numdbs; i++) {
3266 if (txn->mt_dbflags[i] & DB_DIRTY) {
3267 if (TXN_DBI_CHANGED(txn, i)) {
3271 data.mv_data = &txn->mt_dbs[i];
3272 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
3279 rc = mdb_freelist_save(txn);
3283 mdb_midl_free(env->me_pghead);
3284 env->me_pghead = NULL;
3285 if (mdb_midl_shrink(&txn->mt_free_pgs))
3286 env->me_free_pgs = txn->mt_free_pgs;
3292 if ((rc = mdb_page_flush(txn, 0)) ||
3293 (rc = mdb_env_sync(env, 0)) ||
3294 (rc = mdb_env_write_meta(txn)))
3300 mdb_dbis_update(txn, 1);
3303 UNLOCK_MUTEX_W(env);
3313 /** Read the environment parameters of a DB environment before
3314 * mapping it into memory.
3315 * @param[in] env the environment handle
3316 * @param[out] meta address of where to store the meta information
3317 * @return 0 on success, non-zero on failure.
3320 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3326 enum { Size = sizeof(pbuf) };
3328 /* We don't know the page size yet, so use a minimum value.
3329 * Read both meta pages so we can use the latest one.
3332 for (i=off=0; i<2; i++, off = meta->mm_psize) {
3336 memset(&ov, 0, sizeof(ov));
3338 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3339 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3342 rc = pread(env->me_fd, &pbuf, Size, off);
3345 if (rc == 0 && off == 0)
3347 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3348 DPRINTF(("read: %s", mdb_strerror(rc)));
3352 p = (MDB_page *)&pbuf;
3354 if (!F_ISSET(p->mp_flags, P_META)) {
3355 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3360 if (m->mm_magic != MDB_MAGIC) {
3361 DPUTS("meta has invalid magic");
3365 if (m->mm_version != MDB_DATA_VERSION) {
3366 DPRINTF(("database is version %u, expected version %u",
3367 m->mm_version, MDB_DATA_VERSION));
3368 return MDB_VERSION_MISMATCH;
3371 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3378 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3380 meta->mm_magic = MDB_MAGIC;
3381 meta->mm_version = MDB_DATA_VERSION;
3382 meta->mm_mapsize = env->me_mapsize;
3383 meta->mm_psize = env->me_psize;
3384 meta->mm_last_pg = 1;
3385 meta->mm_flags = env->me_flags & 0xffff;
3386 meta->mm_flags |= MDB_INTEGERKEY;
3387 meta->mm_dbs[0].md_root = P_INVALID;
3388 meta->mm_dbs[1].md_root = P_INVALID;
3391 /** Write the environment parameters of a freshly created DB environment.
3392 * @param[in] env the environment handle
3393 * @param[out] meta address of where to store the meta information
3394 * @return 0 on success, non-zero on failure.
3397 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3405 memset(&ov, 0, sizeof(ov));
3406 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3408 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3411 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3412 len = pwrite(fd, ptr, size, pos); \
3413 rc = (len >= 0); } while(0)
3416 DPUTS("writing new meta page");
3418 psize = env->me_psize;
3420 mdb_env_init_meta0(env, meta);
3422 p = calloc(2, psize);
3424 p->mp_flags = P_META;
3425 *(MDB_meta *)METADATA(p) = *meta;
3427 q = (MDB_page *)((char *)p + psize);
3429 q->mp_flags = P_META;
3430 *(MDB_meta *)METADATA(q) = *meta;
3432 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3435 else if ((unsigned) len == psize * 2)
3443 /** Update the environment info to commit a transaction.
3444 * @param[in] txn the transaction that's being committed
3445 * @return 0 on success, non-zero on failure.
3448 mdb_env_write_meta(MDB_txn *txn)
3451 MDB_meta meta, metab, *mp;
3453 int rc, len, toggle;
3462 toggle = txn->mt_txnid & 1;
3463 DPRINTF(("writing meta page %d for root page %"Z"u",
3464 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3467 mp = env->me_metas[toggle];
3469 if (env->me_flags & MDB_WRITEMAP) {
3470 /* Persist any changes of mapsize config */
3471 if (env->me_flags & MDB_RESIZING) {
3472 mp->mm_mapsize = env->me_mapsize;
3473 env->me_flags ^= MDB_RESIZING;
3475 mp->mm_dbs[0] = txn->mt_dbs[0];
3476 mp->mm_dbs[1] = txn->mt_dbs[1];
3477 mp->mm_last_pg = txn->mt_next_pgno - 1;
3478 mp->mm_txnid = txn->mt_txnid;
3479 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3480 unsigned meta_size = env->me_psize;
3481 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3484 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3485 if (meta_size < env->me_os_psize)
3486 meta_size += meta_size;
3491 if (MDB_MSYNC(ptr, meta_size, rc)) {
3498 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3499 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3501 ptr = (char *)&meta;
3502 if (env->me_flags & MDB_RESIZING) {
3503 /* Persist any changes of mapsize config */
3504 meta.mm_mapsize = env->me_mapsize;
3505 off = offsetof(MDB_meta, mm_mapsize);
3506 env->me_flags ^= MDB_RESIZING;
3508 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
3510 len = sizeof(MDB_meta) - off;
3513 meta.mm_dbs[0] = txn->mt_dbs[0];
3514 meta.mm_dbs[1] = txn->mt_dbs[1];
3515 meta.mm_last_pg = txn->mt_next_pgno - 1;
3516 meta.mm_txnid = txn->mt_txnid;
3519 off += env->me_psize;
3522 /* Write to the SYNC fd */
3523 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3524 env->me_fd : env->me_mfd;
3527 memset(&ov, 0, sizeof(ov));
3529 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3533 rc = pwrite(mfd, ptr, len, off);
3536 rc = rc < 0 ? ErrCode() : EIO;
3537 DPUTS("write failed, disk error?");
3538 /* On a failure, the pagecache still contains the new data.
3539 * Write some old data back, to prevent it from being used.
3540 * Use the non-SYNC fd; we know it will fail anyway.
3542 meta.mm_last_pg = metab.mm_last_pg;
3543 meta.mm_txnid = metab.mm_txnid;
3545 memset(&ov, 0, sizeof(ov));
3547 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3549 r2 = pwrite(env->me_fd, ptr, len, off);
3550 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3553 env->me_flags |= MDB_FATAL_ERROR;
3557 /* Memory ordering issues are irrelevant; since the entire writer
3558 * is wrapped by wmutex, all of these changes will become visible
3559 * after the wmutex is unlocked. Since the DB is multi-version,
3560 * readers will get consistent data regardless of how fresh or
3561 * how stale their view of these values is.
3564 env->me_txns->mti_txnid = txn->mt_txnid;
3569 /** Check both meta pages to see which one is newer.
3570 * @param[in] env the environment handle
3571 * @return meta toggle (0 or 1).
3574 mdb_env_pick_meta(const MDB_env *env)
3576 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3580 mdb_env_create(MDB_env **env)
3584 e = calloc(1, sizeof(MDB_env));
3588 e->me_maxreaders = DEFAULT_READERS;
3589 e->me_maxdbs = e->me_numdbs = 2;
3590 e->me_fd = INVALID_HANDLE_VALUE;
3591 e->me_lfd = INVALID_HANDLE_VALUE;
3592 e->me_mfd = INVALID_HANDLE_VALUE;
3593 #ifdef MDB_USE_POSIX_SEM
3594 e->me_rmutex = SEM_FAILED;
3595 e->me_wmutex = SEM_FAILED;
3597 e->me_pid = getpid();
3598 GET_PAGESIZE(e->me_os_psize);
3599 VGMEMP_CREATE(e,0,0);
3605 mdb_env_map(MDB_env *env, void *addr, int newsize)
3608 unsigned int flags = env->me_flags;
3612 LONG sizelo, sizehi;
3615 if (flags & MDB_RDONLY) {
3620 msize = env->me_mapsize;
3621 sizelo = msize & 0xffffffff;
3622 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3625 /* Windows won't create mappings for zero length files.
3626 * Just allocate the maxsize right now.
3629 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3630 || !SetEndOfFile(env->me_fd)
3631 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3634 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3635 PAGE_READWRITE : PAGE_READONLY,
3636 sizehi, sizelo, NULL);
3639 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3640 FILE_MAP_WRITE : FILE_MAP_READ,
3642 rc = env->me_map ? 0 : ErrCode();
3647 int prot = PROT_READ;
3648 if (flags & MDB_WRITEMAP) {
3650 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3653 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3655 if (env->me_map == MAP_FAILED) {
3660 if (flags & MDB_NORDAHEAD) {
3661 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3663 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3665 #ifdef POSIX_MADV_RANDOM
3666 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3667 #endif /* POSIX_MADV_RANDOM */
3668 #endif /* MADV_RANDOM */
3672 /* Can happen because the address argument to mmap() is just a
3673 * hint. mmap() can pick another, e.g. if the range is in use.
3674 * The MAP_FIXED flag would prevent that, but then mmap could
3675 * instead unmap existing pages to make room for the new map.
3677 if (addr && env->me_map != addr)
3678 return EBUSY; /* TODO: Make a new MDB_* error code? */
3680 p = (MDB_page *)env->me_map;
3681 env->me_metas[0] = METADATA(p);
3682 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3688 mdb_env_set_mapsize(MDB_env *env, size_t size)
3690 /* If env is already open, caller is responsible for making
3691 * sure there are no active txns.
3699 size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3701 if (size < env->me_mapsize) {
3702 /* If the configured size is smaller, make sure it's
3703 * still big enough. Silently round up to minimum if not.
3705 size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3709 /* nothing actually changed */
3710 if (size == env->me_mapsize)
3714 munmap(env->me_map, env->me_mapsize);
3715 env->me_mapsize = size;
3716 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3717 rc = mdb_env_map(env, old, 1);
3721 env->me_flags |= MDB_RESIZING;
3723 env->me_mapsize = size;
3725 env->me_maxpg = env->me_mapsize / env->me_psize;
3730 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3734 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3739 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3741 if (env->me_map || readers < 1)
3743 env->me_maxreaders = readers;
3748 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3750 if (!env || !readers)
3752 *readers = env->me_maxreaders;
3756 /** Further setup required for opening an LMDB environment
3759 mdb_env_open2(MDB_env *env)
3761 unsigned int flags = env->me_flags;
3762 int i, newenv = 0, rc;
3766 /* See if we should use QueryLimited */
3768 if ((rc & 0xff) > 5)
3769 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3771 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3774 memset(&meta, 0, sizeof(meta));
3776 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3779 DPUTS("new mdbenv");
3781 env->me_psize = env->me_os_psize;
3782 if (env->me_psize > MAX_PAGESIZE)
3783 env->me_psize = MAX_PAGESIZE;
3785 env->me_psize = meta.mm_psize;
3788 /* Was a mapsize configured? */
3789 if (!env->me_mapsize) {
3790 /* If this is a new environment, take the default,
3791 * else use the size recorded in the existing env.
3793 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3794 } else if (env->me_mapsize < meta.mm_mapsize) {
3795 /* If the configured size is smaller, make sure it's
3796 * still big enough. Silently round up to minimum if not.
3798 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3799 if (env->me_mapsize < minsize)
3800 env->me_mapsize = minsize;
3803 rc = mdb_env_map(env, meta.mm_address, newenv || env->me_mapsize != meta.mm_mapsize);
3808 if (flags & MDB_FIXEDMAP)
3809 meta.mm_address = env->me_map;
3810 i = mdb_env_init_meta(env, &meta);
3811 if (i != MDB_SUCCESS) {
3816 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3817 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
3819 #if !(MDB_MAXKEYSIZE)
3820 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
3822 env->me_maxpg = env->me_mapsize / env->me_psize;
3826 int toggle = mdb_env_pick_meta(env);
3827 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3829 DPRINTF(("opened database version %u, pagesize %u",
3830 env->me_metas[0]->mm_version, env->me_psize));
3831 DPRINTF(("using meta page %d", toggle));
3832 DPRINTF(("depth: %u", db->md_depth));
3833 DPRINTF(("entries: %"Z"u", db->md_entries));
3834 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
3835 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
3836 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3837 DPRINTF(("root: %"Z"u", db->md_root));
3845 /** Release a reader thread's slot in the reader lock table.
3846 * This function is called automatically when a thread exits.
3847 * @param[in] ptr This points to the slot in the reader lock table.
3850 mdb_env_reader_dest(void *ptr)
3852 MDB_reader *reader = ptr;
3858 /** Junk for arranging thread-specific callbacks on Windows. This is
3859 * necessarily platform and compiler-specific. Windows supports up
3860 * to 1088 keys. Let's assume nobody opens more than 64 environments
3861 * in a single process, for now. They can override this if needed.
3863 #ifndef MAX_TLS_KEYS
3864 #define MAX_TLS_KEYS 64
3866 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3867 static int mdb_tls_nkeys;
3869 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3873 case DLL_PROCESS_ATTACH: break;
3874 case DLL_THREAD_ATTACH: break;
3875 case DLL_THREAD_DETACH:
3876 for (i=0; i<mdb_tls_nkeys; i++) {
3877 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3879 mdb_env_reader_dest(r);
3883 case DLL_PROCESS_DETACH: break;
3888 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3890 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3894 /* Force some symbol references.
3895 * _tls_used forces the linker to create the TLS directory if not already done
3896 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3898 #pragma comment(linker, "/INCLUDE:_tls_used")
3899 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3900 #pragma const_seg(".CRT$XLB")
3901 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
3902 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3905 #pragma comment(linker, "/INCLUDE:__tls_used")
3906 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3907 #pragma data_seg(".CRT$XLB")
3908 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3910 #endif /* WIN 32/64 */
3911 #endif /* !__GNUC__ */
3914 /** Downgrade the exclusive lock on the region back to shared */
3916 mdb_env_share_locks(MDB_env *env, int *excl)
3918 int rc = 0, toggle = mdb_env_pick_meta(env);
3920 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3925 /* First acquire a shared lock. The Unlock will
3926 * then release the existing exclusive lock.
3928 memset(&ov, 0, sizeof(ov));
3929 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3932 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3938 struct flock lock_info;
3939 /* The shared lock replaces the existing lock */
3940 memset((void *)&lock_info, 0, sizeof(lock_info));
3941 lock_info.l_type = F_RDLCK;
3942 lock_info.l_whence = SEEK_SET;
3943 lock_info.l_start = 0;
3944 lock_info.l_len = 1;
3945 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3946 (rc = ErrCode()) == EINTR) ;
3947 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3954 /** Try to get exlusive lock, otherwise shared.
3955 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3958 mdb_env_excl_lock(MDB_env *env, int *excl)
3962 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3966 memset(&ov, 0, sizeof(ov));
3967 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3974 struct flock lock_info;
3975 memset((void *)&lock_info, 0, sizeof(lock_info));
3976 lock_info.l_type = F_WRLCK;
3977 lock_info.l_whence = SEEK_SET;
3978 lock_info.l_start = 0;
3979 lock_info.l_len = 1;
3980 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3981 (rc = ErrCode()) == EINTR) ;
3985 # ifdef MDB_USE_POSIX_SEM
3986 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3989 lock_info.l_type = F_RDLCK;
3990 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3991 (rc = ErrCode()) == EINTR) ;
4001 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4003 * @(#) $Revision: 5.1 $
4004 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4005 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4007 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4011 * Please do not copyright this code. This code is in the public domain.
4013 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4014 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4015 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4016 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4017 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4018 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4019 * PERFORMANCE OF THIS SOFTWARE.
4022 * chongo <Landon Curt Noll> /\oo/\
4023 * http://www.isthe.com/chongo/
4025 * Share and Enjoy! :-)
4028 typedef unsigned long long mdb_hash_t;
4029 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4031 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4032 * @param[in] val value to hash
4033 * @param[in] hval initial value for hash
4034 * @return 64 bit hash
4036 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4037 * hval arg on the first call.
4040 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4042 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4043 unsigned char *end = s + val->mv_size;
4045 * FNV-1a hash each octet of the string
4048 /* xor the bottom with the current octet */
4049 hval ^= (mdb_hash_t)*s++;
4051 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4052 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4053 (hval << 7) + (hval << 8) + (hval << 40);
4055 /* return our new hash value */
4059 /** Hash the string and output the encoded hash.
4060 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4061 * very short name limits. We don't care about the encoding being reversible,
4062 * we just want to preserve as many bits of the input as possible in a
4063 * small printable string.
4064 * @param[in] str string to hash
4065 * @param[out] encbuf an array of 11 chars to hold the hash
4067 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4070 mdb_pack85(unsigned long l, char *out)
4074 for (i=0; i<5; i++) {
4075 *out++ = mdb_a85[l % 85];
4081 mdb_hash_enc(MDB_val *val, char *encbuf)
4083 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4085 mdb_pack85(h, encbuf);
4086 mdb_pack85(h>>32, encbuf+5);
4091 /** Open and/or initialize the lock region for the environment.
4092 * @param[in] env The LMDB environment.
4093 * @param[in] lpath The pathname of the file used for the lock region.
4094 * @param[in] mode The Unix permissions for the file, if we create it.
4095 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
4096 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4097 * @return 0 on success, non-zero on failure.
4100 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4103 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4105 # define MDB_ERRCODE_ROFS EROFS
4106 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4107 # define MDB_CLOEXEC O_CLOEXEC
4110 # define MDB_CLOEXEC 0
4117 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
4118 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4119 FILE_ATTRIBUTE_NORMAL, NULL);
4121 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4123 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4125 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4130 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4131 /* Lose record locks when exec*() */
4132 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4133 fcntl(env->me_lfd, F_SETFD, fdflags);
4136 if (!(env->me_flags & MDB_NOTLS)) {
4137 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4140 env->me_flags |= MDB_ENV_TXKEY;
4142 /* Windows TLS callbacks need help finding their TLS info. */
4143 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4147 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4151 /* Try to get exclusive lock. If we succeed, then
4152 * nobody is using the lock region and we should initialize it.
4154 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4157 size = GetFileSize(env->me_lfd, NULL);
4159 size = lseek(env->me_lfd, 0, SEEK_END);
4160 if (size == -1) goto fail_errno;
4162 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4163 if (size < rsize && *excl > 0) {
4165 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4166 || !SetEndOfFile(env->me_lfd))
4169 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4173 size = rsize - sizeof(MDB_txninfo);
4174 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4179 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4181 if (!mh) goto fail_errno;
4182 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4184 if (!env->me_txns) goto fail_errno;
4186 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4188 if (m == MAP_FAILED) goto fail_errno;
4194 BY_HANDLE_FILE_INFORMATION stbuf;
4203 if (!mdb_sec_inited) {
4204 InitializeSecurityDescriptor(&mdb_null_sd,
4205 SECURITY_DESCRIPTOR_REVISION);
4206 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4207 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4208 mdb_all_sa.bInheritHandle = FALSE;
4209 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4212 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4213 idbuf.volume = stbuf.dwVolumeSerialNumber;
4214 idbuf.nhigh = stbuf.nFileIndexHigh;
4215 idbuf.nlow = stbuf.nFileIndexLow;
4216 val.mv_data = &idbuf;
4217 val.mv_size = sizeof(idbuf);
4218 mdb_hash_enc(&val, encbuf);
4219 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4220 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4221 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4222 if (!env->me_rmutex) goto fail_errno;
4223 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4224 if (!env->me_wmutex) goto fail_errno;
4225 #elif defined(MDB_USE_POSIX_SEM)
4234 #if defined(__NetBSD__)
4235 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4237 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4238 idbuf.dev = stbuf.st_dev;
4239 idbuf.ino = stbuf.st_ino;
4240 val.mv_data = &idbuf;
4241 val.mv_size = sizeof(idbuf);
4242 mdb_hash_enc(&val, encbuf);
4243 #ifdef MDB_SHORT_SEMNAMES
4244 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4246 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4247 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4248 /* Clean up after a previous run, if needed: Try to
4249 * remove both semaphores before doing anything else.
4251 sem_unlink(env->me_txns->mti_rmname);
4252 sem_unlink(env->me_txns->mti_wmname);
4253 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4254 O_CREAT|O_EXCL, mode, 1);
4255 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4256 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4257 O_CREAT|O_EXCL, mode, 1);
4258 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4259 #else /* MDB_USE_POSIX_SEM */
4260 pthread_mutexattr_t mattr;
4262 if ((rc = pthread_mutexattr_init(&mattr))
4263 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4264 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
4265 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
4267 pthread_mutexattr_destroy(&mattr);
4268 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4270 env->me_txns->mti_magic = MDB_MAGIC;
4271 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4272 env->me_txns->mti_txnid = 0;
4273 env->me_txns->mti_numreaders = 0;
4276 if (env->me_txns->mti_magic != MDB_MAGIC) {
4277 DPUTS("lock region has invalid magic");
4281 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4282 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4283 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4284 rc = MDB_VERSION_MISMATCH;
4288 if (rc && rc != EACCES && rc != EAGAIN) {
4292 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4293 if (!env->me_rmutex) goto fail_errno;
4294 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4295 if (!env->me_wmutex) goto fail_errno;
4296 #elif defined(MDB_USE_POSIX_SEM)
4297 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4298 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4299 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4300 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4311 /** The name of the lock file in the DB environment */
4312 #define LOCKNAME "/lock.mdb"
4313 /** The name of the data file in the DB environment */
4314 #define DATANAME "/data.mdb"
4315 /** The suffix of the lock file when no subdir is used */
4316 #define LOCKSUFF "-lock"
4317 /** Only a subset of the @ref mdb_env flags can be changed
4318 * at runtime. Changing other flags requires closing the
4319 * environment and re-opening it with the new flags.
4321 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4322 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP| \
4323 MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4325 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4326 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4330 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4332 int oflags, rc, len, excl = -1;
4333 char *lpath, *dpath;
4335 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4339 if (flags & MDB_NOSUBDIR) {
4340 rc = len + sizeof(LOCKSUFF) + len + 1;
4342 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4347 if (flags & MDB_NOSUBDIR) {
4348 dpath = lpath + len + sizeof(LOCKSUFF);
4349 sprintf(lpath, "%s" LOCKSUFF, path);
4350 strcpy(dpath, path);
4352 dpath = lpath + len + sizeof(LOCKNAME);
4353 sprintf(lpath, "%s" LOCKNAME, path);
4354 sprintf(dpath, "%s" DATANAME, path);
4358 flags |= env->me_flags;
4359 if (flags & MDB_RDONLY) {
4360 /* silently ignore WRITEMAP when we're only getting read access */
4361 flags &= ~MDB_WRITEMAP;
4363 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4364 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4367 env->me_flags = flags |= MDB_ENV_ACTIVE;
4371 env->me_path = strdup(path);
4372 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4373 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4374 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4375 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4380 /* For RDONLY, get lockfile after we know datafile exists */
4381 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4382 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4388 if (F_ISSET(flags, MDB_RDONLY)) {
4389 oflags = GENERIC_READ;
4390 len = OPEN_EXISTING;
4392 oflags = GENERIC_READ|GENERIC_WRITE;
4395 mode = FILE_ATTRIBUTE_NORMAL;
4396 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4397 NULL, len, mode, NULL);
4399 if (F_ISSET(flags, MDB_RDONLY))
4402 oflags = O_RDWR | O_CREAT;
4404 env->me_fd = open(dpath, oflags, mode);
4406 if (env->me_fd == INVALID_HANDLE_VALUE) {
4411 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4412 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4417 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4418 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4419 env->me_mfd = env->me_fd;
4421 /* Synchronous fd for meta writes. Needed even with
4422 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4425 len = OPEN_EXISTING;
4426 env->me_mfd = CreateFile(dpath, oflags,
4427 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4428 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4431 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4433 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4438 DPRINTF(("opened dbenv %p", (void *) env));
4440 rc = mdb_env_share_locks(env, &excl);
4444 if (!((flags & MDB_RDONLY) ||
4445 (env->me_pbuf = calloc(1, env->me_psize))))
4451 mdb_env_close0(env, excl);
4457 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4459 mdb_env_close0(MDB_env *env, int excl)
4463 if (!(env->me_flags & MDB_ENV_ACTIVE))
4466 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4467 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4468 free(env->me_dbxs[i].md_name.mv_data);
4471 free(env->me_dbiseqs);
4472 free(env->me_dbflags);
4475 free(env->me_dirty_list);
4476 mdb_midl_free(env->me_free_pgs);
4478 if (env->me_flags & MDB_ENV_TXKEY) {
4479 pthread_key_delete(env->me_txkey);
4481 /* Delete our key from the global list */
4482 for (i=0; i<mdb_tls_nkeys; i++)
4483 if (mdb_tls_keys[i] == env->me_txkey) {
4484 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4492 munmap(env->me_map, env->me_mapsize);
4494 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4495 (void) close(env->me_mfd);
4496 if (env->me_fd != INVALID_HANDLE_VALUE)
4497 (void) close(env->me_fd);
4499 MDB_PID_T pid = env->me_pid;
4500 /* Clearing readers is done in this function because
4501 * me_txkey with its destructor must be disabled first.
4503 for (i = env->me_numreaders; --i >= 0; )
4504 if (env->me_txns->mti_readers[i].mr_pid == pid)
4505 env->me_txns->mti_readers[i].mr_pid = 0;
4507 if (env->me_rmutex) {
4508 CloseHandle(env->me_rmutex);
4509 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4511 /* Windows automatically destroys the mutexes when
4512 * the last handle closes.
4514 #elif defined(MDB_USE_POSIX_SEM)
4515 if (env->me_rmutex != SEM_FAILED) {
4516 sem_close(env->me_rmutex);
4517 if (env->me_wmutex != SEM_FAILED)
4518 sem_close(env->me_wmutex);
4519 /* If we have the filelock: If we are the
4520 * only remaining user, clean up semaphores.
4523 mdb_env_excl_lock(env, &excl);
4525 sem_unlink(env->me_txns->mti_rmname);
4526 sem_unlink(env->me_txns->mti_wmname);
4530 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4532 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4535 /* Unlock the lockfile. Windows would have unlocked it
4536 * after closing anyway, but not necessarily at once.
4538 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4541 (void) close(env->me_lfd);
4544 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4549 mdb_env_close(MDB_env *env)
4556 VGMEMP_DESTROY(env);
4557 while ((dp = env->me_dpages) != NULL) {
4558 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4559 env->me_dpages = dp->mp_next;
4563 mdb_env_close0(env, 0);
4567 /** Compare two items pointing at aligned size_t's */
4569 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4571 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4572 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4575 /** Compare two items pointing at aligned unsigned int's */
4577 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4579 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4580 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4583 /** Compare two items pointing at unsigned ints of unknown alignment.
4584 * Nodes and keys are guaranteed to be 2-byte aligned.
4587 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4589 #if BYTE_ORDER == LITTLE_ENDIAN
4590 unsigned short *u, *c;
4593 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4594 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4597 } while(!x && u > (unsigned short *)a->mv_data);
4600 unsigned short *u, *c, *end;
4603 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4604 u = (unsigned short *)a->mv_data;
4605 c = (unsigned short *)b->mv_data;
4608 } while(!x && u < end);
4613 /** Compare two items pointing at size_t's of unknown alignment. */
4614 #ifdef MISALIGNED_OK
4615 # define mdb_cmp_clong mdb_cmp_long
4617 # define mdb_cmp_clong mdb_cmp_cint
4620 /** Compare two items lexically */
4622 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4629 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4635 diff = memcmp(a->mv_data, b->mv_data, len);
4636 return diff ? diff : len_diff<0 ? -1 : len_diff;
4639 /** Compare two items in reverse byte order */
4641 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4643 const unsigned char *p1, *p2, *p1_lim;
4647 p1_lim = (const unsigned char *)a->mv_data;
4648 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4649 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4651 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4657 while (p1 > p1_lim) {
4658 diff = *--p1 - *--p2;
4662 return len_diff<0 ? -1 : len_diff;
4665 /** Search for key within a page, using binary search.
4666 * Returns the smallest entry larger or equal to the key.
4667 * If exactp is non-null, stores whether the found entry was an exact match
4668 * in *exactp (1 or 0).
4669 * Updates the cursor index with the index of the found entry.
4670 * If no entry larger or equal to the key is found, returns NULL.
4673 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4675 unsigned int i = 0, nkeys;
4678 MDB_page *mp = mc->mc_pg[mc->mc_top];
4679 MDB_node *node = NULL;
4684 nkeys = NUMKEYS(mp);
4686 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4687 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4690 low = IS_LEAF(mp) ? 0 : 1;
4692 cmp = mc->mc_dbx->md_cmp;
4694 /* Branch pages have no data, so if using integer keys,
4695 * alignment is guaranteed. Use faster mdb_cmp_int.
4697 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4698 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4705 nodekey.mv_size = mc->mc_db->md_pad;
4706 node = NODEPTR(mp, 0); /* fake */
4707 while (low <= high) {
4708 i = (low + high) >> 1;
4709 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4710 rc = cmp(key, &nodekey);
4711 DPRINTF(("found leaf index %u [%s], rc = %i",
4712 i, DKEY(&nodekey), rc));
4721 while (low <= high) {
4722 i = (low + high) >> 1;
4724 node = NODEPTR(mp, i);
4725 nodekey.mv_size = NODEKSZ(node);
4726 nodekey.mv_data = NODEKEY(node);
4728 rc = cmp(key, &nodekey);
4731 DPRINTF(("found leaf index %u [%s], rc = %i",
4732 i, DKEY(&nodekey), rc));
4734 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4735 i, DKEY(&nodekey), NODEPGNO(node), rc));
4746 if (rc > 0) { /* Found entry is less than the key. */
4747 i++; /* Skip to get the smallest entry larger than key. */
4749 node = NODEPTR(mp, i);
4752 *exactp = (rc == 0 && nkeys > 0);
4753 /* store the key index */
4754 mc->mc_ki[mc->mc_top] = i;
4756 /* There is no entry larger or equal to the key. */
4759 /* nodeptr is fake for LEAF2 */
4765 mdb_cursor_adjust(MDB_cursor *mc, func)
4769 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4770 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4777 /** Pop a page off the top of the cursor's stack. */
4779 mdb_cursor_pop(MDB_cursor *mc)
4783 MDB_page *top = mc->mc_pg[mc->mc_top];
4789 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4790 DDBI(mc), (void *) mc));
4794 /** Push a page onto the top of the cursor's stack. */
4796 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4798 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4799 DDBI(mc), (void *) mc));
4801 if (mc->mc_snum >= CURSOR_STACK) {
4802 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4803 return MDB_CURSOR_FULL;
4806 mc->mc_top = mc->mc_snum++;
4807 mc->mc_pg[mc->mc_top] = mp;
4808 mc->mc_ki[mc->mc_top] = 0;
4813 /** Find the address of the page corresponding to a given page number.
4814 * @param[in] txn the transaction for this access.
4815 * @param[in] pgno the page number for the page to retrieve.
4816 * @param[out] ret address of a pointer where the page's address will be stored.
4817 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4818 * @return 0 on success, non-zero on failure.
4821 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4823 MDB_env *env = txn->mt_env;
4827 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
4831 MDB_ID2L dl = tx2->mt_u.dirty_list;
4833 /* Spilled pages were dirtied in this txn and flushed
4834 * because the dirty list got full. Bring this page
4835 * back in from the map (but don't unspill it here,
4836 * leave that unless page_touch happens again).
4838 if (tx2->mt_spill_pgs) {
4839 MDB_ID pn = pgno << 1;
4840 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
4841 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
4842 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4847 unsigned x = mdb_mid2l_search(dl, pgno);
4848 if (x <= dl[0].mid && dl[x].mid == pgno) {
4854 } while ((tx2 = tx2->mt_parent) != NULL);
4857 if (pgno < txn->mt_next_pgno) {
4859 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4861 DPRINTF(("page %"Z"u not found", pgno));
4862 txn->mt_flags |= MDB_TXN_ERROR;
4863 return MDB_PAGE_NOTFOUND;
4873 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
4874 * The cursor is at the root page, set up the rest of it.
4877 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
4879 MDB_page *mp = mc->mc_pg[mc->mc_top];
4883 while (IS_BRANCH(mp)) {
4887 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
4888 mdb_cassert(mc, NUMKEYS(mp) > 1);
4889 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
4891 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
4893 if (flags & MDB_PS_LAST)
4894 i = NUMKEYS(mp) - 1;
4897 node = mdb_node_search(mc, key, &exact);
4899 i = NUMKEYS(mp) - 1;
4901 i = mc->mc_ki[mc->mc_top];
4903 mdb_cassert(mc, i > 0);
4907 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
4910 mdb_cassert(mc, i < NUMKEYS(mp));
4911 node = NODEPTR(mp, i);
4913 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4916 mc->mc_ki[mc->mc_top] = i;
4917 if ((rc = mdb_cursor_push(mc, mp)))
4920 if (flags & MDB_PS_MODIFY) {
4921 if ((rc = mdb_page_touch(mc)) != 0)
4923 mp = mc->mc_pg[mc->mc_top];
4928 DPRINTF(("internal error, index points to a %02X page!?",
4930 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4931 return MDB_CORRUPTED;
4934 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
4935 key ? DKEY(key) : "null"));
4936 mc->mc_flags |= C_INITIALIZED;
4937 mc->mc_flags &= ~C_EOF;
4942 /** Search for the lowest key under the current branch page.
4943 * This just bypasses a NUMKEYS check in the current page
4944 * before calling mdb_page_search_root(), because the callers
4945 * are all in situations where the current page is known to
4949 mdb_page_search_lowest(MDB_cursor *mc)
4951 MDB_page *mp = mc->mc_pg[mc->mc_top];
4952 MDB_node *node = NODEPTR(mp, 0);
4955 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4958 mc->mc_ki[mc->mc_top] = 0;
4959 if ((rc = mdb_cursor_push(mc, mp)))
4961 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
4964 /** Search for the page a given key should be in.
4965 * Push it and its parent pages on the cursor stack.
4966 * @param[in,out] mc the cursor for this operation.
4967 * @param[in] key the key to search for, or NULL for first/last page.
4968 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
4969 * are touched (updated with new page numbers).
4970 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
4971 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
4972 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4973 * @return 0 on success, non-zero on failure.
4976 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4981 /* Make sure the txn is still viable, then find the root from
4982 * the txn's db table and set it as the root of the cursor's stack.
4984 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4985 DPUTS("transaction has failed, must abort");
4988 /* Make sure we're using an up-to-date root */
4989 if (*mc->mc_dbflag & DB_STALE) {
4991 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
4993 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4994 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5001 MDB_node *leaf = mdb_node_search(&mc2,
5002 &mc->mc_dbx->md_name, &exact);
5004 return MDB_NOTFOUND;
5005 rc = mdb_node_read(mc->mc_txn, leaf, &data);
5008 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5010 /* The txn may not know this DBI, or another process may
5011 * have dropped and recreated the DB with other flags.
5013 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5014 return MDB_INCOMPATIBLE;
5015 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5017 *mc->mc_dbflag &= ~DB_STALE;
5019 root = mc->mc_db->md_root;
5021 if (root == P_INVALID) { /* Tree is empty. */
5022 DPUTS("tree is empty");
5023 return MDB_NOTFOUND;
5027 mdb_cassert(mc, root > 1);
5028 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5029 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
5035 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5036 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5038 if (flags & MDB_PS_MODIFY) {
5039 if ((rc = mdb_page_touch(mc)))
5043 if (flags & MDB_PS_ROOTONLY)
5046 return mdb_page_search_root(mc, key, flags);
5050 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5052 MDB_txn *txn = mc->mc_txn;
5053 pgno_t pg = mp->mp_pgno;
5054 unsigned x = 0, ovpages = mp->mp_pages;
5055 MDB_env *env = txn->mt_env;
5056 MDB_IDL sl = txn->mt_spill_pgs;
5057 MDB_ID pn = pg << 1;
5060 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5061 /* If the page is dirty or on the spill list we just acquired it,
5062 * so we should give it back to our current free list, if any.
5063 * Otherwise put it onto the list of pages we freed in this txn.
5065 * Won't create me_pghead: me_pglast must be inited along with it.
5066 * Unsupported in nested txns: They would need to hide the page
5067 * range in ancestor txns' dirty and spilled lists.
5069 if (env->me_pghead &&
5071 ((mp->mp_flags & P_DIRTY) ||
5072 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5076 MDB_ID2 *dl, ix, iy;
5077 rc = mdb_midl_need(&env->me_pghead, ovpages);
5080 if (!(mp->mp_flags & P_DIRTY)) {
5081 /* This page is no longer spilled */
5088 /* Remove from dirty list */
5089 dl = txn->mt_u.dirty_list;
5091 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5097 mdb_cassert(mc, x > 1);
5099 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5100 txn->mt_flags |= MDB_TXN_ERROR;
5101 return MDB_CORRUPTED;
5104 if (!(env->me_flags & MDB_WRITEMAP))
5105 mdb_dpage_free(env, mp);
5107 /* Insert in me_pghead */
5108 mop = env->me_pghead;
5109 j = mop[0] + ovpages;
5110 for (i = mop[0]; i && mop[i] < pg; i--)
5116 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5120 mc->mc_db->md_overflow_pages -= ovpages;
5124 /** Return the data associated with a given node.
5125 * @param[in] txn The transaction for this operation.
5126 * @param[in] leaf The node being read.
5127 * @param[out] data Updated to point to the node's data.
5128 * @return 0 on success, non-zero on failure.
5131 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5133 MDB_page *omp; /* overflow page */
5137 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5138 data->mv_size = NODEDSZ(leaf);
5139 data->mv_data = NODEDATA(leaf);
5143 /* Read overflow data.
5145 data->mv_size = NODEDSZ(leaf);
5146 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5147 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5148 DPRINTF(("read overflow page %"Z"u failed", pgno));
5151 data->mv_data = METADATA(omp);
5157 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5158 MDB_val *key, MDB_val *data)
5165 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5167 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
5170 if (txn->mt_flags & MDB_TXN_ERROR)
5173 mdb_cursor_init(&mc, txn, dbi, &mx);
5174 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5177 /** Find a sibling for a page.
5178 * Replaces the page at the top of the cursor's stack with the
5179 * specified sibling, if one exists.
5180 * @param[in] mc The cursor for this operation.
5181 * @param[in] move_right Non-zero if the right sibling is requested,
5182 * otherwise the left sibling.
5183 * @return 0 on success, non-zero on failure.
5186 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5192 if (mc->mc_snum < 2) {
5193 return MDB_NOTFOUND; /* root has no siblings */
5197 DPRINTF(("parent page is page %"Z"u, index %u",
5198 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5200 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5201 : (mc->mc_ki[mc->mc_top] == 0)) {
5202 DPRINTF(("no more keys left, moving to %s sibling",
5203 move_right ? "right" : "left"));
5204 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5205 /* undo cursor_pop before returning */
5212 mc->mc_ki[mc->mc_top]++;
5214 mc->mc_ki[mc->mc_top]--;
5215 DPRINTF(("just moving to %s index key %u",
5216 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5218 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5220 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5221 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5222 /* mc will be inconsistent if caller does mc_snum++ as above */
5223 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5227 mdb_cursor_push(mc, mp);
5229 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5234 /** Move the cursor to the next data item. */
5236 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5242 if (mc->mc_flags & C_EOF) {
5243 return MDB_NOTFOUND;
5246 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5248 mp = mc->mc_pg[mc->mc_top];
5250 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5251 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5252 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5253 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5254 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5255 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5256 if (rc == MDB_SUCCESS)
5257 MDB_GET_KEY(leaf, key);
5262 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5263 if (op == MDB_NEXT_DUP)
5264 return MDB_NOTFOUND;
5268 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5269 mdb_dbg_pgno(mp), (void *) mc));
5270 if (mc->mc_flags & C_DEL)
5273 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5274 DPUTS("=====> move to next sibling page");
5275 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5276 mc->mc_flags |= C_EOF;
5279 mp = mc->mc_pg[mc->mc_top];
5280 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5282 mc->mc_ki[mc->mc_top]++;
5285 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5286 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5289 key->mv_size = mc->mc_db->md_pad;
5290 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5294 mdb_cassert(mc, IS_LEAF(mp));
5295 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5297 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5298 mdb_xcursor_init1(mc, leaf);
5301 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5304 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5305 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5306 if (rc != MDB_SUCCESS)
5311 MDB_GET_KEY(leaf, key);
5315 /** Move the cursor to the previous data item. */
5317 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5323 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5325 mp = mc->mc_pg[mc->mc_top];
5327 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5328 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5329 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5330 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5331 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5332 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5333 if (rc == MDB_SUCCESS)
5334 MDB_GET_KEY(leaf, key);
5338 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5339 if (op == MDB_PREV_DUP)
5340 return MDB_NOTFOUND;
5345 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5346 mdb_dbg_pgno(mp), (void *) mc));
5348 if (mc->mc_ki[mc->mc_top] == 0) {
5349 DPUTS("=====> move to prev sibling page");
5350 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5353 mp = mc->mc_pg[mc->mc_top];
5354 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5355 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5357 mc->mc_ki[mc->mc_top]--;
5359 mc->mc_flags &= ~C_EOF;
5361 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5362 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5365 key->mv_size = mc->mc_db->md_pad;
5366 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5370 mdb_cassert(mc, IS_LEAF(mp));
5371 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5373 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5374 mdb_xcursor_init1(mc, leaf);
5377 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5380 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5381 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5382 if (rc != MDB_SUCCESS)
5387 MDB_GET_KEY(leaf, key);
5391 /** Set the cursor on a specific data item. */
5393 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5394 MDB_cursor_op op, int *exactp)
5398 MDB_node *leaf = NULL;
5401 if (key->mv_size == 0)
5402 return MDB_BAD_VALSIZE;
5405 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5407 /* See if we're already on the right page */
5408 if (mc->mc_flags & C_INITIALIZED) {
5411 mp = mc->mc_pg[mc->mc_top];
5413 mc->mc_ki[mc->mc_top] = 0;
5414 return MDB_NOTFOUND;
5416 if (mp->mp_flags & P_LEAF2) {
5417 nodekey.mv_size = mc->mc_db->md_pad;
5418 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5420 leaf = NODEPTR(mp, 0);
5421 MDB_GET_KEY2(leaf, nodekey);
5423 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5425 /* Probably happens rarely, but first node on the page
5426 * was the one we wanted.
5428 mc->mc_ki[mc->mc_top] = 0;
5435 unsigned int nkeys = NUMKEYS(mp);
5437 if (mp->mp_flags & P_LEAF2) {
5438 nodekey.mv_data = LEAF2KEY(mp,
5439 nkeys-1, nodekey.mv_size);
5441 leaf = NODEPTR(mp, nkeys-1);
5442 MDB_GET_KEY2(leaf, nodekey);
5444 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5446 /* last node was the one we wanted */
5447 mc->mc_ki[mc->mc_top] = nkeys-1;
5453 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5454 /* This is definitely the right page, skip search_page */
5455 if (mp->mp_flags & P_LEAF2) {
5456 nodekey.mv_data = LEAF2KEY(mp,
5457 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5459 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5460 MDB_GET_KEY2(leaf, nodekey);
5462 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5464 /* current node was the one we wanted */
5474 /* If any parents have right-sibs, search.
5475 * Otherwise, there's nothing further.
5477 for (i=0; i<mc->mc_top; i++)
5479 NUMKEYS(mc->mc_pg[i])-1)
5481 if (i == mc->mc_top) {
5482 /* There are no other pages */
5483 mc->mc_ki[mc->mc_top] = nkeys;
5484 return MDB_NOTFOUND;
5488 /* There are no other pages */
5489 mc->mc_ki[mc->mc_top] = 0;
5490 if (op == MDB_SET_RANGE && !exactp) {
5494 return MDB_NOTFOUND;
5498 rc = mdb_page_search(mc, key, 0);
5499 if (rc != MDB_SUCCESS)
5502 mp = mc->mc_pg[mc->mc_top];
5503 mdb_cassert(mc, IS_LEAF(mp));
5506 leaf = mdb_node_search(mc, key, exactp);
5507 if (exactp != NULL && !*exactp) {
5508 /* MDB_SET specified and not an exact match. */
5509 return MDB_NOTFOUND;
5513 DPUTS("===> inexact leaf not found, goto sibling");
5514 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5515 return rc; /* no entries matched */
5516 mp = mc->mc_pg[mc->mc_top];
5517 mdb_cassert(mc, IS_LEAF(mp));
5518 leaf = NODEPTR(mp, 0);
5522 mc->mc_flags |= C_INITIALIZED;
5523 mc->mc_flags &= ~C_EOF;
5526 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5527 key->mv_size = mc->mc_db->md_pad;
5528 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5533 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5534 mdb_xcursor_init1(mc, leaf);
5537 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5538 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5539 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5542 if (op == MDB_GET_BOTH) {
5548 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5549 if (rc != MDB_SUCCESS)
5552 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5554 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5556 rc = mc->mc_dbx->md_dcmp(data, &d2);
5558 if (op == MDB_GET_BOTH || rc > 0)
5559 return MDB_NOTFOUND;
5566 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5567 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5572 /* The key already matches in all other cases */
5573 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5574 MDB_GET_KEY(leaf, key);
5575 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5580 /** Move the cursor to the first item in the database. */
5582 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5588 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5590 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5591 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5592 if (rc != MDB_SUCCESS)
5595 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5597 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5598 mc->mc_flags |= C_INITIALIZED;
5599 mc->mc_flags &= ~C_EOF;
5601 mc->mc_ki[mc->mc_top] = 0;
5603 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5604 key->mv_size = mc->mc_db->md_pad;
5605 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5610 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5611 mdb_xcursor_init1(mc, leaf);
5612 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5616 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5620 MDB_GET_KEY(leaf, key);
5624 /** Move the cursor to the last item in the database. */
5626 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5632 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5634 if (!(mc->mc_flags & C_EOF)) {
5636 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5637 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5638 if (rc != MDB_SUCCESS)
5641 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5644 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5645 mc->mc_flags |= C_INITIALIZED|C_EOF;
5646 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5648 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5649 key->mv_size = mc->mc_db->md_pad;
5650 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5655 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5656 mdb_xcursor_init1(mc, leaf);
5657 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5661 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5666 MDB_GET_KEY(leaf, key);
5671 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5676 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5681 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5685 case MDB_GET_CURRENT:
5686 if (!(mc->mc_flags & C_INITIALIZED)) {
5689 MDB_page *mp = mc->mc_pg[mc->mc_top];
5690 int nkeys = NUMKEYS(mp);
5691 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5692 mc->mc_ki[mc->mc_top] = nkeys;
5698 key->mv_size = mc->mc_db->md_pad;
5699 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5701 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5702 MDB_GET_KEY(leaf, key);
5704 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5705 if (mc->mc_flags & C_DEL)
5706 mdb_xcursor_init1(mc, leaf);
5707 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5709 rc = mdb_node_read(mc->mc_txn, leaf, data);
5716 case MDB_GET_BOTH_RANGE:
5721 if (mc->mc_xcursor == NULL) {
5722 rc = MDB_INCOMPATIBLE;
5732 rc = mdb_cursor_set(mc, key, data, op,
5733 op == MDB_SET_RANGE ? NULL : &exact);
5736 case MDB_GET_MULTIPLE:
5737 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5741 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5742 rc = MDB_INCOMPATIBLE;
5746 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5747 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5750 case MDB_NEXT_MULTIPLE:
5755 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5756 rc = MDB_INCOMPATIBLE;
5759 if (!(mc->mc_flags & C_INITIALIZED))
5760 rc = mdb_cursor_first(mc, key, data);
5762 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5763 if (rc == MDB_SUCCESS) {
5764 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5767 mx = &mc->mc_xcursor->mx_cursor;
5768 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5770 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5771 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5779 case MDB_NEXT_NODUP:
5780 if (!(mc->mc_flags & C_INITIALIZED))
5781 rc = mdb_cursor_first(mc, key, data);
5783 rc = mdb_cursor_next(mc, key, data, op);
5787 case MDB_PREV_NODUP:
5788 if (!(mc->mc_flags & C_INITIALIZED)) {
5789 rc = mdb_cursor_last(mc, key, data);
5792 mc->mc_flags |= C_INITIALIZED;
5793 mc->mc_ki[mc->mc_top]++;
5795 rc = mdb_cursor_prev(mc, key, data, op);
5798 rc = mdb_cursor_first(mc, key, data);
5801 mfunc = mdb_cursor_first;
5803 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5807 if (mc->mc_xcursor == NULL) {
5808 rc = MDB_INCOMPATIBLE;
5811 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5815 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
5818 rc = mdb_cursor_last(mc, key, data);
5821 mfunc = mdb_cursor_last;
5824 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
5829 if (mc->mc_flags & C_DEL)
5830 mc->mc_flags ^= C_DEL;
5835 /** Touch all the pages in the cursor stack. Set mc_top.
5836 * Makes sure all the pages are writable, before attempting a write operation.
5837 * @param[in] mc The cursor to operate on.
5840 mdb_cursor_touch(MDB_cursor *mc)
5842 int rc = MDB_SUCCESS;
5844 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5847 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5849 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5850 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5853 *mc->mc_dbflag |= DB_DIRTY;
5858 rc = mdb_page_touch(mc);
5859 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
5860 mc->mc_top = mc->mc_snum-1;
5865 /** Do not spill pages to disk if txn is getting full, may fail instead */
5866 #define MDB_NOSPILL 0x8000
5869 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5872 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5874 MDB_node *leaf = NULL;
5877 MDB_val xdata, *rdata, dkey, olddata;
5879 int do_sub = 0, insert_key, insert_data;
5880 unsigned int mcount = 0, dcount = 0, nospill;
5883 unsigned int nflags;
5886 if (mc == NULL || key == NULL)
5889 env = mc->mc_txn->mt_env;
5891 /* Check this first so counter will always be zero on any
5894 if (flags & MDB_MULTIPLE) {
5895 dcount = data[1].mv_size;
5896 data[1].mv_size = 0;
5897 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5898 return MDB_INCOMPATIBLE;
5901 nospill = flags & MDB_NOSPILL;
5902 flags &= ~MDB_NOSPILL;
5904 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
5905 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
5907 if (key->mv_size-1 >= ENV_MAXKEY(env))
5908 return MDB_BAD_VALSIZE;
5910 #if SIZE_MAX > MAXDATASIZE
5911 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
5912 return MDB_BAD_VALSIZE;
5914 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
5915 return MDB_BAD_VALSIZE;
5918 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
5919 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
5923 if (flags == MDB_CURRENT) {
5924 if (!(mc->mc_flags & C_INITIALIZED))
5927 } else if (mc->mc_db->md_root == P_INVALID) {
5928 /* new database, cursor has nothing to point to */
5931 mc->mc_flags &= ~C_INITIALIZED;
5936 if (flags & MDB_APPEND) {
5938 rc = mdb_cursor_last(mc, &k2, &d2);
5940 rc = mc->mc_dbx->md_cmp(key, &k2);
5943 mc->mc_ki[mc->mc_top]++;
5945 /* new key is <= last key */
5950 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5952 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5953 DPRINTF(("duplicate key [%s]", DKEY(key)));
5955 return MDB_KEYEXIST;
5957 if (rc && rc != MDB_NOTFOUND)
5961 if (mc->mc_flags & C_DEL)
5962 mc->mc_flags ^= C_DEL;
5964 /* Cursor is positioned, check for room in the dirty list */
5966 if (flags & MDB_MULTIPLE) {
5968 xdata.mv_size = data->mv_size * dcount;
5972 if ((rc2 = mdb_page_spill(mc, key, rdata)))
5976 if (rc == MDB_NO_ROOT) {
5978 /* new database, write a root leaf page */
5979 DPUTS("allocating new root leaf page");
5980 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
5983 mdb_cursor_push(mc, np);
5984 mc->mc_db->md_root = np->mp_pgno;
5985 mc->mc_db->md_depth++;
5986 *mc->mc_dbflag |= DB_DIRTY;
5987 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5989 np->mp_flags |= P_LEAF2;
5990 mc->mc_flags |= C_INITIALIZED;
5992 /* make sure all cursor pages are writable */
5993 rc2 = mdb_cursor_touch(mc);
5998 insert_key = insert_data = rc;
6000 /* The key does not exist */
6001 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6002 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6003 LEAFSIZE(key, data) > env->me_nodemax)
6005 /* Too big for a node, insert in sub-DB. Set up an empty
6006 * "old sub-page" for prep_subDB to expand to a full page.
6008 fp_flags = P_LEAF|P_DIRTY;
6010 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6011 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6012 olddata.mv_size = PAGEHDRSZ;
6016 /* there's only a key anyway, so this is a no-op */
6017 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6019 unsigned int ksize = mc->mc_db->md_pad;
6020 if (key->mv_size != ksize)
6021 return MDB_BAD_VALSIZE;
6022 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6023 memcpy(ptr, key->mv_data, ksize);
6028 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6029 olddata.mv_size = NODEDSZ(leaf);
6030 olddata.mv_data = NODEDATA(leaf);
6033 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6034 /* Prepare (sub-)page/sub-DB to accept the new item,
6035 * if needed. fp: old sub-page or a header faking
6036 * it. mp: new (sub-)page. offset: growth in page
6037 * size. xdata: node data with new page or DB.
6039 unsigned i, offset = 0;
6040 mp = fp = xdata.mv_data = env->me_pbuf;
6041 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6043 /* Was a single item before, must convert now */
6044 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6045 /* Just overwrite the current item */
6046 if (flags == MDB_CURRENT)
6049 #if UINT_MAX < SIZE_MAX
6050 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6051 mc->mc_dbx->md_dcmp = mdb_cmp_clong;
6053 /* does data match? */
6054 if (!mc->mc_dbx->md_dcmp(data, &olddata)) {
6055 if (flags & MDB_NODUPDATA)
6056 return MDB_KEYEXIST;
6061 /* Back up original data item */
6062 dkey.mv_size = olddata.mv_size;
6063 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6065 /* Make sub-page header for the dup items, with dummy body */
6066 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6067 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6068 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6069 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6070 fp->mp_flags |= P_LEAF2;
6071 fp->mp_pad = data->mv_size;
6072 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6074 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6075 (dkey.mv_size & 1) + (data->mv_size & 1);
6077 fp->mp_upper = xdata.mv_size - PAGEBASE;
6078 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6079 } else if (leaf->mn_flags & F_SUBDATA) {
6080 /* Data is on sub-DB, just store it */
6081 flags |= F_DUPDATA|F_SUBDATA;
6084 /* Data is on sub-page */
6085 fp = olddata.mv_data;
6088 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6089 offset = EVEN(NODESIZE + sizeof(indx_t) +
6093 offset = fp->mp_pad;
6094 if (SIZELEFT(fp) < offset) {
6095 offset *= 4; /* space for 4 more */
6098 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6100 fp->mp_flags |= P_DIRTY;
6101 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6102 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6106 xdata.mv_size = olddata.mv_size + offset;
6109 fp_flags = fp->mp_flags;
6110 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6111 /* Too big for a sub-page, convert to sub-DB */
6112 fp_flags &= ~P_SUBP;
6114 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6115 fp_flags |= P_LEAF2;
6116 dummy.md_pad = fp->mp_pad;
6117 dummy.md_flags = MDB_DUPFIXED;
6118 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6119 dummy.md_flags |= MDB_INTEGERKEY;
6125 dummy.md_branch_pages = 0;
6126 dummy.md_leaf_pages = 1;
6127 dummy.md_overflow_pages = 0;
6128 dummy.md_entries = NUMKEYS(fp);
6129 xdata.mv_size = sizeof(MDB_db);
6130 xdata.mv_data = &dummy;
6131 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6133 offset = env->me_psize - olddata.mv_size;
6134 flags |= F_DUPDATA|F_SUBDATA;
6135 dummy.md_root = mp->mp_pgno;
6138 mp->mp_flags = fp_flags | P_DIRTY;
6139 mp->mp_pad = fp->mp_pad;
6140 mp->mp_lower = fp->mp_lower;
6141 mp->mp_upper = fp->mp_upper + offset;
6142 if (fp_flags & P_LEAF2) {
6143 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6145 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6146 olddata.mv_size - fp->mp_upper - PAGEBASE);
6147 for (i=0; i<NUMKEYS(fp); i++)
6148 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6156 mdb_node_del(mc, 0);
6160 /* overflow page overwrites need special handling */
6161 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6164 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6166 memcpy(&pg, olddata.mv_data, sizeof(pg));
6167 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6169 ovpages = omp->mp_pages;
6171 /* Is the ov page large enough? */
6172 if (ovpages >= dpages) {
6173 if (!(omp->mp_flags & P_DIRTY) &&
6174 (level || (env->me_flags & MDB_WRITEMAP)))
6176 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6179 level = 0; /* dirty in this txn or clean */
6182 if (omp->mp_flags & P_DIRTY) {
6183 /* yes, overwrite it. Note in this case we don't
6184 * bother to try shrinking the page if the new data
6185 * is smaller than the overflow threshold.
6188 /* It is writable only in a parent txn */
6189 size_t sz = (size_t) env->me_psize * ovpages, off;
6190 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6196 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6197 mdb_cassert(mc, rc2 == 0);
6198 if (!(flags & MDB_RESERVE)) {
6199 /* Copy end of page, adjusting alignment so
6200 * compiler may copy words instead of bytes.
6202 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6203 memcpy((size_t *)((char *)np + off),
6204 (size_t *)((char *)omp + off), sz - off);
6207 memcpy(np, omp, sz); /* Copy beginning of page */
6210 SETDSZ(leaf, data->mv_size);
6211 if (F_ISSET(flags, MDB_RESERVE))
6212 data->mv_data = METADATA(omp);
6214 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6218 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6220 } else if (data->mv_size == olddata.mv_size) {
6221 /* same size, just replace it. Note that we could
6222 * also reuse this node if the new data is smaller,
6223 * but instead we opt to shrink the node in that case.
6225 if (F_ISSET(flags, MDB_RESERVE))
6226 data->mv_data = olddata.mv_data;
6227 else if (!(mc->mc_flags & C_SUB))
6228 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6230 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6233 mdb_node_del(mc, 0);
6239 nflags = flags & NODE_ADD_FLAGS;
6240 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6241 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6242 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6243 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6245 nflags |= MDB_SPLIT_REPLACE;
6246 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6248 /* There is room already in this leaf page. */
6249 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6250 if (rc == 0 && insert_key) {
6251 /* Adjust other cursors pointing to mp */
6252 MDB_cursor *m2, *m3;
6253 MDB_dbi dbi = mc->mc_dbi;
6254 unsigned i = mc->mc_top;
6255 MDB_page *mp = mc->mc_pg[i];
6257 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6258 if (mc->mc_flags & C_SUB)
6259 m3 = &m2->mc_xcursor->mx_cursor;
6262 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6263 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6270 if (rc == MDB_SUCCESS) {
6271 /* Now store the actual data in the child DB. Note that we're
6272 * storing the user data in the keys field, so there are strict
6273 * size limits on dupdata. The actual data fields of the child
6274 * DB are all zero size.
6282 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6283 if (flags & MDB_CURRENT) {
6284 xflags = MDB_CURRENT|MDB_NOSPILL;
6286 mdb_xcursor_init1(mc, leaf);
6287 xflags = (flags & MDB_NODUPDATA) ?
6288 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6290 /* converted, write the original data first */
6292 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6296 /* Adjust other cursors pointing to mp */
6298 unsigned i = mc->mc_top;
6299 MDB_page *mp = mc->mc_pg[i];
6301 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6302 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6303 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6304 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6305 mdb_xcursor_init1(m2, leaf);
6309 /* we've done our job */
6312 ecount = mc->mc_xcursor->mx_db.md_entries;
6313 if (flags & MDB_APPENDDUP)
6314 xflags |= MDB_APPEND;
6315 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6316 if (flags & F_SUBDATA) {
6317 void *db = NODEDATA(leaf);
6318 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6320 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6322 /* Increment count unless we just replaced an existing item. */
6324 mc->mc_db->md_entries++;
6326 /* Invalidate txn if we created an empty sub-DB */
6329 /* If we succeeded and the key didn't exist before,
6330 * make sure the cursor is marked valid.
6332 mc->mc_flags |= C_INITIALIZED;
6334 if (flags & MDB_MULTIPLE) {
6337 /* let caller know how many succeeded, if any */
6338 data[1].mv_size = mcount;
6339 if (mcount < dcount) {
6340 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6341 insert_key = insert_data = 0;
6348 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6351 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6356 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6362 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6363 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6365 if (!(mc->mc_flags & C_INITIALIZED))
6368 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6369 return MDB_NOTFOUND;
6371 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6374 rc = mdb_cursor_touch(mc);
6378 mp = mc->mc_pg[mc->mc_top];
6381 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6383 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6384 if (flags & MDB_NODUPDATA) {
6385 /* mdb_cursor_del0() will subtract the final entry */
6386 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6388 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6389 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6391 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6394 /* If sub-DB still has entries, we're done */
6395 if (mc->mc_xcursor->mx_db.md_entries) {
6396 if (leaf->mn_flags & F_SUBDATA) {
6397 /* update subDB info */
6398 void *db = NODEDATA(leaf);
6399 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6402 /* shrink fake page */
6403 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6404 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6405 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6406 /* fix other sub-DB cursors pointed at this fake page */
6407 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6408 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6409 if (m2->mc_pg[mc->mc_top] == mp &&
6410 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6411 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6414 mc->mc_db->md_entries--;
6415 mc->mc_flags |= C_DEL;
6418 /* otherwise fall thru and delete the sub-DB */
6421 if (leaf->mn_flags & F_SUBDATA) {
6422 /* add all the child DB's pages to the free list */
6423 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6429 /* add overflow pages to free list */
6430 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6434 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6435 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6436 (rc = mdb_ovpage_free(mc, omp)))
6441 return mdb_cursor_del0(mc);
6444 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6448 /** Allocate and initialize new pages for a database.
6449 * @param[in] mc a cursor on the database being added to.
6450 * @param[in] flags flags defining what type of page is being allocated.
6451 * @param[in] num the number of pages to allocate. This is usually 1,
6452 * unless allocating overflow pages for a large record.
6453 * @param[out] mp Address of a page, or NULL on failure.
6454 * @return 0 on success, non-zero on failure.
6457 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6462 if ((rc = mdb_page_alloc(mc, num, &np)))
6464 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6465 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6466 np->mp_flags = flags | P_DIRTY;
6467 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
6468 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
6471 mc->mc_db->md_branch_pages++;
6472 else if (IS_LEAF(np))
6473 mc->mc_db->md_leaf_pages++;
6474 else if (IS_OVERFLOW(np)) {
6475 mc->mc_db->md_overflow_pages += num;
6483 /** Calculate the size of a leaf node.
6484 * The size depends on the environment's page size; if a data item
6485 * is too large it will be put onto an overflow page and the node
6486 * size will only include the key and not the data. Sizes are always
6487 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6488 * of the #MDB_node headers.
6489 * @param[in] env The environment handle.
6490 * @param[in] key The key for the node.
6491 * @param[in] data The data for the node.
6492 * @return The number of bytes needed to store the node.
6495 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6499 sz = LEAFSIZE(key, data);
6500 if (sz > env->me_nodemax) {
6501 /* put on overflow page */
6502 sz -= data->mv_size - sizeof(pgno_t);
6505 return EVEN(sz + sizeof(indx_t));
6508 /** Calculate the size of a branch node.
6509 * The size should depend on the environment's page size but since
6510 * we currently don't support spilling large keys onto overflow
6511 * pages, it's simply the size of the #MDB_node header plus the
6512 * size of the key. Sizes are always rounded up to an even number
6513 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6514 * @param[in] env The environment handle.
6515 * @param[in] key The key for the node.
6516 * @return The number of bytes needed to store the node.
6519 mdb_branch_size(MDB_env *env, MDB_val *key)
6524 if (sz > env->me_nodemax) {
6525 /* put on overflow page */
6526 /* not implemented */
6527 /* sz -= key->size - sizeof(pgno_t); */
6530 return sz + sizeof(indx_t);
6533 /** Add a node to the page pointed to by the cursor.
6534 * @param[in] mc The cursor for this operation.
6535 * @param[in] indx The index on the page where the new node should be added.
6536 * @param[in] key The key for the new node.
6537 * @param[in] data The data for the new node, if any.
6538 * @param[in] pgno The page number, if adding a branch node.
6539 * @param[in] flags Flags for the node.
6540 * @return 0 on success, non-zero on failure. Possible errors are:
6542 * <li>ENOMEM - failed to allocate overflow pages for the node.
6543 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6544 * should never happen since all callers already calculate the
6545 * page's free space before calling this function.
6549 mdb_node_add(MDB_cursor *mc, indx_t indx,
6550 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6553 size_t node_size = NODESIZE;
6557 MDB_page *mp = mc->mc_pg[mc->mc_top];
6558 MDB_page *ofp = NULL; /* overflow page */
6561 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
6563 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6564 IS_LEAF(mp) ? "leaf" : "branch",
6565 IS_SUBP(mp) ? "sub-" : "",
6566 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
6567 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6570 /* Move higher keys up one slot. */
6571 int ksize = mc->mc_db->md_pad, dif;
6572 char *ptr = LEAF2KEY(mp, indx, ksize);
6573 dif = NUMKEYS(mp) - indx;
6575 memmove(ptr+ksize, ptr, dif*ksize);
6576 /* insert new key */
6577 memcpy(ptr, key->mv_data, ksize);
6579 /* Just using these for counting */
6580 mp->mp_lower += sizeof(indx_t);
6581 mp->mp_upper -= ksize - sizeof(indx_t);
6585 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6587 node_size += key->mv_size;
6589 mdb_cassert(mc, data);
6590 if (F_ISSET(flags, F_BIGDATA)) {
6591 /* Data already on overflow page. */
6592 node_size += sizeof(pgno_t);
6593 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
6594 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6596 /* Put data on overflow page. */
6597 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6598 data->mv_size, node_size+data->mv_size));
6599 node_size = EVEN(node_size + sizeof(pgno_t));
6600 if ((ssize_t)node_size > room)
6602 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6604 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6608 node_size += data->mv_size;
6611 node_size = EVEN(node_size);
6612 if ((ssize_t)node_size > room)
6616 /* Move higher pointers up one slot. */
6617 for (i = NUMKEYS(mp); i > indx; i--)
6618 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6620 /* Adjust free space offsets. */
6621 ofs = mp->mp_upper - node_size;
6622 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
6623 mp->mp_ptrs[indx] = ofs;
6625 mp->mp_lower += sizeof(indx_t);
6627 /* Write the node data. */
6628 node = NODEPTR(mp, indx);
6629 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6630 node->mn_flags = flags;
6632 SETDSZ(node,data->mv_size);
6637 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6640 mdb_cassert(mc, key);
6642 if (F_ISSET(flags, F_BIGDATA))
6643 memcpy(node->mn_data + key->mv_size, data->mv_data,
6645 else if (F_ISSET(flags, MDB_RESERVE))
6646 data->mv_data = node->mn_data + key->mv_size;
6648 memcpy(node->mn_data + key->mv_size, data->mv_data,
6651 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6653 if (F_ISSET(flags, MDB_RESERVE))
6654 data->mv_data = METADATA(ofp);
6656 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6663 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6664 mdb_dbg_pgno(mp), NUMKEYS(mp)));
6665 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6666 DPRINTF(("node size = %"Z"u", node_size));
6667 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6668 return MDB_PAGE_FULL;
6671 /** Delete the specified node from a page.
6672 * @param[in] mc Cursor pointing to the node to delete.
6673 * @param[in] ksize The size of a node. Only used if the page is
6674 * part of a #MDB_DUPFIXED database.
6677 mdb_node_del(MDB_cursor *mc, int ksize)
6679 MDB_page *mp = mc->mc_pg[mc->mc_top];
6680 indx_t indx = mc->mc_ki[mc->mc_top];
6682 indx_t i, j, numkeys, ptr;
6686 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6687 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
6688 numkeys = NUMKEYS(mp);
6689 mdb_cassert(mc, indx < numkeys);
6692 int x = numkeys - 1 - indx;
6693 base = LEAF2KEY(mp, indx, ksize);
6695 memmove(base, base + ksize, x * ksize);
6696 mp->mp_lower -= sizeof(indx_t);
6697 mp->mp_upper += ksize - sizeof(indx_t);
6701 node = NODEPTR(mp, indx);
6702 sz = NODESIZE + node->mn_ksize;
6704 if (F_ISSET(node->mn_flags, F_BIGDATA))
6705 sz += sizeof(pgno_t);
6707 sz += NODEDSZ(node);
6711 ptr = mp->mp_ptrs[indx];
6712 for (i = j = 0; i < numkeys; i++) {
6714 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6715 if (mp->mp_ptrs[i] < ptr)
6716 mp->mp_ptrs[j] += sz;
6721 base = (char *)mp + mp->mp_upper + PAGEBASE;
6722 memmove(base + sz, base, ptr - mp->mp_upper);
6724 mp->mp_lower -= sizeof(indx_t);
6728 /** Compact the main page after deleting a node on a subpage.
6729 * @param[in] mp The main page to operate on.
6730 * @param[in] indx The index of the subpage on the main page.
6733 mdb_node_shrink(MDB_page *mp, indx_t indx)
6739 indx_t i, numkeys, ptr;
6741 node = NODEPTR(mp, indx);
6742 sp = (MDB_page *)NODEDATA(node);
6743 delta = SIZELEFT(sp);
6744 xp = (MDB_page *)((char *)sp + delta);
6746 /* shift subpage upward */
6748 nsize = NUMKEYS(sp) * sp->mp_pad;
6750 return; /* do not make the node uneven-sized */
6751 memmove(METADATA(xp), METADATA(sp), nsize);
6754 numkeys = NUMKEYS(sp);
6755 for (i=numkeys-1; i>=0; i--)
6756 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6758 xp->mp_upper = sp->mp_lower;
6759 xp->mp_lower = sp->mp_lower;
6760 xp->mp_flags = sp->mp_flags;
6761 xp->mp_pad = sp->mp_pad;
6762 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6764 nsize = NODEDSZ(node) - delta;
6765 SETDSZ(node, nsize);
6767 /* shift lower nodes upward */
6768 ptr = mp->mp_ptrs[indx];
6769 numkeys = NUMKEYS(mp);
6770 for (i = 0; i < numkeys; i++) {
6771 if (mp->mp_ptrs[i] <= ptr)
6772 mp->mp_ptrs[i] += delta;
6775 base = (char *)mp + mp->mp_upper + PAGEBASE;
6776 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6777 mp->mp_upper += delta;
6780 /** Initial setup of a sorted-dups cursor.
6781 * Sorted duplicates are implemented as a sub-database for the given key.
6782 * The duplicate data items are actually keys of the sub-database.
6783 * Operations on the duplicate data items are performed using a sub-cursor
6784 * initialized when the sub-database is first accessed. This function does
6785 * the preliminary setup of the sub-cursor, filling in the fields that
6786 * depend only on the parent DB.
6787 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6790 mdb_xcursor_init0(MDB_cursor *mc)
6792 MDB_xcursor *mx = mc->mc_xcursor;
6794 mx->mx_cursor.mc_xcursor = NULL;
6795 mx->mx_cursor.mc_txn = mc->mc_txn;
6796 mx->mx_cursor.mc_db = &mx->mx_db;
6797 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6798 mx->mx_cursor.mc_dbi = mc->mc_dbi;
6799 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6800 mx->mx_cursor.mc_snum = 0;
6801 mx->mx_cursor.mc_top = 0;
6802 mx->mx_cursor.mc_flags = C_SUB;
6803 mx->mx_dbx.md_name.mv_size = 0;
6804 mx->mx_dbx.md_name.mv_data = NULL;
6805 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6806 mx->mx_dbx.md_dcmp = NULL;
6807 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6810 /** Final setup of a sorted-dups cursor.
6811 * Sets up the fields that depend on the data from the main cursor.
6812 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6813 * @param[in] node The data containing the #MDB_db record for the
6814 * sorted-dup database.
6817 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6819 MDB_xcursor *mx = mc->mc_xcursor;
6821 if (node->mn_flags & F_SUBDATA) {
6822 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6823 mx->mx_cursor.mc_pg[0] = 0;
6824 mx->mx_cursor.mc_snum = 0;
6825 mx->mx_cursor.mc_top = 0;
6826 mx->mx_cursor.mc_flags = C_SUB;
6828 MDB_page *fp = NODEDATA(node);
6829 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6830 mx->mx_db.md_flags = 0;
6831 mx->mx_db.md_depth = 1;
6832 mx->mx_db.md_branch_pages = 0;
6833 mx->mx_db.md_leaf_pages = 1;
6834 mx->mx_db.md_overflow_pages = 0;
6835 mx->mx_db.md_entries = NUMKEYS(fp);
6836 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6837 mx->mx_cursor.mc_snum = 1;
6838 mx->mx_cursor.mc_top = 0;
6839 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6840 mx->mx_cursor.mc_pg[0] = fp;
6841 mx->mx_cursor.mc_ki[0] = 0;
6842 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6843 mx->mx_db.md_flags = MDB_DUPFIXED;
6844 mx->mx_db.md_pad = fp->mp_pad;
6845 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6846 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6849 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
6850 mx->mx_db.md_root));
6851 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
6852 #if UINT_MAX < SIZE_MAX
6853 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6854 mx->mx_dbx.md_cmp = mdb_cmp_clong;
6858 /** Initialize a cursor for a given transaction and database. */
6860 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6863 mc->mc_backup = NULL;
6866 mc->mc_db = &txn->mt_dbs[dbi];
6867 mc->mc_dbx = &txn->mt_dbxs[dbi];
6868 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6873 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6874 mdb_tassert(txn, mx != NULL);
6875 mc->mc_xcursor = mx;
6876 mdb_xcursor_init0(mc);
6878 mc->mc_xcursor = NULL;
6880 if (*mc->mc_dbflag & DB_STALE) {
6881 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6886 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6889 size_t size = sizeof(MDB_cursor);
6891 if (!ret || !TXN_DBI_EXIST(txn, dbi))
6894 if (txn->mt_flags & MDB_TXN_ERROR)
6897 /* Allow read access to the freelist */
6898 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6901 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6902 size += sizeof(MDB_xcursor);
6904 if ((mc = malloc(size)) != NULL) {
6905 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6906 if (txn->mt_cursors) {
6907 mc->mc_next = txn->mt_cursors[dbi];
6908 txn->mt_cursors[dbi] = mc;
6909 mc->mc_flags |= C_UNTRACK;
6921 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6923 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi))
6926 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6929 if (txn->mt_flags & MDB_TXN_ERROR)
6932 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6936 /* Return the count of duplicate data items for the current key */
6938 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6942 if (mc == NULL || countp == NULL)
6945 if (mc->mc_xcursor == NULL)
6946 return MDB_INCOMPATIBLE;
6948 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
6951 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6952 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6955 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
6958 *countp = mc->mc_xcursor->mx_db.md_entries;
6964 mdb_cursor_close(MDB_cursor *mc)
6966 if (mc && !mc->mc_backup) {
6967 /* remove from txn, if tracked */
6968 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
6969 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
6970 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
6972 *prev = mc->mc_next;
6979 mdb_cursor_txn(MDB_cursor *mc)
6981 if (!mc) return NULL;
6986 mdb_cursor_dbi(MDB_cursor *mc)
6991 /** Replace the key for a branch node with a new key.
6992 * @param[in] mc Cursor pointing to the node to operate on.
6993 * @param[in] key The new key to use.
6994 * @return 0 on success, non-zero on failure.
6997 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7003 int delta, ksize, oksize;
7004 indx_t ptr, i, numkeys, indx;
7007 indx = mc->mc_ki[mc->mc_top];
7008 mp = mc->mc_pg[mc->mc_top];
7009 node = NODEPTR(mp, indx);
7010 ptr = mp->mp_ptrs[indx];
7014 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7015 k2.mv_data = NODEKEY(node);
7016 k2.mv_size = node->mn_ksize;
7017 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7019 mdb_dkey(&k2, kbuf2),
7025 /* Sizes must be 2-byte aligned. */
7026 ksize = EVEN(key->mv_size);
7027 oksize = EVEN(node->mn_ksize);
7028 delta = ksize - oksize;
7030 /* Shift node contents if EVEN(key length) changed. */
7032 if (delta > 0 && SIZELEFT(mp) < delta) {
7034 /* not enough space left, do a delete and split */
7035 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7036 pgno = NODEPGNO(node);
7037 mdb_node_del(mc, 0);
7038 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7041 numkeys = NUMKEYS(mp);
7042 for (i = 0; i < numkeys; i++) {
7043 if (mp->mp_ptrs[i] <= ptr)
7044 mp->mp_ptrs[i] -= delta;
7047 base = (char *)mp + mp->mp_upper + PAGEBASE;
7048 len = ptr - mp->mp_upper + NODESIZE;
7049 memmove(base - delta, base, len);
7050 mp->mp_upper -= delta;
7052 node = NODEPTR(mp, indx);
7055 /* But even if no shift was needed, update ksize */
7056 if (node->mn_ksize != key->mv_size)
7057 node->mn_ksize = key->mv_size;
7060 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7066 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7068 /** Move a node from csrc to cdst.
7071 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
7078 unsigned short flags;
7082 /* Mark src and dst as dirty. */
7083 if ((rc = mdb_page_touch(csrc)) ||
7084 (rc = mdb_page_touch(cdst)))
7087 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7088 key.mv_size = csrc->mc_db->md_pad;
7089 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7091 data.mv_data = NULL;
7095 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7096 mdb_cassert(csrc, !((size_t)srcnode & 1));
7097 srcpg = NODEPGNO(srcnode);
7098 flags = srcnode->mn_flags;
7099 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7100 unsigned int snum = csrc->mc_snum;
7102 /* must find the lowest key below src */
7103 rc = mdb_page_search_lowest(csrc);
7106 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7107 key.mv_size = csrc->mc_db->md_pad;
7108 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7110 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7111 key.mv_size = NODEKSZ(s2);
7112 key.mv_data = NODEKEY(s2);
7114 csrc->mc_snum = snum--;
7115 csrc->mc_top = snum;
7117 key.mv_size = NODEKSZ(srcnode);
7118 key.mv_data = NODEKEY(srcnode);
7120 data.mv_size = NODEDSZ(srcnode);
7121 data.mv_data = NODEDATA(srcnode);
7123 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7124 unsigned int snum = cdst->mc_snum;
7127 /* must find the lowest key below dst */
7128 mdb_cursor_copy(cdst, &mn);
7129 rc = mdb_page_search_lowest(&mn);
7132 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7133 bkey.mv_size = mn.mc_db->md_pad;
7134 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7136 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7137 bkey.mv_size = NODEKSZ(s2);
7138 bkey.mv_data = NODEKEY(s2);
7140 mn.mc_snum = snum--;
7143 rc = mdb_update_key(&mn, &bkey);
7148 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7149 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7150 csrc->mc_ki[csrc->mc_top],
7152 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7153 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7155 /* Add the node to the destination page.
7157 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7158 if (rc != MDB_SUCCESS)
7161 /* Delete the node from the source page.
7163 mdb_node_del(csrc, key.mv_size);
7166 /* Adjust other cursors pointing to mp */
7167 MDB_cursor *m2, *m3;
7168 MDB_dbi dbi = csrc->mc_dbi;
7169 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
7171 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7172 if (csrc->mc_flags & C_SUB)
7173 m3 = &m2->mc_xcursor->mx_cursor;
7176 if (m3 == csrc) continue;
7177 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
7178 csrc->mc_ki[csrc->mc_top]) {
7179 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7180 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7185 /* Update the parent separators.
7187 if (csrc->mc_ki[csrc->mc_top] == 0) {
7188 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7189 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7190 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7192 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7193 key.mv_size = NODEKSZ(srcnode);
7194 key.mv_data = NODEKEY(srcnode);
7196 DPRINTF(("update separator for source page %"Z"u to [%s]",
7197 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7198 mdb_cursor_copy(csrc, &mn);
7201 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7204 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7206 indx_t ix = csrc->mc_ki[csrc->mc_top];
7207 nullkey.mv_size = 0;
7208 csrc->mc_ki[csrc->mc_top] = 0;
7209 rc = mdb_update_key(csrc, &nullkey);
7210 csrc->mc_ki[csrc->mc_top] = ix;
7211 mdb_cassert(csrc, rc == MDB_SUCCESS);
7215 if (cdst->mc_ki[cdst->mc_top] == 0) {
7216 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7217 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7218 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7220 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7221 key.mv_size = NODEKSZ(srcnode);
7222 key.mv_data = NODEKEY(srcnode);
7224 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7225 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7226 mdb_cursor_copy(cdst, &mn);
7229 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7232 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7234 indx_t ix = cdst->mc_ki[cdst->mc_top];
7235 nullkey.mv_size = 0;
7236 cdst->mc_ki[cdst->mc_top] = 0;
7237 rc = mdb_update_key(cdst, &nullkey);
7238 cdst->mc_ki[cdst->mc_top] = ix;
7239 mdb_cassert(csrc, rc == MDB_SUCCESS);
7246 /** Merge one page into another.
7247 * The nodes from the page pointed to by \b csrc will
7248 * be copied to the page pointed to by \b cdst and then
7249 * the \b csrc page will be freed.
7250 * @param[in] csrc Cursor pointing to the source page.
7251 * @param[in] cdst Cursor pointing to the destination page.
7252 * @return 0 on success, non-zero on failure.
7255 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7257 MDB_page *psrc, *pdst;
7264 psrc = csrc->mc_pg[csrc->mc_top];
7265 pdst = cdst->mc_pg[cdst->mc_top];
7267 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7269 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7270 mdb_cassert(csrc, cdst->mc_snum > 1);
7272 /* Mark dst as dirty. */
7273 if ((rc = mdb_page_touch(cdst)))
7276 /* Move all nodes from src to dst.
7278 j = nkeys = NUMKEYS(pdst);
7279 if (IS_LEAF2(psrc)) {
7280 key.mv_size = csrc->mc_db->md_pad;
7281 key.mv_data = METADATA(psrc);
7282 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7283 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7284 if (rc != MDB_SUCCESS)
7286 key.mv_data = (char *)key.mv_data + key.mv_size;
7289 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7290 srcnode = NODEPTR(psrc, i);
7291 if (i == 0 && IS_BRANCH(psrc)) {
7294 mdb_cursor_copy(csrc, &mn);
7295 /* must find the lowest key below src */
7296 rc = mdb_page_search_lowest(&mn);
7299 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7300 key.mv_size = mn.mc_db->md_pad;
7301 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7303 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7304 key.mv_size = NODEKSZ(s2);
7305 key.mv_data = NODEKEY(s2);
7308 key.mv_size = srcnode->mn_ksize;
7309 key.mv_data = NODEKEY(srcnode);
7312 data.mv_size = NODEDSZ(srcnode);
7313 data.mv_data = NODEDATA(srcnode);
7314 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7315 if (rc != MDB_SUCCESS)
7320 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7321 pdst->mp_pgno, NUMKEYS(pdst),
7322 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7324 /* Unlink the src page from parent and add to free list.
7327 mdb_node_del(csrc, 0);
7328 if (csrc->mc_ki[csrc->mc_top] == 0) {
7330 rc = mdb_update_key(csrc, &key);
7338 psrc = csrc->mc_pg[csrc->mc_top];
7339 /* If not operating on FreeDB, allow this page to be reused
7340 * in this txn. Otherwise just add to free list.
7342 rc = mdb_page_loose(csrc, psrc);
7346 csrc->mc_db->md_leaf_pages--;
7348 csrc->mc_db->md_branch_pages--;
7350 /* Adjust other cursors pointing to mp */
7351 MDB_cursor *m2, *m3;
7352 MDB_dbi dbi = csrc->mc_dbi;
7354 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7355 if (csrc->mc_flags & C_SUB)
7356 m3 = &m2->mc_xcursor->mx_cursor;
7359 if (m3 == csrc) continue;
7360 if (m3->mc_snum < csrc->mc_snum) continue;
7361 if (m3->mc_pg[csrc->mc_top] == psrc) {
7362 m3->mc_pg[csrc->mc_top] = pdst;
7363 m3->mc_ki[csrc->mc_top] += nkeys;
7368 unsigned int snum = cdst->mc_snum;
7369 uint16_t depth = cdst->mc_db->md_depth;
7370 mdb_cursor_pop(cdst);
7371 rc = mdb_rebalance(cdst);
7372 /* Did the tree shrink? */
7373 if (depth > cdst->mc_db->md_depth)
7375 cdst->mc_snum = snum;
7376 cdst->mc_top = snum-1;
7381 /** Copy the contents of a cursor.
7382 * @param[in] csrc The cursor to copy from.
7383 * @param[out] cdst The cursor to copy to.
7386 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7390 cdst->mc_txn = csrc->mc_txn;
7391 cdst->mc_dbi = csrc->mc_dbi;
7392 cdst->mc_db = csrc->mc_db;
7393 cdst->mc_dbx = csrc->mc_dbx;
7394 cdst->mc_snum = csrc->mc_snum;
7395 cdst->mc_top = csrc->mc_top;
7396 cdst->mc_flags = csrc->mc_flags;
7398 for (i=0; i<csrc->mc_snum; i++) {
7399 cdst->mc_pg[i] = csrc->mc_pg[i];
7400 cdst->mc_ki[i] = csrc->mc_ki[i];
7404 /** Rebalance the tree after a delete operation.
7405 * @param[in] mc Cursor pointing to the page where rebalancing
7407 * @return 0 on success, non-zero on failure.
7410 mdb_rebalance(MDB_cursor *mc)
7414 unsigned int ptop, minkeys;
7418 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7419 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7420 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7421 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7422 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7424 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7425 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7426 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7427 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7431 if (mc->mc_snum < 2) {
7432 MDB_page *mp = mc->mc_pg[0];
7434 DPUTS("Can't rebalance a subpage, ignoring");
7437 if (NUMKEYS(mp) == 0) {
7438 DPUTS("tree is completely empty");
7439 mc->mc_db->md_root = P_INVALID;
7440 mc->mc_db->md_depth = 0;
7441 mc->mc_db->md_leaf_pages = 0;
7442 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7445 /* Adjust cursors pointing to mp */
7448 mc->mc_flags &= ~C_INITIALIZED;
7450 MDB_cursor *m2, *m3;
7451 MDB_dbi dbi = mc->mc_dbi;
7453 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7454 if (mc->mc_flags & C_SUB)
7455 m3 = &m2->mc_xcursor->mx_cursor;
7458 if (m3->mc_snum < mc->mc_snum) continue;
7459 if (m3->mc_pg[0] == mp) {
7462 m3->mc_flags &= ~C_INITIALIZED;
7466 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7468 DPUTS("collapsing root page!");
7469 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7472 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7473 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7476 mc->mc_db->md_depth--;
7477 mc->mc_db->md_branch_pages--;
7478 mc->mc_ki[0] = mc->mc_ki[1];
7479 for (i = 1; i<mc->mc_db->md_depth; i++) {
7480 mc->mc_pg[i] = mc->mc_pg[i+1];
7481 mc->mc_ki[i] = mc->mc_ki[i+1];
7484 /* Adjust other cursors pointing to mp */
7485 MDB_cursor *m2, *m3;
7486 MDB_dbi dbi = mc->mc_dbi;
7488 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7489 if (mc->mc_flags & C_SUB)
7490 m3 = &m2->mc_xcursor->mx_cursor;
7493 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7494 if (m3->mc_pg[0] == mp) {
7497 for (i=0; i<m3->mc_snum; i++) {
7498 m3->mc_pg[i] = m3->mc_pg[i+1];
7499 m3->mc_ki[i] = m3->mc_ki[i+1];
7505 DPUTS("root page doesn't need rebalancing");
7509 /* The parent (branch page) must have at least 2 pointers,
7510 * otherwise the tree is invalid.
7512 ptop = mc->mc_top-1;
7513 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
7515 /* Leaf page fill factor is below the threshold.
7516 * Try to move keys from left or right neighbor, or
7517 * merge with a neighbor page.
7522 mdb_cursor_copy(mc, &mn);
7523 mn.mc_xcursor = NULL;
7525 oldki = mc->mc_ki[mc->mc_top];
7526 if (mc->mc_ki[ptop] == 0) {
7527 /* We're the leftmost leaf in our parent.
7529 DPUTS("reading right neighbor");
7531 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7532 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7535 mn.mc_ki[mn.mc_top] = 0;
7536 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7538 /* There is at least one neighbor to the left.
7540 DPUTS("reading left neighbor");
7542 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7543 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7546 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7547 mc->mc_ki[mc->mc_top] = 0;
7550 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7551 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7552 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7554 /* If the neighbor page is above threshold and has enough keys,
7555 * move one key from it. Otherwise we should try to merge them.
7556 * (A branch page must never have less than 2 keys.)
7558 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7559 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
7560 rc = mdb_node_move(&mn, mc);
7561 if (mc->mc_ki[ptop]) {
7565 if (mc->mc_ki[ptop] == 0) {
7566 rc = mdb_page_merge(&mn, mc);
7568 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
7569 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7570 rc = mdb_page_merge(mc, &mn);
7571 mdb_cursor_copy(&mn, mc);
7573 mc->mc_flags &= ~C_EOF;
7575 mc->mc_ki[mc->mc_top] = oldki;
7579 /** Complete a delete operation started by #mdb_cursor_del(). */
7581 mdb_cursor_del0(MDB_cursor *mc)
7588 ki = mc->mc_ki[mc->mc_top];
7589 mdb_node_del(mc, mc->mc_db->md_pad);
7590 mc->mc_db->md_entries--;
7591 rc = mdb_rebalance(mc);
7593 if (rc == MDB_SUCCESS) {
7594 MDB_cursor *m2, *m3;
7595 MDB_dbi dbi = mc->mc_dbi;
7597 mp = mc->mc_pg[mc->mc_top];
7598 nkeys = NUMKEYS(mp);
7600 /* if mc points past last node in page, find next sibling */
7601 if (mc->mc_ki[mc->mc_top] >= nkeys) {
7602 rc = mdb_cursor_sibling(mc, 1);
7603 if (rc == MDB_NOTFOUND) {
7604 mc->mc_flags |= C_EOF;
7609 /* Adjust other cursors pointing to mp */
7610 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
7611 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
7612 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7614 if (m3 == mc || m3->mc_snum < mc->mc_snum)
7616 if (m3->mc_pg[mc->mc_top] == mp) {
7617 if (m3->mc_ki[mc->mc_top] >= ki) {
7618 m3->mc_flags |= C_DEL;
7619 if (m3->mc_ki[mc->mc_top] > ki)
7620 m3->mc_ki[mc->mc_top]--;
7622 if (m3->mc_ki[mc->mc_top] >= nkeys) {
7623 rc = mdb_cursor_sibling(m3, 1);
7624 if (rc == MDB_NOTFOUND) {
7625 m3->mc_flags |= C_EOF;
7631 mc->mc_flags |= C_DEL;
7635 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7640 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7641 MDB_val *key, MDB_val *data)
7643 if (!key || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
7646 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7647 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7649 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7650 /* must ignore any data */
7654 return mdb_del0(txn, dbi, key, data, 0);
7658 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
7659 MDB_val *key, MDB_val *data, unsigned flags)
7664 MDB_val rdata, *xdata;
7668 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7670 mdb_cursor_init(&mc, txn, dbi, &mx);
7679 flags |= MDB_NODUPDATA;
7681 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7683 /* let mdb_page_split know about this cursor if needed:
7684 * delete will trigger a rebalance; if it needs to move
7685 * a node from one page to another, it will have to
7686 * update the parent's separator key(s). If the new sepkey
7687 * is larger than the current one, the parent page may
7688 * run out of space, triggering a split. We need this
7689 * cursor to be consistent until the end of the rebalance.
7691 mc.mc_flags |= C_UNTRACK;
7692 mc.mc_next = txn->mt_cursors[dbi];
7693 txn->mt_cursors[dbi] = &mc;
7694 rc = mdb_cursor_del(&mc, flags);
7695 txn->mt_cursors[dbi] = mc.mc_next;
7700 /** Split a page and insert a new node.
7701 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7702 * The cursor will be updated to point to the actual page and index where
7703 * the node got inserted after the split.
7704 * @param[in] newkey The key for the newly inserted node.
7705 * @param[in] newdata The data for the newly inserted node.
7706 * @param[in] newpgno The page number, if the new node is a branch node.
7707 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7708 * @return 0 on success, non-zero on failure.
7711 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7712 unsigned int nflags)
7715 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7718 int i, j, split_indx, nkeys, pmax;
7719 MDB_env *env = mc->mc_txn->mt_env;
7721 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7722 MDB_page *copy = NULL;
7723 MDB_page *mp, *rp, *pp;
7728 mp = mc->mc_pg[mc->mc_top];
7729 newindx = mc->mc_ki[mc->mc_top];
7730 nkeys = NUMKEYS(mp);
7732 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
7733 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7734 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
7736 /* Create a right sibling. */
7737 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7739 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7741 if (mc->mc_snum < 2) {
7742 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7744 /* shift current top to make room for new parent */
7745 mc->mc_pg[1] = mc->mc_pg[0];
7746 mc->mc_ki[1] = mc->mc_ki[0];
7749 mc->mc_db->md_root = pp->mp_pgno;
7750 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7751 mc->mc_db->md_depth++;
7754 /* Add left (implicit) pointer. */
7755 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7756 /* undo the pre-push */
7757 mc->mc_pg[0] = mc->mc_pg[1];
7758 mc->mc_ki[0] = mc->mc_ki[1];
7759 mc->mc_db->md_root = mp->mp_pgno;
7760 mc->mc_db->md_depth--;
7767 ptop = mc->mc_top-1;
7768 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7771 mc->mc_flags |= C_SPLITTING;
7772 mdb_cursor_copy(mc, &mn);
7773 mn.mc_pg[mn.mc_top] = rp;
7774 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7776 if (nflags & MDB_APPEND) {
7777 mn.mc_ki[mn.mc_top] = 0;
7779 split_indx = newindx;
7783 split_indx = (nkeys+1) / 2;
7788 unsigned int lsize, rsize, ksize;
7789 /* Move half of the keys to the right sibling */
7790 x = mc->mc_ki[mc->mc_top] - split_indx;
7791 ksize = mc->mc_db->md_pad;
7792 split = LEAF2KEY(mp, split_indx, ksize);
7793 rsize = (nkeys - split_indx) * ksize;
7794 lsize = (nkeys - split_indx) * sizeof(indx_t);
7795 mp->mp_lower -= lsize;
7796 rp->mp_lower += lsize;
7797 mp->mp_upper += rsize - lsize;
7798 rp->mp_upper -= rsize - lsize;
7799 sepkey.mv_size = ksize;
7800 if (newindx == split_indx) {
7801 sepkey.mv_data = newkey->mv_data;
7803 sepkey.mv_data = split;
7806 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7807 memcpy(rp->mp_ptrs, split, rsize);
7808 sepkey.mv_data = rp->mp_ptrs;
7809 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7810 memcpy(ins, newkey->mv_data, ksize);
7811 mp->mp_lower += sizeof(indx_t);
7812 mp->mp_upper -= ksize - sizeof(indx_t);
7815 memcpy(rp->mp_ptrs, split, x * ksize);
7816 ins = LEAF2KEY(rp, x, ksize);
7817 memcpy(ins, newkey->mv_data, ksize);
7818 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7819 rp->mp_lower += sizeof(indx_t);
7820 rp->mp_upper -= ksize - sizeof(indx_t);
7821 mc->mc_ki[mc->mc_top] = x;
7822 mc->mc_pg[mc->mc_top] = rp;
7825 int psize, nsize, k;
7826 /* Maximum free space in an empty page */
7827 pmax = env->me_psize - PAGEHDRSZ;
7829 nsize = mdb_leaf_size(env, newkey, newdata);
7831 nsize = mdb_branch_size(env, newkey);
7832 nsize = EVEN(nsize);
7834 /* grab a page to hold a temporary copy */
7835 copy = mdb_page_malloc(mc->mc_txn, 1);
7840 copy->mp_pgno = mp->mp_pgno;
7841 copy->mp_flags = mp->mp_flags;
7842 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
7843 copy->mp_upper = env->me_psize - PAGEBASE;
7845 /* prepare to insert */
7846 for (i=0, j=0; i<nkeys; i++) {
7848 copy->mp_ptrs[j++] = 0;
7850 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
7853 /* When items are relatively large the split point needs
7854 * to be checked, because being off-by-one will make the
7855 * difference between success or failure in mdb_node_add.
7857 * It's also relevant if a page happens to be laid out
7858 * such that one half of its nodes are all "small" and
7859 * the other half of its nodes are "large." If the new
7860 * item is also "large" and falls on the half with
7861 * "large" nodes, it also may not fit.
7863 * As a final tweak, if the new item goes on the last
7864 * spot on the page (and thus, onto the new page), bias
7865 * the split so the new page is emptier than the old page.
7866 * This yields better packing during sequential inserts.
7868 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
7869 /* Find split point */
7871 if (newindx <= split_indx || newindx >= nkeys) {
7873 k = newindx >= nkeys ? nkeys : split_indx+2;
7878 for (; i!=k; i+=j) {
7883 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
7884 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7886 if (F_ISSET(node->mn_flags, F_BIGDATA))
7887 psize += sizeof(pgno_t);
7889 psize += NODEDSZ(node);
7891 psize = EVEN(psize);
7893 if (psize > pmax || i == k-j) {
7894 split_indx = i + (j<0);
7899 if (split_indx == newindx) {
7900 sepkey.mv_size = newkey->mv_size;
7901 sepkey.mv_data = newkey->mv_data;
7903 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
7904 sepkey.mv_size = node->mn_ksize;
7905 sepkey.mv_data = NODEKEY(node);
7910 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
7912 /* Copy separator key to the parent.
7914 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
7918 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7923 if (mn.mc_snum == mc->mc_snum) {
7924 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7925 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7926 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7927 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7932 /* Right page might now have changed parent.
7933 * Check if left page also changed parent.
7935 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7936 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7937 for (i=0; i<ptop; i++) {
7938 mc->mc_pg[i] = mn.mc_pg[i];
7939 mc->mc_ki[i] = mn.mc_ki[i];
7941 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7942 if (mn.mc_ki[ptop]) {
7943 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7945 /* find right page's left sibling */
7946 mc->mc_ki[ptop] = mn.mc_ki[ptop];
7947 mdb_cursor_sibling(mc, 0);
7952 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7955 mc->mc_flags ^= C_SPLITTING;
7956 if (rc != MDB_SUCCESS) {
7959 if (nflags & MDB_APPEND) {
7960 mc->mc_pg[mc->mc_top] = rp;
7961 mc->mc_ki[mc->mc_top] = 0;
7962 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
7965 for (i=0; i<mc->mc_top; i++)
7966 mc->mc_ki[i] = mn.mc_ki[i];
7967 } else if (!IS_LEAF2(mp)) {
7969 mc->mc_pg[mc->mc_top] = rp;
7974 rkey.mv_data = newkey->mv_data;
7975 rkey.mv_size = newkey->mv_size;
7981 /* Update index for the new key. */
7982 mc->mc_ki[mc->mc_top] = j;
7984 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
7985 rkey.mv_data = NODEKEY(node);
7986 rkey.mv_size = node->mn_ksize;
7988 xdata.mv_data = NODEDATA(node);
7989 xdata.mv_size = NODEDSZ(node);
7992 pgno = NODEPGNO(node);
7993 flags = node->mn_flags;
7996 if (!IS_LEAF(mp) && j == 0) {
7997 /* First branch index doesn't need key data. */
8001 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8007 mc->mc_pg[mc->mc_top] = copy;
8012 } while (i != split_indx);
8014 nkeys = NUMKEYS(copy);
8015 for (i=0; i<nkeys; i++)
8016 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8017 mp->mp_lower = copy->mp_lower;
8018 mp->mp_upper = copy->mp_upper;
8019 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8020 env->me_psize - copy->mp_upper - PAGEBASE);
8022 /* reset back to original page */
8023 if (newindx < split_indx) {
8024 mc->mc_pg[mc->mc_top] = mp;
8025 if (nflags & MDB_RESERVE) {
8026 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
8027 if (!(node->mn_flags & F_BIGDATA))
8028 newdata->mv_data = NODEDATA(node);
8031 mc->mc_pg[mc->mc_top] = rp;
8033 /* Make sure mc_ki is still valid.
8035 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8036 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8037 for (i=0; i<=ptop; i++) {
8038 mc->mc_pg[i] = mn.mc_pg[i];
8039 mc->mc_ki[i] = mn.mc_ki[i];
8046 /* Adjust other cursors pointing to mp */
8047 MDB_cursor *m2, *m3;
8048 MDB_dbi dbi = mc->mc_dbi;
8049 int fixup = NUMKEYS(mp);
8051 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8052 if (mc->mc_flags & C_SUB)
8053 m3 = &m2->mc_xcursor->mx_cursor;
8058 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8060 if (m3->mc_flags & C_SPLITTING)
8065 for (k=m3->mc_top; k>=0; k--) {
8066 m3->mc_ki[k+1] = m3->mc_ki[k];
8067 m3->mc_pg[k+1] = m3->mc_pg[k];
8069 if (m3->mc_ki[0] >= split_indx) {
8074 m3->mc_pg[0] = mc->mc_pg[0];
8078 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8079 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8080 m3->mc_ki[mc->mc_top]++;
8081 if (m3->mc_ki[mc->mc_top] >= fixup) {
8082 m3->mc_pg[mc->mc_top] = rp;
8083 m3->mc_ki[mc->mc_top] -= fixup;
8084 m3->mc_ki[ptop] = mn.mc_ki[ptop];
8086 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8087 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8092 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8095 if (copy) /* tmp page */
8096 mdb_page_free(env, copy);
8098 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8103 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8104 MDB_val *key, MDB_val *data, unsigned int flags)
8109 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8112 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
8115 mdb_cursor_init(&mc, txn, dbi, &mx);
8116 return mdb_cursor_put(&mc, key, data, flags);
8120 #define MDB_WBUF (1024*1024)
8123 /** State needed for a compacting copy. */
8124 typedef struct mdb_copy {
8125 pthread_mutex_t mc_mutex;
8126 pthread_cond_t mc_cond;
8133 pgno_t mc_next_pgno;
8136 volatile int mc_new;
8141 /** Dedicated writer thread for compacting copy. */
8142 static THREAD_RET ESECT
8143 mdb_env_copythr(void *arg)
8147 int toggle = 0, wsize, rc;
8150 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8153 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8156 pthread_mutex_lock(&my->mc_mutex);
8158 pthread_cond_signal(&my->mc_cond);
8161 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8162 if (my->mc_new < 0) {
8167 wsize = my->mc_wlen[toggle];
8168 ptr = my->mc_wbuf[toggle];
8171 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8175 } else if (len > 0) {
8189 /* If there's an overflow page tail, write it too */
8190 if (my->mc_olen[toggle]) {
8191 wsize = my->mc_olen[toggle];
8192 ptr = my->mc_over[toggle];
8193 my->mc_olen[toggle] = 0;
8196 my->mc_wlen[toggle] = 0;
8198 pthread_cond_signal(&my->mc_cond);
8200 pthread_cond_signal(&my->mc_cond);
8201 pthread_mutex_unlock(&my->mc_mutex);
8202 return (THREAD_RET)0;
8206 /** Tell the writer thread there's a buffer ready to write */
8208 mdb_env_cthr_toggle(mdb_copy *my, int st)
8210 int toggle = my->mc_toggle ^ 1;
8211 pthread_mutex_lock(&my->mc_mutex);
8212 if (my->mc_status) {
8213 pthread_mutex_unlock(&my->mc_mutex);
8214 return my->mc_status;
8216 while (my->mc_new == 1)
8217 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8219 my->mc_toggle = toggle;
8220 pthread_cond_signal(&my->mc_cond);
8221 pthread_mutex_unlock(&my->mc_mutex);
8225 /** Depth-first tree traversal for compacting copy. */
8227 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8230 MDB_txn *txn = my->mc_txn;
8232 MDB_page *mo, *mp, *leaf;
8237 /* Empty DB, nothing to do */
8238 if (*pg == P_INVALID)
8245 rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
8248 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8252 /* Make cursor pages writable */
8253 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8257 for (i=0; i<mc.mc_top; i++) {
8258 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8259 mc.mc_pg[i] = (MDB_page *)ptr;
8260 ptr += my->mc_env->me_psize;
8263 /* This is writable space for a leaf page. Usually not needed. */
8264 leaf = (MDB_page *)ptr;
8266 toggle = my->mc_toggle;
8267 while (mc.mc_snum > 0) {
8269 mp = mc.mc_pg[mc.mc_top];
8273 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8274 for (i=0; i<n; i++) {
8275 ni = NODEPTR(mp, i);
8276 if (ni->mn_flags & F_BIGDATA) {
8280 /* Need writable leaf */
8282 mc.mc_pg[mc.mc_top] = leaf;
8283 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8285 ni = NODEPTR(mp, i);
8288 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8289 rc = mdb_page_get(txn, pg, &omp, NULL);
8292 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8293 rc = mdb_env_cthr_toggle(my, 1);
8296 toggle = my->mc_toggle;
8298 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8299 memcpy(mo, omp, my->mc_env->me_psize);
8300 mo->mp_pgno = my->mc_next_pgno;
8301 my->mc_next_pgno += omp->mp_pages;
8302 my->mc_wlen[toggle] += my->mc_env->me_psize;
8303 if (omp->mp_pages > 1) {
8304 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
8305 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
8306 rc = mdb_env_cthr_toggle(my, 1);
8309 toggle = my->mc_toggle;
8311 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
8312 } else if (ni->mn_flags & F_SUBDATA) {
8315 /* Need writable leaf */
8317 mc.mc_pg[mc.mc_top] = leaf;
8318 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8320 ni = NODEPTR(mp, i);
8323 memcpy(&db, NODEDATA(ni), sizeof(db));
8324 my->mc_toggle = toggle;
8325 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
8328 toggle = my->mc_toggle;
8329 memcpy(NODEDATA(ni), &db, sizeof(db));
8334 mc.mc_ki[mc.mc_top]++;
8335 if (mc.mc_ki[mc.mc_top] < n) {
8338 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
8340 rc = mdb_page_get(txn, pg, &mp, NULL);
8345 mc.mc_ki[mc.mc_top] = 0;
8346 if (IS_BRANCH(mp)) {
8347 /* Whenever we advance to a sibling branch page,
8348 * we must proceed all the way down to its first leaf.
8350 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
8353 mc.mc_pg[mc.mc_top] = mp;
8357 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8358 rc = mdb_env_cthr_toggle(my, 1);
8361 toggle = my->mc_toggle;
8363 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8364 mdb_page_copy(mo, mp, my->mc_env->me_psize);
8365 mo->mp_pgno = my->mc_next_pgno++;
8366 my->mc_wlen[toggle] += my->mc_env->me_psize;
8368 /* Update parent if there is one */
8369 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
8370 SETPGNO(ni, mo->mp_pgno);
8371 mdb_cursor_pop(&mc);
8373 /* Otherwise we're done */
8383 /** Copy environment with compaction. */
8385 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
8390 MDB_txn *txn = NULL;
8395 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
8396 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
8397 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_psize);
8398 if (my.mc_wbuf[0] == NULL)
8401 pthread_mutex_init(&my.mc_mutex, NULL);
8402 pthread_cond_init(&my.mc_cond, NULL);
8403 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_psize, MDB_WBUF*2);
8407 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
8412 my.mc_next_pgno = 2;
8418 THREAD_CREATE(thr, mdb_env_copythr, &my);
8420 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8424 mp = (MDB_page *)my.mc_wbuf[0];
8425 memset(mp, 0, 2*env->me_psize);
8427 mp->mp_flags = P_META;
8428 mm = (MDB_meta *)METADATA(mp);
8429 mdb_env_init_meta0(env, mm);
8430 mm->mm_address = env->me_metas[0]->mm_address;
8432 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
8434 mp->mp_flags = P_META;
8435 *(MDB_meta *)METADATA(mp) = *mm;
8436 mm = (MDB_meta *)METADATA(mp);
8438 /* Count the number of free pages, subtract from lastpg to find
8439 * number of active pages
8442 MDB_ID freecount = 0;
8445 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
8446 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
8447 freecount += *(MDB_ID *)data.mv_data;
8448 freecount += txn->mt_dbs[0].md_branch_pages +
8449 txn->mt_dbs[0].md_leaf_pages +
8450 txn->mt_dbs[0].md_overflow_pages;
8452 /* Set metapage 1 */
8453 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
8454 mm->mm_dbs[1] = txn->mt_dbs[1];
8455 mm->mm_dbs[1].md_root = mm->mm_last_pg;
8458 my.mc_wlen[0] = env->me_psize * 2;
8460 pthread_mutex_lock(&my.mc_mutex);
8462 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8463 pthread_mutex_unlock(&my.mc_mutex);
8464 rc = mdb_env_cwalk(&my, &txn->mt_dbs[1].md_root, 0);
8465 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
8466 rc = mdb_env_cthr_toggle(&my, 1);
8467 mdb_env_cthr_toggle(&my, -1);
8468 pthread_mutex_lock(&my.mc_mutex);
8470 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8471 pthread_mutex_unlock(&my.mc_mutex);
8476 CloseHandle(my.mc_cond);
8477 CloseHandle(my.mc_mutex);
8478 _aligned_free(my.mc_wbuf[0]);
8480 pthread_cond_destroy(&my.mc_cond);
8481 pthread_mutex_destroy(&my.mc_mutex);
8482 free(my.mc_wbuf[0]);
8487 /** Copy environment as-is. */
8489 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
8491 MDB_txn *txn = NULL;
8497 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8501 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8504 /* Do the lock/unlock of the reader mutex before starting the
8505 * write txn. Otherwise other read txns could block writers.
8507 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8512 /* We must start the actual read txn after blocking writers */
8513 mdb_txn_reset0(txn, "reset-stage1");
8515 /* Temporarily block writers until we snapshot the meta pages */
8518 rc = mdb_txn_renew0(txn);
8520 UNLOCK_MUTEX_W(env);
8525 wsize = env->me_psize * 2;
8529 DO_WRITE(rc, fd, ptr, w2, len);
8533 } else if (len > 0) {
8539 /* Non-blocking or async handles are not supported */
8545 UNLOCK_MUTEX_W(env);
8550 w2 = txn->mt_next_pgno * env->me_psize;
8553 LARGE_INTEGER fsize;
8554 GetFileSizeEx(env->me_fd, &fsize);
8555 if (w2 > fsize.QuadPart)
8556 w2 = fsize.QuadPart;
8561 fstat(env->me_fd, &st);
8562 if (w2 > (size_t)st.st_size)
8568 if (wsize > MAX_WRITE)
8572 DO_WRITE(rc, fd, ptr, w2, len);
8576 } else if (len > 0) {
8593 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
8595 if (flags & MDB_CP_COMPACT)
8596 return mdb_env_copyfd1(env, fd);
8598 return mdb_env_copyfd0(env, fd);
8602 mdb_env_copyfd(MDB_env *env, HANDLE fd)
8604 return mdb_env_copyfd2(env, fd, 0);
8608 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
8612 HANDLE newfd = INVALID_HANDLE_VALUE;
8614 if (env->me_flags & MDB_NOSUBDIR) {
8615 lpath = (char *)path;
8618 len += sizeof(DATANAME);
8619 lpath = malloc(len);
8622 sprintf(lpath, "%s" DATANAME, path);
8625 /* The destination path must exist, but the destination file must not.
8626 * We don't want the OS to cache the writes, since the source data is
8627 * already in the OS cache.
8630 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
8631 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
8633 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
8635 if (newfd == INVALID_HANDLE_VALUE) {
8641 /* Set O_DIRECT if the file system supports it */
8642 if ((rc = fcntl(newfd, F_GETFL)) != -1)
8643 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
8645 #ifdef F_NOCACHE /* __APPLE__ */
8646 rc = fcntl(newfd, F_NOCACHE, 1);
8653 rc = mdb_env_copyfd2(env, newfd, flags);
8656 if (!(env->me_flags & MDB_NOSUBDIR))
8658 if (newfd != INVALID_HANDLE_VALUE)
8659 if (close(newfd) < 0 && rc == MDB_SUCCESS)
8666 mdb_env_copy(MDB_env *env, const char *path)
8668 return mdb_env_copy2(env, path, 0);
8672 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
8674 if ((flag & CHANGEABLE) != flag)
8677 env->me_flags |= flag;
8679 env->me_flags &= ~flag;
8684 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
8689 *arg = env->me_flags;
8694 mdb_env_set_userctx(MDB_env *env, void *ctx)
8698 env->me_userctx = ctx;
8703 mdb_env_get_userctx(MDB_env *env)
8705 return env ? env->me_userctx : NULL;
8709 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
8714 env->me_assert_func = func;
8720 mdb_env_get_path(MDB_env *env, const char **arg)
8725 *arg = env->me_path;
8730 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
8739 /** Common code for #mdb_stat() and #mdb_env_stat().
8740 * @param[in] env the environment to operate in.
8741 * @param[in] db the #MDB_db record containing the stats to return.
8742 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
8743 * @return 0, this function always succeeds.
8746 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
8748 arg->ms_psize = env->me_psize;
8749 arg->ms_depth = db->md_depth;
8750 arg->ms_branch_pages = db->md_branch_pages;
8751 arg->ms_leaf_pages = db->md_leaf_pages;
8752 arg->ms_overflow_pages = db->md_overflow_pages;
8753 arg->ms_entries = db->md_entries;
8759 mdb_env_stat(MDB_env *env, MDB_stat *arg)
8763 if (env == NULL || arg == NULL)
8766 toggle = mdb_env_pick_meta(env);
8768 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
8772 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
8776 if (env == NULL || arg == NULL)
8779 toggle = mdb_env_pick_meta(env);
8780 arg->me_mapaddr = env->me_metas[toggle]->mm_address;
8781 arg->me_mapsize = env->me_mapsize;
8782 arg->me_maxreaders = env->me_maxreaders;
8784 /* me_numreaders may be zero if this process never used any readers. Use
8785 * the shared numreader count if it exists.
8787 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
8789 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
8790 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
8794 /** Set the default comparison functions for a database.
8795 * Called immediately after a database is opened to set the defaults.
8796 * The user can then override them with #mdb_set_compare() or
8797 * #mdb_set_dupsort().
8798 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
8799 * @param[in] dbi A database handle returned by #mdb_dbi_open()
8802 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
8804 uint16_t f = txn->mt_dbs[dbi].md_flags;
8806 txn->mt_dbxs[dbi].md_cmp =
8807 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
8808 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
8810 txn->mt_dbxs[dbi].md_dcmp =
8811 !(f & MDB_DUPSORT) ? 0 :
8812 ((f & MDB_INTEGERDUP)
8813 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
8814 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
8817 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
8822 int rc, dbflag, exact;
8823 unsigned int unused = 0, seq;
8826 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
8827 mdb_default_cmp(txn, FREE_DBI);
8830 if ((flags & VALID_FLAGS) != flags)
8832 if (txn->mt_flags & MDB_TXN_ERROR)
8838 if (flags & PERSISTENT_FLAGS) {
8839 uint16_t f2 = flags & PERSISTENT_FLAGS;
8840 /* make sure flag changes get committed */
8841 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
8842 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
8843 txn->mt_flags |= MDB_TXN_DIRTY;
8846 mdb_default_cmp(txn, MAIN_DBI);
8850 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
8851 mdb_default_cmp(txn, MAIN_DBI);
8854 /* Is the DB already open? */
8856 for (i=2; i<txn->mt_numdbs; i++) {
8857 if (!txn->mt_dbxs[i].md_name.mv_size) {
8858 /* Remember this free slot */
8859 if (!unused) unused = i;
8862 if (len == txn->mt_dbxs[i].md_name.mv_size &&
8863 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
8869 /* If no free slot and max hit, fail */
8870 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
8871 return MDB_DBS_FULL;
8873 /* Cannot mix named databases with some mainDB flags */
8874 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
8875 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
8877 /* Find the DB info */
8878 dbflag = DB_NEW|DB_VALID;
8881 key.mv_data = (void *)name;
8882 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
8883 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
8884 if (rc == MDB_SUCCESS) {
8885 /* make sure this is actually a DB */
8886 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
8887 if (!(node->mn_flags & F_SUBDATA))
8888 return MDB_INCOMPATIBLE;
8889 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
8890 /* Create if requested */
8892 data.mv_size = sizeof(MDB_db);
8893 data.mv_data = &dummy;
8894 memset(&dummy, 0, sizeof(dummy));
8895 dummy.md_root = P_INVALID;
8896 dummy.md_flags = flags & PERSISTENT_FLAGS;
8897 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
8901 /* OK, got info, add to table */
8902 if (rc == MDB_SUCCESS) {
8903 unsigned int slot = unused ? unused : txn->mt_numdbs;
8904 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
8905 txn->mt_dbxs[slot].md_name.mv_size = len;
8906 txn->mt_dbxs[slot].md_rel = NULL;
8907 txn->mt_dbflags[slot] = dbflag;
8908 /* txn-> and env-> are the same in read txns, use
8909 * tmp variable to avoid undefined assignment
8911 seq = ++txn->mt_env->me_dbiseqs[slot];
8912 txn->mt_dbiseqs[slot] = seq;
8914 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
8916 mdb_default_cmp(txn, slot);
8925 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
8927 if (!arg || !TXN_DBI_EXIST(txn, dbi))
8930 if (txn->mt_flags & MDB_TXN_ERROR)
8933 if (txn->mt_dbflags[dbi] & DB_STALE) {
8936 /* Stale, must read the DB's root. cursor_init does it for us. */
8937 mdb_cursor_init(&mc, txn, dbi, &mx);
8939 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
8942 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
8945 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
8947 ptr = env->me_dbxs[dbi].md_name.mv_data;
8948 /* If there was no name, this was already closed */
8950 env->me_dbxs[dbi].md_name.mv_data = NULL;
8951 env->me_dbxs[dbi].md_name.mv_size = 0;
8952 env->me_dbflags[dbi] = 0;
8953 env->me_dbiseqs[dbi]++;
8958 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
8960 /* We could return the flags for the FREE_DBI too but what's the point? */
8961 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8963 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
8967 /** Add all the DB's pages to the free list.
8968 * @param[in] mc Cursor on the DB to free.
8969 * @param[in] subs non-Zero to check for sub-DBs in this DB.
8970 * @return 0 on success, non-zero on failure.
8973 mdb_drop0(MDB_cursor *mc, int subs)
8977 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
8978 if (rc == MDB_SUCCESS) {
8979 MDB_txn *txn = mc->mc_txn;
8984 /* LEAF2 pages have no nodes, cannot have sub-DBs */
8985 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
8988 mdb_cursor_copy(mc, &mx);
8989 while (mc->mc_snum > 0) {
8990 MDB_page *mp = mc->mc_pg[mc->mc_top];
8991 unsigned n = NUMKEYS(mp);
8993 for (i=0; i<n; i++) {
8994 ni = NODEPTR(mp, i);
8995 if (ni->mn_flags & F_BIGDATA) {
8998 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8999 rc = mdb_page_get(txn, pg, &omp, NULL);
9002 mdb_cassert(mc, IS_OVERFLOW(omp));
9003 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9007 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9008 mdb_xcursor_init1(mc, ni);
9009 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9015 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9017 for (i=0; i<n; i++) {
9019 ni = NODEPTR(mp, i);
9022 mdb_midl_xappend(txn->mt_free_pgs, pg);
9027 mc->mc_ki[mc->mc_top] = i;
9028 rc = mdb_cursor_sibling(mc, 1);
9030 if (rc != MDB_NOTFOUND)
9032 /* no more siblings, go back to beginning
9033 * of previous level.
9037 for (i=1; i<mc->mc_snum; i++) {
9039 mc->mc_pg[i] = mx.mc_pg[i];
9044 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9047 txn->mt_flags |= MDB_TXN_ERROR;
9048 } else if (rc == MDB_NOTFOUND) {
9054 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9056 MDB_cursor *mc, *m2;
9059 if ((unsigned)del > 1 || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9062 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9065 if (dbi > MAIN_DBI && TXN_DBI_CHANGED(txn, dbi))
9068 rc = mdb_cursor_open(txn, dbi, &mc);
9072 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9073 /* Invalidate the dropped DB's cursors */
9074 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9075 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9079 /* Can't delete the main DB */
9080 if (del && dbi > MAIN_DBI) {
9081 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, 0);
9083 txn->mt_dbflags[dbi] = DB_STALE;
9084 mdb_dbi_close(txn->mt_env, dbi);
9086 txn->mt_flags |= MDB_TXN_ERROR;
9089 /* reset the DB record, mark it dirty */
9090 txn->mt_dbflags[dbi] |= DB_DIRTY;
9091 txn->mt_dbs[dbi].md_depth = 0;
9092 txn->mt_dbs[dbi].md_branch_pages = 0;
9093 txn->mt_dbs[dbi].md_leaf_pages = 0;
9094 txn->mt_dbs[dbi].md_overflow_pages = 0;
9095 txn->mt_dbs[dbi].md_entries = 0;
9096 txn->mt_dbs[dbi].md_root = P_INVALID;
9098 txn->mt_flags |= MDB_TXN_DIRTY;
9101 mdb_cursor_close(mc);
9105 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9107 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9110 txn->mt_dbxs[dbi].md_cmp = cmp;
9114 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9116 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9119 txn->mt_dbxs[dbi].md_dcmp = cmp;
9123 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9125 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9128 txn->mt_dbxs[dbi].md_rel = rel;
9132 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9134 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9137 txn->mt_dbxs[dbi].md_relctx = ctx;
9142 mdb_env_get_maxkeysize(MDB_env *env)
9144 return ENV_MAXKEY(env);
9148 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9150 unsigned int i, rdrs;
9153 int rc = 0, first = 1;
9157 if (!env->me_txns) {
9158 return func("(no reader locks)\n", ctx);
9160 rdrs = env->me_txns->mti_numreaders;
9161 mr = env->me_txns->mti_readers;
9162 for (i=0; i<rdrs; i++) {
9164 txnid_t txnid = mr[i].mr_txnid;
9165 sprintf(buf, txnid == (txnid_t)-1 ?
9166 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9167 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9170 rc = func(" pid thread txnid\n", ctx);
9174 rc = func(buf, ctx);
9180 rc = func("(no active readers)\n", ctx);
9185 /** Insert pid into list if not already present.
9186 * return -1 if already present.
9189 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9191 /* binary search of pid in list */
9193 unsigned cursor = 1;
9195 unsigned n = ids[0];
9198 unsigned pivot = n >> 1;
9199 cursor = base + pivot + 1;
9200 val = pid - ids[cursor];
9205 } else if ( val > 0 ) {
9210 /* found, so it's a duplicate */
9219 for (n = ids[0]; n > cursor; n--)
9226 mdb_reader_check(MDB_env *env, int *dead)
9228 unsigned int i, j, rdrs;
9230 MDB_PID_T *pids, pid;
9239 rdrs = env->me_txns->mti_numreaders;
9240 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
9244 mr = env->me_txns->mti_readers;
9245 for (i=0; i<rdrs; i++) {
9246 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
9248 if (mdb_pid_insert(pids, pid) == 0) {
9249 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9251 /* Recheck, a new process may have reused pid */
9252 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9253 for (j=i; j<rdrs; j++)
9254 if (mr[j].mr_pid == pid) {
9255 DPRINTF(("clear stale reader pid %u txn %"Z"d",
9256 (unsigned) pid, mr[j].mr_txnid));
9261 UNLOCK_MUTEX_R(env);