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 /** @defgroup mt_dbflag Transaction DB Flags
961 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
962 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
963 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
964 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
966 /** In write txns, array of cursors for each DB */
967 MDB_cursor **mt_cursors;
968 /** Array of flags for each DB */
969 unsigned char *mt_dbflags;
970 /** Number of DB records in use. This number only ever increments;
971 * we don't decrement it when individual DB handles are closed.
975 /** @defgroup mdb_txn Transaction Flags
979 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
980 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
981 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
982 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
984 unsigned int mt_flags; /**< @ref mdb_txn */
985 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
986 * Includes ancestor txns' dirty pages not hidden by other txns'
987 * dirty/spilled pages. Thus commit(nested txn) has room to merge
988 * dirty_list into mt_parent after freeing hidden mt_parent pages.
990 unsigned int mt_dirty_room;
993 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
994 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
995 * raise this on a 64 bit machine.
997 #define CURSOR_STACK 32
1001 /** Cursors are used for all DB operations.
1002 * A cursor holds a path of (page pointer, key index) from the DB
1003 * root to a position in the DB, plus other state. #MDB_DUPSORT
1004 * cursors include an xcursor to the current data item. Write txns
1005 * track their cursors and keep them up to date when data moves.
1006 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1007 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1010 /** Next cursor on this DB in this txn */
1011 MDB_cursor *mc_next;
1012 /** Backup of the original cursor if this cursor is a shadow */
1013 MDB_cursor *mc_backup;
1014 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1015 struct MDB_xcursor *mc_xcursor;
1016 /** The transaction that owns this cursor */
1018 /** The database handle this cursor operates on */
1020 /** The database record for this cursor */
1022 /** The database auxiliary record for this cursor */
1024 /** The @ref mt_dbflag for this database */
1025 unsigned char *mc_dbflag;
1026 unsigned short mc_snum; /**< number of pushed pages */
1027 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1028 /** @defgroup mdb_cursor Cursor Flags
1030 * Cursor state flags.
1033 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1034 #define C_EOF 0x02 /**< No more data */
1035 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1036 #define C_DEL 0x08 /**< last op was a cursor_del */
1037 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
1038 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1040 unsigned int mc_flags; /**< @ref mdb_cursor */
1041 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1042 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1045 /** Context for sorted-dup records.
1046 * We could have gone to a fully recursive design, with arbitrarily
1047 * deep nesting of sub-databases. But for now we only handle these
1048 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1050 typedef struct MDB_xcursor {
1051 /** A sub-cursor for traversing the Dup DB */
1052 MDB_cursor mx_cursor;
1053 /** The database record for this Dup DB */
1055 /** The auxiliary DB record for this Dup DB */
1057 /** The @ref mt_dbflag for this Dup DB */
1058 unsigned char mx_dbflag;
1061 /** State of FreeDB old pages, stored in the MDB_env */
1062 typedef struct MDB_pgstate {
1063 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1064 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1067 /** The database environment. */
1069 HANDLE me_fd; /**< The main data file */
1070 HANDLE me_lfd; /**< The lock file */
1071 HANDLE me_mfd; /**< just for writing the meta pages */
1072 /** Failed to update the meta page. Probably an I/O error. */
1073 #define MDB_FATAL_ERROR 0x80000000U
1074 /** We're explicitly changing the mapsize. */
1075 #define MDB_RESIZING 0x40000000U
1076 /** Some fields are initialized. */
1077 #define MDB_ENV_ACTIVE 0x20000000U
1078 /** me_txkey is set */
1079 #define MDB_ENV_TXKEY 0x10000000U
1080 uint32_t me_flags; /**< @ref mdb_env */
1081 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1082 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1083 unsigned int me_maxreaders; /**< size of the reader table */
1084 unsigned int me_numreaders; /**< max numreaders set by this env */
1085 MDB_dbi me_numdbs; /**< number of DBs opened */
1086 MDB_dbi me_maxdbs; /**< size of the DB table */
1087 MDB_PID_T me_pid; /**< process ID of this env */
1088 char *me_path; /**< path to the DB files */
1089 char *me_map; /**< the memory map of the data file */
1090 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1091 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
1092 void *me_pbuf; /**< scratch area for DUPSORT put() */
1093 MDB_txn *me_txn; /**< current write transaction */
1094 size_t me_mapsize; /**< size of the data memory map */
1095 off_t me_size; /**< current file size */
1096 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1097 MDB_dbx *me_dbxs; /**< array of static DB info */
1098 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1099 pthread_key_t me_txkey; /**< thread-key for readers */
1100 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1101 # define me_pglast me_pgstate.mf_pglast
1102 # define me_pghead me_pgstate.mf_pghead
1103 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1104 /** IDL of pages that became unused in a write txn */
1105 MDB_IDL me_free_pgs;
1106 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1107 MDB_ID2L me_dirty_list;
1108 /** Max number of freelist items that can fit in a single overflow page */
1110 /** Max size of a node on a page */
1111 unsigned int me_nodemax;
1112 #if !(MDB_MAXKEYSIZE)
1113 unsigned int me_maxkey; /**< max size of a key */
1115 int me_live_reader; /**< have liveness lock in reader table */
1117 int me_pidquery; /**< Used in OpenProcess */
1118 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
1120 #elif defined(MDB_USE_POSIX_SEM)
1121 sem_t *me_rmutex; /* Shared mutexes are not supported */
1124 void *me_userctx; /**< User-settable context */
1125 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1128 /** Nested transaction */
1129 typedef struct MDB_ntxn {
1130 MDB_txn mnt_txn; /**< the transaction */
1131 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1134 /** max number of pages to commit in one writev() call */
1135 #define MDB_COMMIT_PAGES 64
1136 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1137 #undef MDB_COMMIT_PAGES
1138 #define MDB_COMMIT_PAGES IOV_MAX
1141 /** max bytes to write in one call */
1142 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1144 /** Check \b txn and \b dbi arguments to a function */
1145 #define TXN_DBI_EXIST(txn, dbi) \
1146 ((txn) && (dbi) < (txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & DB_VALID))
1148 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1149 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1150 static int mdb_page_touch(MDB_cursor *mc);
1152 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1153 static int mdb_page_search_root(MDB_cursor *mc,
1154 MDB_val *key, int modify);
1155 #define MDB_PS_MODIFY 1
1156 #define MDB_PS_ROOTONLY 2
1157 #define MDB_PS_FIRST 4
1158 #define MDB_PS_LAST 8
1159 static int mdb_page_search(MDB_cursor *mc,
1160 MDB_val *key, int flags);
1161 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1163 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1164 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1165 pgno_t newpgno, unsigned int nflags);
1167 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1168 static int mdb_env_pick_meta(const MDB_env *env);
1169 static int mdb_env_write_meta(MDB_txn *txn);
1170 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1171 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1173 static void mdb_env_close0(MDB_env *env, int excl);
1175 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1176 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1177 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1178 static void mdb_node_del(MDB_cursor *mc, int ksize);
1179 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1180 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1181 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1182 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1183 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1185 static int mdb_rebalance(MDB_cursor *mc);
1186 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1188 static void mdb_cursor_pop(MDB_cursor *mc);
1189 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1191 static int mdb_cursor_del0(MDB_cursor *mc);
1192 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1193 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1194 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1195 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1196 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1198 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1199 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1201 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1202 static void mdb_xcursor_init0(MDB_cursor *mc);
1203 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1205 static int mdb_drop0(MDB_cursor *mc, int subs);
1206 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1209 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1213 static SECURITY_DESCRIPTOR mdb_null_sd;
1214 static SECURITY_ATTRIBUTES mdb_all_sa;
1215 static int mdb_sec_inited;
1218 /** Return the library version info. */
1220 mdb_version(int *major, int *minor, int *patch)
1222 if (major) *major = MDB_VERSION_MAJOR;
1223 if (minor) *minor = MDB_VERSION_MINOR;
1224 if (patch) *patch = MDB_VERSION_PATCH;
1225 return MDB_VERSION_STRING;
1228 /** Table of descriptions for LMDB @ref errors */
1229 static char *const mdb_errstr[] = {
1230 "MDB_KEYEXIST: Key/data pair already exists",
1231 "MDB_NOTFOUND: No matching key/data pair found",
1232 "MDB_PAGE_NOTFOUND: Requested page not found",
1233 "MDB_CORRUPTED: Located page was wrong type",
1234 "MDB_PANIC: Update of meta page failed",
1235 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1236 "MDB_INVALID: File is not an LMDB file",
1237 "MDB_MAP_FULL: Environment mapsize limit reached",
1238 "MDB_DBS_FULL: Environment maxdbs limit reached",
1239 "MDB_READERS_FULL: Environment maxreaders limit reached",
1240 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1241 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1242 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1243 "MDB_PAGE_FULL: Internal error - page has no more space",
1244 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1245 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1246 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1247 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1248 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1252 mdb_strerror(int err)
1256 return ("Successful return: 0");
1258 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1259 i = err - MDB_KEYEXIST;
1260 return mdb_errstr[i];
1263 return strerror(err);
1266 /** assert(3) variant in cursor context */
1267 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1268 /** assert(3) variant in transaction context */
1269 #define mdb_tassert(mc, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1270 /** assert(3) variant in environment context */
1271 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1274 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1275 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1278 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1279 const char *func, const char *file, int line)
1282 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1283 file, line, expr_txt, func);
1284 if (env->me_assert_func)
1285 env->me_assert_func(env, buf);
1286 fprintf(stderr, "%s\n", buf);
1290 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1294 /** Return the page number of \b mp which may be sub-page, for debug output */
1296 mdb_dbg_pgno(MDB_page *mp)
1299 COPY_PGNO(ret, mp->mp_pgno);
1303 /** Display a key in hexadecimal and return the address of the result.
1304 * @param[in] key the key to display
1305 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1306 * @return The key in hexadecimal form.
1309 mdb_dkey(MDB_val *key, char *buf)
1312 unsigned char *c = key->mv_data;
1318 if (key->mv_size > DKBUF_MAXKEYSIZE)
1319 return "MDB_MAXKEYSIZE";
1320 /* may want to make this a dynamic check: if the key is mostly
1321 * printable characters, print it as-is instead of converting to hex.
1325 for (i=0; i<key->mv_size; i++)
1326 ptr += sprintf(ptr, "%02x", *c++);
1328 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1334 mdb_leafnode_type(MDB_node *n)
1336 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1337 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1338 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1341 /** Display all the keys in the page. */
1343 mdb_page_list(MDB_page *mp)
1345 pgno_t pgno = mdb_dbg_pgno(mp);
1346 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1348 unsigned int i, nkeys, nsize, total = 0;
1352 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1353 case P_BRANCH: type = "Branch page"; break;
1354 case P_LEAF: type = "Leaf page"; break;
1355 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1356 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1357 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1359 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1360 pgno, mp->mp_pages, state);
1363 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1364 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1367 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1371 nkeys = NUMKEYS(mp);
1372 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1374 for (i=0; i<nkeys; i++) {
1375 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1376 key.mv_size = nsize = mp->mp_pad;
1377 key.mv_data = LEAF2KEY(mp, i, nsize);
1379 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1382 node = NODEPTR(mp, i);
1383 key.mv_size = node->mn_ksize;
1384 key.mv_data = node->mn_data;
1385 nsize = NODESIZE + key.mv_size;
1386 if (IS_BRANCH(mp)) {
1387 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1391 if (F_ISSET(node->mn_flags, F_BIGDATA))
1392 nsize += sizeof(pgno_t);
1394 nsize += NODEDSZ(node);
1396 nsize += sizeof(indx_t);
1397 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1398 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1400 total = EVEN(total);
1402 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1403 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1407 mdb_cursor_chk(MDB_cursor *mc)
1413 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1414 for (i=0; i<mc->mc_top; i++) {
1416 node = NODEPTR(mp, mc->mc_ki[i]);
1417 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1420 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1426 /** Count all the pages in each DB and in the freelist
1427 * and make sure it matches the actual number of pages
1429 * All named DBs must be open for a correct count.
1431 static void mdb_audit(MDB_txn *txn)
1435 MDB_ID freecount, count;
1440 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1441 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1442 freecount += *(MDB_ID *)data.mv_data;
1443 mdb_tassert(txn, rc == MDB_NOTFOUND);
1446 for (i = 0; i<txn->mt_numdbs; i++) {
1448 if (!(txn->mt_dbflags[i] & DB_VALID))
1450 mdb_cursor_init(&mc, txn, i, &mx);
1451 if (txn->mt_dbs[i].md_root == P_INVALID)
1453 count += txn->mt_dbs[i].md_branch_pages +
1454 txn->mt_dbs[i].md_leaf_pages +
1455 txn->mt_dbs[i].md_overflow_pages;
1456 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1457 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1458 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1461 mp = mc.mc_pg[mc.mc_top];
1462 for (j=0; j<NUMKEYS(mp); j++) {
1463 MDB_node *leaf = NODEPTR(mp, j);
1464 if (leaf->mn_flags & F_SUBDATA) {
1466 memcpy(&db, NODEDATA(leaf), sizeof(db));
1467 count += db.md_branch_pages + db.md_leaf_pages +
1468 db.md_overflow_pages;
1472 mdb_tassert(txn, rc == MDB_NOTFOUND);
1475 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1476 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1477 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1483 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1485 return txn->mt_dbxs[dbi].md_cmp(a, b);
1489 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1491 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1494 /** Allocate memory for a page.
1495 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1498 mdb_page_malloc(MDB_txn *txn, unsigned num)
1500 MDB_env *env = txn->mt_env;
1501 MDB_page *ret = env->me_dpages;
1502 size_t psize = env->me_psize, sz = psize, off;
1503 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1504 * For a single page alloc, we init everything after the page header.
1505 * For multi-page, we init the final page; if the caller needed that
1506 * many pages they will be filling in at least up to the last page.
1510 VGMEMP_ALLOC(env, ret, sz);
1511 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1512 env->me_dpages = ret->mp_next;
1515 psize -= off = PAGEHDRSZ;
1520 if ((ret = malloc(sz)) != NULL) {
1521 VGMEMP_ALLOC(env, ret, sz);
1522 if (!(env->me_flags & MDB_NOMEMINIT)) {
1523 memset((char *)ret + off, 0, psize);
1527 txn->mt_flags |= MDB_TXN_ERROR;
1531 /** Free a single page.
1532 * Saves single pages to a list, for future reuse.
1533 * (This is not used for multi-page overflow pages.)
1536 mdb_page_free(MDB_env *env, MDB_page *mp)
1538 mp->mp_next = env->me_dpages;
1539 VGMEMP_FREE(env, mp);
1540 env->me_dpages = mp;
1543 /** Free a dirty page */
1545 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1547 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1548 mdb_page_free(env, dp);
1550 /* large pages just get freed directly */
1551 VGMEMP_FREE(env, dp);
1556 /** Return all dirty pages to dpage list */
1558 mdb_dlist_free(MDB_txn *txn)
1560 MDB_env *env = txn->mt_env;
1561 MDB_ID2L dl = txn->mt_u.dirty_list;
1562 unsigned i, n = dl[0].mid;
1564 for (i = 1; i <= n; i++) {
1565 mdb_dpage_free(env, dl[i].mptr);
1570 /** Loosen or free a single page.
1571 * Saves single pages to a list for future reuse
1572 * in this same txn. It has been pulled from the freeDB
1573 * and already resides on the dirty list, but has been
1574 * deleted. Use these pages first before pulling again
1577 * If the page wasn't dirtied in this txn, just add it
1578 * to this txn's free list.
1581 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1584 pgno_t pgno = mp->mp_pgno;
1586 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1587 if (mc->mc_txn->mt_parent) {
1588 MDB_ID2 *dl = mc->mc_txn->mt_u.dirty_list;
1589 /* If txn has a parent, make sure the page is in our
1593 unsigned x = mdb_mid2l_search(dl, pgno);
1594 if (x <= dl[0].mid && dl[x].mid == pgno) {
1595 if (mp != dl[x].mptr) { /* bad cursor? */
1596 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1597 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
1598 return MDB_CORRUPTED;
1605 /* no parent txn, so it's just ours */
1610 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1612 NEXT_LOOSE_PAGE(mp) = mc->mc_txn->mt_loose_pgs;
1613 mc->mc_txn->mt_loose_pgs = mp;
1614 mp->mp_flags |= P_LOOSE;
1616 int rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, pgno);
1624 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1625 * @param[in] mc A cursor handle for the current operation.
1626 * @param[in] pflags Flags of the pages to update:
1627 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1628 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1629 * @return 0 on success, non-zero on failure.
1632 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1634 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1635 MDB_txn *txn = mc->mc_txn;
1641 int rc = MDB_SUCCESS, level;
1643 /* Mark pages seen by cursors */
1644 if (mc->mc_flags & C_UNTRACK)
1645 mc = NULL; /* will find mc in mt_cursors */
1646 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1647 for (; mc; mc=mc->mc_next) {
1648 if (!(mc->mc_flags & C_INITIALIZED))
1650 for (m3 = mc;; m3 = &mx->mx_cursor) {
1652 for (j=0; j<m3->mc_snum; j++) {
1654 if ((mp->mp_flags & Mask) == pflags)
1655 mp->mp_flags ^= P_KEEP;
1657 mx = m3->mc_xcursor;
1658 /* Proceed to mx if it is at a sub-database */
1659 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1661 if (! (mp && (mp->mp_flags & P_LEAF)))
1663 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1664 if (!(leaf->mn_flags & F_SUBDATA))
1673 /* Mark dirty root pages */
1674 for (i=0; i<txn->mt_numdbs; i++) {
1675 if (txn->mt_dbflags[i] & DB_DIRTY) {
1676 pgno_t pgno = txn->mt_dbs[i].md_root;
1677 if (pgno == P_INVALID)
1679 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1681 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1682 dp->mp_flags ^= P_KEEP;
1690 static int mdb_page_flush(MDB_txn *txn, int keep);
1692 /** Spill pages from the dirty list back to disk.
1693 * This is intended to prevent running into #MDB_TXN_FULL situations,
1694 * but note that they may still occur in a few cases:
1695 * 1) our estimate of the txn size could be too small. Currently this
1696 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1697 * 2) child txns may run out of space if their parents dirtied a
1698 * lot of pages and never spilled them. TODO: we probably should do
1699 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1700 * the parent's dirty_room is below a given threshold.
1702 * Otherwise, if not using nested txns, it is expected that apps will
1703 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1704 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1705 * If the txn never references them again, they can be left alone.
1706 * If the txn only reads them, they can be used without any fuss.
1707 * If the txn writes them again, they can be dirtied immediately without
1708 * going thru all of the work of #mdb_page_touch(). Such references are
1709 * handled by #mdb_page_unspill().
1711 * Also note, we never spill DB root pages, nor pages of active cursors,
1712 * because we'll need these back again soon anyway. And in nested txns,
1713 * we can't spill a page in a child txn if it was already spilled in a
1714 * parent txn. That would alter the parent txns' data even though
1715 * the child hasn't committed yet, and we'd have no way to undo it if
1716 * the child aborted.
1718 * @param[in] m0 cursor A cursor handle identifying the transaction and
1719 * database for which we are checking space.
1720 * @param[in] key For a put operation, the key being stored.
1721 * @param[in] data For a put operation, the data being stored.
1722 * @return 0 on success, non-zero on failure.
1725 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1727 MDB_txn *txn = m0->mc_txn;
1729 MDB_ID2L dl = txn->mt_u.dirty_list;
1730 unsigned int i, j, need;
1733 if (m0->mc_flags & C_SUB)
1736 /* Estimate how much space this op will take */
1737 i = m0->mc_db->md_depth;
1738 /* Named DBs also dirty the main DB */
1739 if (m0->mc_dbi > MAIN_DBI)
1740 i += txn->mt_dbs[MAIN_DBI].md_depth;
1741 /* For puts, roughly factor in the key+data size */
1743 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1744 i += i; /* double it for good measure */
1747 if (txn->mt_dirty_room > i)
1750 if (!txn->mt_spill_pgs) {
1751 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1752 if (!txn->mt_spill_pgs)
1755 /* purge deleted slots */
1756 MDB_IDL sl = txn->mt_spill_pgs;
1757 unsigned int num = sl[0];
1759 for (i=1; i<=num; i++) {
1766 /* Preserve pages which may soon be dirtied again */
1767 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1770 /* Less aggressive spill - we originally spilled the entire dirty list,
1771 * with a few exceptions for cursor pages and DB root pages. But this
1772 * turns out to be a lot of wasted effort because in a large txn many
1773 * of those pages will need to be used again. So now we spill only 1/8th
1774 * of the dirty pages. Testing revealed this to be a good tradeoff,
1775 * better than 1/2, 1/4, or 1/10.
1777 if (need < MDB_IDL_UM_MAX / 8)
1778 need = MDB_IDL_UM_MAX / 8;
1780 /* Save the page IDs of all the pages we're flushing */
1781 /* flush from the tail forward, this saves a lot of shifting later on. */
1782 for (i=dl[0].mid; i && need; i--) {
1783 MDB_ID pn = dl[i].mid << 1;
1785 if (dp->mp_flags & (P_LOOSE|P_KEEP))
1787 /* Can't spill twice, make sure it's not already in a parent's
1790 if (txn->mt_parent) {
1792 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1793 if (tx2->mt_spill_pgs) {
1794 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1795 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1796 dp->mp_flags |= P_KEEP;
1804 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1808 mdb_midl_sort(txn->mt_spill_pgs);
1810 /* Flush the spilled part of dirty list */
1811 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1814 /* Reset any dirty pages we kept that page_flush didn't see */
1815 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1818 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1822 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1824 mdb_find_oldest(MDB_txn *txn)
1827 txnid_t mr, oldest = txn->mt_txnid - 1;
1828 if (txn->mt_env->me_txns) {
1829 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1830 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1841 /** Add a page to the txn's dirty list */
1843 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1846 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
1848 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1849 insert = mdb_mid2l_append;
1851 insert = mdb_mid2l_insert;
1853 mid.mid = mp->mp_pgno;
1855 rc = insert(txn->mt_u.dirty_list, &mid);
1856 mdb_tassert(txn, rc == 0);
1857 txn->mt_dirty_room--;
1860 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1861 * me_pghead and mt_next_pgno.
1863 * If there are free pages available from older transactions, they
1864 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1865 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1866 * and move me_pglast to say which records were consumed. Only this
1867 * function can create me_pghead and move me_pglast/mt_next_pgno.
1868 * @param[in] mc cursor A cursor handle identifying the transaction and
1869 * database for which we are allocating.
1870 * @param[in] num the number of pages to allocate.
1871 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1872 * will always be satisfied by a single contiguous chunk of memory.
1873 * @return 0 on success, non-zero on failure.
1876 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1878 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1879 /* Get at most <Max_retries> more freeDB records once me_pghead
1880 * has enough pages. If not enough, use new pages from the map.
1881 * If <Paranoid> and mc is updating the freeDB, only get new
1882 * records if me_pghead is empty. Then the freelist cannot play
1883 * catch-up with itself by growing while trying to save it.
1885 enum { Paranoid = 1, Max_retries = 500 };
1887 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1889 int rc, retry = num * 20;
1890 MDB_txn *txn = mc->mc_txn;
1891 MDB_env *env = txn->mt_env;
1892 pgno_t pgno, *mop = env->me_pghead;
1893 unsigned i, j, k, mop_len = mop ? mop[0] : 0, n2 = num-1;
1895 txnid_t oldest = 0, last;
1899 /* If there are any loose pages, just use them */
1900 if (num == 1 && txn->mt_loose_pgs) {
1901 np = txn->mt_loose_pgs;
1902 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
1903 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
1911 /* If our dirty list is already full, we can't do anything */
1912 if (txn->mt_dirty_room == 0) {
1917 for (op = MDB_FIRST;; op = MDB_NEXT) {
1920 pgno_t *idl, old_id, new_id;
1922 /* Seek a big enough contiguous page range. Prefer
1923 * pages at the tail, just truncating the list.
1929 if (mop[i-n2] == pgno+n2)
1936 if (op == MDB_FIRST) { /* 1st iteration */
1937 /* Prepare to fetch more and coalesce */
1938 oldest = mdb_find_oldest(txn);
1939 last = env->me_pglast;
1940 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1943 key.mv_data = &last; /* will look up last+1 */
1944 key.mv_size = sizeof(last);
1946 if (Paranoid && mc->mc_dbi == FREE_DBI)
1949 if (Paranoid && retry < 0 && mop_len)
1953 /* Do not fetch more if the record will be too recent */
1956 rc = mdb_cursor_get(&m2, &key, NULL, op);
1958 if (rc == MDB_NOTFOUND)
1962 last = *(txnid_t*)key.mv_data;
1965 np = m2.mc_pg[m2.mc_top];
1966 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1967 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1970 idl = (MDB_ID *) data.mv_data;
1973 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
1978 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1980 mop = env->me_pghead;
1982 env->me_pglast = last;
1984 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
1985 last, txn->mt_dbs[FREE_DBI].md_root, i));
1987 DPRINTF(("IDL %"Z"u", idl[k]));
1989 /* Merge in descending sorted order */
1992 mop[0] = (pgno_t)-1;
1996 for (; old_id < new_id; old_id = mop[--j])
2003 /* Use new pages from the map when nothing suitable in the freeDB */
2005 pgno = txn->mt_next_pgno;
2006 if (pgno + num >= env->me_maxpg) {
2007 DPUTS("DB size maxed out");
2013 if (env->me_flags & MDB_WRITEMAP) {
2014 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2016 if (!(np = mdb_page_malloc(txn, num))) {
2022 mop[0] = mop_len -= num;
2023 /* Move any stragglers down */
2024 for (j = i-num; j < mop_len; )
2025 mop[++j] = mop[++i];
2027 txn->mt_next_pgno = pgno + num;
2030 mdb_page_dirty(txn, np);
2036 txn->mt_flags |= MDB_TXN_ERROR;
2040 /** Copy the used portions of a non-overflow page.
2041 * @param[in] dst page to copy into
2042 * @param[in] src page to copy from
2043 * @param[in] psize size of a page
2046 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2048 enum { Align = sizeof(pgno_t) };
2049 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2051 /* If page isn't full, just copy the used portion. Adjust
2052 * alignment so memcpy may copy words instead of bytes.
2054 if ((unused &= -Align) && !IS_LEAF2(src)) {
2055 upper = (upper + PAGEBASE) & -Align;
2056 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2057 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2060 memcpy(dst, src, psize - unused);
2064 /** Pull a page off the txn's spill list, if present.
2065 * If a page being referenced was spilled to disk in this txn, bring
2066 * it back and make it dirty/writable again.
2067 * @param[in] txn the transaction handle.
2068 * @param[in] mp the page being referenced. It must not be dirty.
2069 * @param[out] ret the writable page, if any. ret is unchanged if
2070 * mp wasn't spilled.
2073 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2075 MDB_env *env = txn->mt_env;
2078 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2080 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2081 if (!tx2->mt_spill_pgs)
2083 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2084 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2087 if (txn->mt_dirty_room == 0)
2088 return MDB_TXN_FULL;
2089 if (IS_OVERFLOW(mp))
2093 if (env->me_flags & MDB_WRITEMAP) {
2096 np = mdb_page_malloc(txn, num);
2100 memcpy(np, mp, num * env->me_psize);
2102 mdb_page_copy(np, mp, env->me_psize);
2105 /* If in current txn, this page is no longer spilled.
2106 * If it happens to be the last page, truncate the spill list.
2107 * Otherwise mark it as deleted by setting the LSB.
2109 if (x == txn->mt_spill_pgs[0])
2110 txn->mt_spill_pgs[0]--;
2112 txn->mt_spill_pgs[x] |= 1;
2113 } /* otherwise, if belonging to a parent txn, the
2114 * page remains spilled until child commits
2117 mdb_page_dirty(txn, np);
2118 np->mp_flags |= P_DIRTY;
2126 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2127 * @param[in] mc cursor pointing to the page to be touched
2128 * @return 0 on success, non-zero on failure.
2131 mdb_page_touch(MDB_cursor *mc)
2133 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2134 MDB_txn *txn = mc->mc_txn;
2135 MDB_cursor *m2, *m3;
2139 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2140 if (txn->mt_flags & MDB_TXN_SPILLS) {
2142 rc = mdb_page_unspill(txn, mp, &np);
2148 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2149 (rc = mdb_page_alloc(mc, 1, &np)))
2152 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2153 mp->mp_pgno, pgno));
2154 mdb_cassert(mc, mp->mp_pgno != pgno);
2155 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2156 /* Update the parent page, if any, to point to the new page */
2158 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2159 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2160 SETPGNO(node, pgno);
2162 mc->mc_db->md_root = pgno;
2164 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2165 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2167 /* If txn has a parent, make sure the page is in our
2171 unsigned x = mdb_mid2l_search(dl, pgno);
2172 if (x <= dl[0].mid && dl[x].mid == pgno) {
2173 if (mp != dl[x].mptr) { /* bad cursor? */
2174 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2175 txn->mt_flags |= MDB_TXN_ERROR;
2176 return MDB_CORRUPTED;
2181 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2183 np = mdb_page_malloc(txn, 1);
2188 rc = mdb_mid2l_insert(dl, &mid);
2189 mdb_cassert(mc, rc == 0);
2194 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2196 np->mp_flags |= P_DIRTY;
2199 /* Adjust cursors pointing to mp */
2200 mc->mc_pg[mc->mc_top] = np;
2201 m2 = txn->mt_cursors[mc->mc_dbi];
2202 if (mc->mc_flags & C_SUB) {
2203 for (; m2; m2=m2->mc_next) {
2204 m3 = &m2->mc_xcursor->mx_cursor;
2205 if (m3->mc_snum < mc->mc_snum) continue;
2206 if (m3->mc_pg[mc->mc_top] == mp)
2207 m3->mc_pg[mc->mc_top] = np;
2210 for (; m2; m2=m2->mc_next) {
2211 if (m2->mc_snum < mc->mc_snum) continue;
2212 if (m2->mc_pg[mc->mc_top] == mp) {
2213 m2->mc_pg[mc->mc_top] = np;
2214 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2216 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2218 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2219 if (!(leaf->mn_flags & F_SUBDATA))
2220 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2228 txn->mt_flags |= MDB_TXN_ERROR;
2233 mdb_env_sync(MDB_env *env, int force)
2236 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2237 if (env->me_flags & MDB_WRITEMAP) {
2238 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2239 ? MS_ASYNC : MS_SYNC;
2240 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2243 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2247 if (MDB_FDATASYNC(env->me_fd))
2254 /** Back up parent txn's cursors, then grab the originals for tracking */
2256 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2258 MDB_cursor *mc, *bk;
2263 for (i = src->mt_numdbs; --i >= 0; ) {
2264 if ((mc = src->mt_cursors[i]) != NULL) {
2265 size = sizeof(MDB_cursor);
2267 size += sizeof(MDB_xcursor);
2268 for (; mc; mc = bk->mc_next) {
2274 mc->mc_db = &dst->mt_dbs[i];
2275 /* Kill pointers into src - and dst to reduce abuse: The
2276 * user may not use mc until dst ends. Otherwise we'd...
2278 mc->mc_txn = NULL; /* ...set this to dst */
2279 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2280 if ((mx = mc->mc_xcursor) != NULL) {
2281 *(MDB_xcursor *)(bk+1) = *mx;
2282 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2284 mc->mc_next = dst->mt_cursors[i];
2285 dst->mt_cursors[i] = mc;
2292 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2293 * @param[in] txn the transaction handle.
2294 * @param[in] merge true to keep changes to parent cursors, false to revert.
2295 * @return 0 on success, non-zero on failure.
2298 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2300 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2304 for (i = txn->mt_numdbs; --i >= 0; ) {
2305 for (mc = cursors[i]; mc; mc = next) {
2307 if ((bk = mc->mc_backup) != NULL) {
2309 /* Commit changes to parent txn */
2310 mc->mc_next = bk->mc_next;
2311 mc->mc_backup = bk->mc_backup;
2312 mc->mc_txn = bk->mc_txn;
2313 mc->mc_db = bk->mc_db;
2314 mc->mc_dbflag = bk->mc_dbflag;
2315 if ((mx = mc->mc_xcursor) != NULL)
2316 mx->mx_cursor.mc_txn = bk->mc_txn;
2318 /* Abort nested txn */
2320 if ((mx = mc->mc_xcursor) != NULL)
2321 *mx = *(MDB_xcursor *)(bk+1);
2325 /* Only malloced cursors are permanently tracked. */
2333 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2336 mdb_txn_reset0(MDB_txn *txn, const char *act);
2338 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2344 Pidset = F_SETLK, Pidcheck = F_GETLK
2348 /** Set or check a pid lock. Set returns 0 on success.
2349 * Check returns 0 if the process is certainly dead, nonzero if it may
2350 * be alive (the lock exists or an error happened so we do not know).
2352 * On Windows Pidset is a no-op, we merely check for the existence
2353 * of the process with the given pid. On POSIX we use a single byte
2354 * lock on the lockfile, set at an offset equal to the pid.
2357 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2359 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2362 if (op == Pidcheck) {
2363 h = OpenProcess(env->me_pidquery, FALSE, pid);
2364 /* No documented "no such process" code, but other program use this: */
2366 return ErrCode() != ERROR_INVALID_PARAMETER;
2367 /* A process exists until all handles to it close. Has it exited? */
2368 ret = WaitForSingleObject(h, 0) != 0;
2375 struct flock lock_info;
2376 memset(&lock_info, 0, sizeof(lock_info));
2377 lock_info.l_type = F_WRLCK;
2378 lock_info.l_whence = SEEK_SET;
2379 lock_info.l_start = pid;
2380 lock_info.l_len = 1;
2381 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2382 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2384 } else if ((rc = ErrCode()) == EINTR) {
2392 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2393 * @param[in] txn the transaction handle to initialize
2394 * @return 0 on success, non-zero on failure.
2397 mdb_txn_renew0(MDB_txn *txn)
2399 MDB_env *env = txn->mt_env;
2400 MDB_txninfo *ti = env->me_txns;
2404 int rc, new_notls = 0;
2407 txn->mt_numdbs = env->me_numdbs;
2408 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2410 if (txn->mt_flags & MDB_TXN_RDONLY) {
2412 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2413 txn->mt_txnid = meta->mm_txnid;
2414 txn->mt_u.reader = NULL;
2416 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2417 pthread_getspecific(env->me_txkey);
2419 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2420 return MDB_BAD_RSLOT;
2422 MDB_PID_T pid = env->me_pid;
2423 MDB_THR_T tid = pthread_self();
2425 if (!env->me_live_reader) {
2426 rc = mdb_reader_pid(env, Pidset, pid);
2429 env->me_live_reader = 1;
2433 nr = ti->mti_numreaders;
2434 for (i=0; i<nr; i++)
2435 if (ti->mti_readers[i].mr_pid == 0)
2437 if (i == env->me_maxreaders) {
2438 UNLOCK_MUTEX_R(env);
2439 return MDB_READERS_FULL;
2441 ti->mti_readers[i].mr_pid = pid;
2442 ti->mti_readers[i].mr_tid = tid;
2444 ti->mti_numreaders = ++nr;
2445 /* Save numreaders for un-mutexed mdb_env_close() */
2446 env->me_numreaders = nr;
2447 UNLOCK_MUTEX_R(env);
2449 r = &ti->mti_readers[i];
2450 new_notls = (env->me_flags & MDB_NOTLS);
2451 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2456 txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
2457 txn->mt_u.reader = r;
2458 meta = env->me_metas[txn->mt_txnid & 1];
2464 txn->mt_txnid = ti->mti_txnid;
2465 meta = env->me_metas[txn->mt_txnid & 1];
2467 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2468 txn->mt_txnid = meta->mm_txnid;
2472 if (txn->mt_txnid == mdb_debug_start)
2475 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2476 txn->mt_u.dirty_list = env->me_dirty_list;
2477 txn->mt_u.dirty_list[0].mid = 0;
2478 txn->mt_free_pgs = env->me_free_pgs;
2479 txn->mt_free_pgs[0] = 0;
2480 txn->mt_spill_pgs = NULL;
2484 /* Copy the DB info and flags */
2485 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2487 /* Moved to here to avoid a data race in read TXNs */
2488 txn->mt_next_pgno = meta->mm_last_pg+1;
2490 for (i=2; i<txn->mt_numdbs; i++) {
2491 x = env->me_dbflags[i];
2492 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2493 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2495 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2497 /* If we didn't ask for a resize, but the size changed, fail */
2498 if (!(env->me_flags & MDB_RESIZING)
2499 && env->me_mapsize != meta->mm_mapsize) {
2500 mdb_txn_reset0(txn, "renew0-mapfail");
2502 txn->mt_u.reader->mr_pid = 0;
2503 txn->mt_u.reader = NULL;
2505 return MDB_MAP_RESIZED;
2512 mdb_txn_renew(MDB_txn *txn)
2516 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2519 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2520 DPUTS("environment had fatal error, must shutdown!");
2524 rc = mdb_txn_renew0(txn);
2525 if (rc == MDB_SUCCESS) {
2526 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2527 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2528 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2534 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2538 int rc, size, tsize = sizeof(MDB_txn);
2540 if (env->me_flags & MDB_FATAL_ERROR) {
2541 DPUTS("environment had fatal error, must shutdown!");
2544 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2547 /* Nested transactions: Max 1 child, write txns only, no writemap */
2548 if (parent->mt_child ||
2549 (flags & MDB_RDONLY) ||
2550 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2551 (env->me_flags & MDB_WRITEMAP))
2553 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2555 tsize = sizeof(MDB_ntxn);
2557 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2558 if (!(flags & MDB_RDONLY))
2559 size += env->me_maxdbs * sizeof(MDB_cursor *);
2561 if ((txn = calloc(1, size)) == NULL) {
2562 DPRINTF(("calloc: %s", strerror(ErrCode())));
2565 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2566 if (flags & MDB_RDONLY) {
2567 txn->mt_flags |= MDB_TXN_RDONLY;
2568 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2570 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2571 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2577 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2578 if (!txn->mt_u.dirty_list ||
2579 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2581 free(txn->mt_u.dirty_list);
2585 txn->mt_txnid = parent->mt_txnid;
2586 txn->mt_dirty_room = parent->mt_dirty_room;
2587 txn->mt_u.dirty_list[0].mid = 0;
2588 txn->mt_spill_pgs = NULL;
2589 txn->mt_next_pgno = parent->mt_next_pgno;
2590 parent->mt_child = txn;
2591 txn->mt_parent = parent;
2592 txn->mt_numdbs = parent->mt_numdbs;
2593 txn->mt_flags = parent->mt_flags;
2594 txn->mt_dbxs = parent->mt_dbxs;
2595 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2596 /* Copy parent's mt_dbflags, but clear DB_NEW */
2597 for (i=0; i<txn->mt_numdbs; i++)
2598 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2600 ntxn = (MDB_ntxn *)txn;
2601 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2602 if (env->me_pghead) {
2603 size = MDB_IDL_SIZEOF(env->me_pghead);
2604 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2606 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2611 rc = mdb_cursor_shadow(parent, txn);
2613 mdb_txn_reset0(txn, "beginchild-fail");
2615 rc = mdb_txn_renew0(txn);
2621 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2622 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2623 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2630 mdb_txn_env(MDB_txn *txn)
2632 if(!txn) return NULL;
2636 /** Export or close DBI handles opened in this txn. */
2638 mdb_dbis_update(MDB_txn *txn, int keep)
2641 MDB_dbi n = txn->mt_numdbs;
2642 MDB_env *env = txn->mt_env;
2643 unsigned char *tdbflags = txn->mt_dbflags;
2645 for (i = n; --i >= 2;) {
2646 if (tdbflags[i] & DB_NEW) {
2648 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2650 char *ptr = env->me_dbxs[i].md_name.mv_data;
2651 env->me_dbxs[i].md_name.mv_data = NULL;
2652 env->me_dbxs[i].md_name.mv_size = 0;
2653 env->me_dbflags[i] = 0;
2658 if (keep && env->me_numdbs < n)
2662 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2663 * May be called twice for readonly txns: First reset it, then abort.
2664 * @param[in] txn the transaction handle to reset
2665 * @param[in] act why the transaction is being reset
2668 mdb_txn_reset0(MDB_txn *txn, const char *act)
2670 MDB_env *env = txn->mt_env;
2672 /* Close any DBI handles opened in this txn */
2673 mdb_dbis_update(txn, 0);
2675 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2676 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2677 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2679 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2680 if (txn->mt_u.reader) {
2681 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2682 if (!(env->me_flags & MDB_NOTLS))
2683 txn->mt_u.reader = NULL; /* txn does not own reader */
2685 txn->mt_numdbs = 0; /* close nothing if called again */
2686 txn->mt_dbxs = NULL; /* mark txn as reset */
2688 mdb_cursors_close(txn, 0);
2690 if (!(env->me_flags & MDB_WRITEMAP)) {
2691 mdb_dlist_free(txn);
2693 mdb_midl_free(env->me_pghead);
2695 if (txn->mt_parent) {
2696 txn->mt_parent->mt_child = NULL;
2697 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2698 mdb_midl_free(txn->mt_free_pgs);
2699 mdb_midl_free(txn->mt_spill_pgs);
2700 free(txn->mt_u.dirty_list);
2704 if (mdb_midl_shrink(&txn->mt_free_pgs))
2705 env->me_free_pgs = txn->mt_free_pgs;
2706 env->me_pghead = NULL;
2710 /* The writer mutex was locked in mdb_txn_begin. */
2712 UNLOCK_MUTEX_W(env);
2717 mdb_txn_reset(MDB_txn *txn)
2722 /* This call is only valid for read-only txns */
2723 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2726 mdb_txn_reset0(txn, "reset");
2730 mdb_txn_abort(MDB_txn *txn)
2736 mdb_txn_abort(txn->mt_child);
2738 mdb_txn_reset0(txn, "abort");
2739 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2740 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2741 txn->mt_u.reader->mr_pid = 0;
2746 /** Save the freelist as of this transaction to the freeDB.
2747 * This changes the freelist. Keep trying until it stabilizes.
2750 mdb_freelist_save(MDB_txn *txn)
2752 /* env->me_pghead[] can grow and shrink during this call.
2753 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2754 * Page numbers cannot disappear from txn->mt_free_pgs[].
2757 MDB_env *env = txn->mt_env;
2758 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2759 txnid_t pglast = 0, head_id = 0;
2760 pgno_t freecnt = 0, *free_pgs, *mop;
2761 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2763 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2765 if (env->me_pghead) {
2766 /* Make sure first page of freeDB is touched and on freelist */
2767 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2768 if (rc && rc != MDB_NOTFOUND)
2772 /* Dispose of loose pages. Usually they will have all
2773 * been used up by the time we get here.
2775 if (txn->mt_loose_pgs) {
2776 MDB_page *mp = txn->mt_loose_pgs;
2777 /* Just return them to freeDB */
2778 if (env->me_pghead) {
2780 mop = env->me_pghead;
2781 for (; mp; mp = NEXT_LOOSE_PAGE(mp)) {
2782 pgno_t pg = mp->mp_pgno;
2784 for (i = mop[0]; i && mop[i] < pg; i--)
2790 /* Oh well, they were wasted. Put on freelist */
2791 for (; mp; mp = NEXT_LOOSE_PAGE(mp)) {
2792 mdb_midl_append(&txn->mt_free_pgs, mp->mp_pgno);
2795 txn->mt_loose_pgs = NULL;
2798 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2799 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2800 ? SSIZE_MAX : maxfree_1pg;
2803 /* Come back here after each Put() in case freelist changed */
2808 /* If using records from freeDB which we have not yet
2809 * deleted, delete them and any we reserved for me_pghead.
2811 while (pglast < env->me_pglast) {
2812 rc = mdb_cursor_first(&mc, &key, NULL);
2815 pglast = head_id = *(txnid_t *)key.mv_data;
2816 total_room = head_room = 0;
2817 mdb_tassert(txn, pglast <= env->me_pglast);
2818 rc = mdb_cursor_del(&mc, 0);
2823 /* Save the IDL of pages freed by this txn, to a single record */
2824 if (freecnt < txn->mt_free_pgs[0]) {
2826 /* Make sure last page of freeDB is touched and on freelist */
2827 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2828 if (rc && rc != MDB_NOTFOUND)
2831 free_pgs = txn->mt_free_pgs;
2832 /* Write to last page of freeDB */
2833 key.mv_size = sizeof(txn->mt_txnid);
2834 key.mv_data = &txn->mt_txnid;
2836 freecnt = free_pgs[0];
2837 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2838 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2841 /* Retry if mt_free_pgs[] grew during the Put() */
2842 free_pgs = txn->mt_free_pgs;
2843 } while (freecnt < free_pgs[0]);
2844 mdb_midl_sort(free_pgs);
2845 memcpy(data.mv_data, free_pgs, data.mv_size);
2848 unsigned int i = free_pgs[0];
2849 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2850 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2852 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2858 mop = env->me_pghead;
2859 mop_len = mop ? mop[0] : 0;
2861 /* Reserve records for me_pghead[]. Split it if multi-page,
2862 * to avoid searching freeDB for a page range. Use keys in
2863 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2865 if (total_room >= mop_len) {
2866 if (total_room == mop_len || --more < 0)
2868 } else if (head_room >= maxfree_1pg && head_id > 1) {
2869 /* Keep current record (overflow page), add a new one */
2873 /* (Re)write {key = head_id, IDL length = head_room} */
2874 total_room -= head_room;
2875 head_room = mop_len - total_room;
2876 if (head_room > maxfree_1pg && head_id > 1) {
2877 /* Overflow multi-page for part of me_pghead */
2878 head_room /= head_id; /* amortize page sizes */
2879 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2880 } else if (head_room < 0) {
2881 /* Rare case, not bothering to delete this record */
2884 key.mv_size = sizeof(head_id);
2885 key.mv_data = &head_id;
2886 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2887 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2890 /* IDL is initially empty, zero out at least the length */
2891 pgs = (pgno_t *)data.mv_data;
2892 j = head_room > clean_limit ? head_room : 0;
2896 total_room += head_room;
2899 /* Fill in the reserved me_pghead records */
2905 rc = mdb_cursor_first(&mc, &key, &data);
2906 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2907 txnid_t id = *(txnid_t *)key.mv_data;
2908 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2911 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
2913 if (len > mop_len) {
2915 data.mv_size = (len + 1) * sizeof(MDB_ID);
2917 data.mv_data = mop -= len;
2920 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
2922 if (rc || !(mop_len -= len))
2929 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
2930 * @param[in] txn the transaction that's being committed
2931 * @param[in] keep number of initial pages in dirty_list to keep dirty.
2932 * @return 0 on success, non-zero on failure.
2935 mdb_page_flush(MDB_txn *txn, int keep)
2937 MDB_env *env = txn->mt_env;
2938 MDB_ID2L dl = txn->mt_u.dirty_list;
2939 unsigned psize = env->me_psize, j;
2940 int i, pagecount = dl[0].mid, rc;
2941 size_t size = 0, pos = 0;
2943 MDB_page *dp = NULL;
2947 struct iovec iov[MDB_COMMIT_PAGES];
2948 ssize_t wpos = 0, wsize = 0, wres;
2949 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
2955 if (env->me_flags & MDB_WRITEMAP) {
2956 /* Clear dirty flags */
2957 while (++i <= pagecount) {
2959 /* Don't flush this page yet */
2960 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
2961 dp->mp_flags &= ~P_KEEP;
2965 dp->mp_flags &= ~P_DIRTY;
2970 /* Write the pages */
2972 if (++i <= pagecount) {
2974 /* Don't flush this page yet */
2975 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
2976 dp->mp_flags &= ~P_KEEP;
2981 /* clear dirty flag */
2982 dp->mp_flags &= ~P_DIRTY;
2985 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
2990 /* Windows actually supports scatter/gather I/O, but only on
2991 * unbuffered file handles. Since we're relying on the OS page
2992 * cache for all our data, that's self-defeating. So we just
2993 * write pages one at a time. We use the ov structure to set
2994 * the write offset, to at least save the overhead of a Seek
2997 DPRINTF(("committing page %"Z"u", pgno));
2998 memset(&ov, 0, sizeof(ov));
2999 ov.Offset = pos & 0xffffffff;
3000 ov.OffsetHigh = pos >> 16 >> 16;
3001 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3003 DPRINTF(("WriteFile: %d", rc));
3007 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3008 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3010 /* Write previous page(s) */
3011 #ifdef MDB_USE_PWRITEV
3012 wres = pwritev(env->me_fd, iov, n, wpos);
3015 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3017 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3019 DPRINTF(("lseek: %s", strerror(rc)));
3022 wres = writev(env->me_fd, iov, n);
3025 if (wres != wsize) {
3028 DPRINTF(("Write error: %s", strerror(rc)));
3030 rc = EIO; /* TODO: Use which error code? */
3031 DPUTS("short write, filesystem full?");
3042 DPRINTF(("committing page %"Z"u", pgno));
3043 next_pos = pos + size;
3044 iov[n].iov_len = size;
3045 iov[n].iov_base = (char *)dp;
3051 for (i = keep; ++i <= pagecount; ) {
3053 /* This is a page we skipped above */
3056 dl[j].mid = dp->mp_pgno;
3059 mdb_dpage_free(env, dp);
3064 txn->mt_dirty_room += i - j;
3070 mdb_txn_commit(MDB_txn *txn)
3076 if (txn == NULL || txn->mt_env == NULL)
3079 if (txn->mt_child) {
3080 rc = mdb_txn_commit(txn->mt_child);
3081 txn->mt_child = NULL;
3088 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3089 mdb_dbis_update(txn, 1);
3090 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
3095 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
3096 DPUTS("error flag is set, can't commit");
3098 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3103 if (txn->mt_parent) {
3104 MDB_txn *parent = txn->mt_parent;
3108 unsigned x, y, len, ps_len;
3110 /* Append our free list to parent's */
3111 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3114 mdb_midl_free(txn->mt_free_pgs);
3115 /* Failures after this must either undo the changes
3116 * to the parent or set MDB_TXN_ERROR in the parent.
3119 parent->mt_next_pgno = txn->mt_next_pgno;
3120 parent->mt_flags = txn->mt_flags;
3122 /* Merge our cursors into parent's and close them */
3123 mdb_cursors_close(txn, 1);
3125 /* Update parent's DB table. */
3126 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3127 parent->mt_numdbs = txn->mt_numdbs;
3128 parent->mt_dbflags[0] = txn->mt_dbflags[0];
3129 parent->mt_dbflags[1] = txn->mt_dbflags[1];
3130 for (i=2; i<txn->mt_numdbs; i++) {
3131 /* preserve parent's DB_NEW status */
3132 x = parent->mt_dbflags[i] & DB_NEW;
3133 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3136 dst = parent->mt_u.dirty_list;
3137 src = txn->mt_u.dirty_list;
3138 /* Remove anything in our dirty list from parent's spill list */
3139 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3141 pspill[0] = (pgno_t)-1;
3142 /* Mark our dirty pages as deleted in parent spill list */
3143 for (i=0, len=src[0].mid; ++i <= len; ) {
3144 MDB_ID pn = src[i].mid << 1;
3145 while (pn > pspill[x])
3147 if (pn == pspill[x]) {
3152 /* Squash deleted pagenums if we deleted any */
3153 for (x=y; ++x <= ps_len; )
3154 if (!(pspill[x] & 1))
3155 pspill[++y] = pspill[x];
3159 /* Find len = length of merging our dirty list with parent's */
3161 dst[0].mid = 0; /* simplify loops */
3162 if (parent->mt_parent) {
3163 len = x + src[0].mid;
3164 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3165 for (i = x; y && i; y--) {
3166 pgno_t yp = src[y].mid;
3167 while (yp < dst[i].mid)
3169 if (yp == dst[i].mid) {
3174 } else { /* Simplify the above for single-ancestor case */
3175 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3177 /* Merge our dirty list with parent's */
3179 for (i = len; y; dst[i--] = src[y--]) {
3180 pgno_t yp = src[y].mid;
3181 while (yp < dst[x].mid)
3182 dst[i--] = dst[x--];
3183 if (yp == dst[x].mid)
3184 free(dst[x--].mptr);
3186 mdb_tassert(txn, i == x);
3188 free(txn->mt_u.dirty_list);
3189 parent->mt_dirty_room = txn->mt_dirty_room;
3190 if (txn->mt_spill_pgs) {
3191 if (parent->mt_spill_pgs) {
3192 /* TODO: Prevent failure here, so parent does not fail */
3193 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3195 parent->mt_flags |= MDB_TXN_ERROR;
3196 mdb_midl_free(txn->mt_spill_pgs);
3197 mdb_midl_sort(parent->mt_spill_pgs);
3199 parent->mt_spill_pgs = txn->mt_spill_pgs;
3203 /* Append our loose page list to parent's */
3204 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(lp))
3206 *lp = txn->mt_loose_pgs;
3208 parent->mt_child = NULL;
3209 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3214 if (txn != env->me_txn) {
3215 DPUTS("attempt to commit unknown transaction");
3220 mdb_cursors_close(txn, 0);
3222 if (!txn->mt_u.dirty_list[0].mid &&
3223 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS))) {
3224 if ((env->me_flags & MDB_RESIZING)
3225 && (rc = mdb_env_write_meta(txn))) {
3231 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3232 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3234 /* Update DB root pointers */
3235 if (txn->mt_numdbs > 2) {
3239 data.mv_size = sizeof(MDB_db);
3241 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3242 for (i = 2; i < txn->mt_numdbs; i++) {
3243 if (txn->mt_dbflags[i] & DB_DIRTY) {
3244 data.mv_data = &txn->mt_dbs[i];
3245 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
3252 rc = mdb_freelist_save(txn);
3256 mdb_midl_free(env->me_pghead);
3257 env->me_pghead = NULL;
3258 if (mdb_midl_shrink(&txn->mt_free_pgs))
3259 env->me_free_pgs = txn->mt_free_pgs;
3265 if ((rc = mdb_page_flush(txn, 0)) ||
3266 (rc = mdb_env_sync(env, 0)) ||
3267 (rc = mdb_env_write_meta(txn)))
3273 mdb_dbis_update(txn, 1);
3276 UNLOCK_MUTEX_W(env);
3286 /** Read the environment parameters of a DB environment before
3287 * mapping it into memory.
3288 * @param[in] env the environment handle
3289 * @param[out] meta address of where to store the meta information
3290 * @return 0 on success, non-zero on failure.
3293 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3299 enum { Size = sizeof(pbuf) };
3301 /* We don't know the page size yet, so use a minimum value.
3302 * Read both meta pages so we can use the latest one.
3305 for (i=off=0; i<2; i++, off = meta->mm_psize) {
3309 memset(&ov, 0, sizeof(ov));
3311 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3312 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3315 rc = pread(env->me_fd, &pbuf, Size, off);
3318 if (rc == 0 && off == 0)
3320 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3321 DPRINTF(("read: %s", mdb_strerror(rc)));
3325 p = (MDB_page *)&pbuf;
3327 if (!F_ISSET(p->mp_flags, P_META)) {
3328 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3333 if (m->mm_magic != MDB_MAGIC) {
3334 DPUTS("meta has invalid magic");
3338 if (m->mm_version != MDB_DATA_VERSION) {
3339 DPRINTF(("database is version %u, expected version %u",
3340 m->mm_version, MDB_DATA_VERSION));
3341 return MDB_VERSION_MISMATCH;
3344 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3351 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3353 meta->mm_magic = MDB_MAGIC;
3354 meta->mm_version = MDB_DATA_VERSION;
3355 meta->mm_mapsize = env->me_mapsize;
3356 meta->mm_psize = env->me_psize;
3357 meta->mm_last_pg = 1;
3358 meta->mm_flags = env->me_flags & 0xffff;
3359 meta->mm_flags |= MDB_INTEGERKEY;
3360 meta->mm_dbs[0].md_root = P_INVALID;
3361 meta->mm_dbs[1].md_root = P_INVALID;
3364 /** Write the environment parameters of a freshly created DB environment.
3365 * @param[in] env the environment handle
3366 * @param[out] meta address of where to store the meta information
3367 * @return 0 on success, non-zero on failure.
3370 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3378 memset(&ov, 0, sizeof(ov));
3379 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3381 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3384 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3385 len = pwrite(fd, ptr, size, pos); \
3386 rc = (len >= 0); } while(0)
3389 DPUTS("writing new meta page");
3391 psize = env->me_psize;
3393 mdb_env_init_meta0(env, meta);
3395 p = calloc(2, psize);
3397 p->mp_flags = P_META;
3398 *(MDB_meta *)METADATA(p) = *meta;
3400 q = (MDB_page *)((char *)p + psize);
3402 q->mp_flags = P_META;
3403 *(MDB_meta *)METADATA(q) = *meta;
3405 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3408 else if ((unsigned) len == psize * 2)
3416 /** Update the environment info to commit a transaction.
3417 * @param[in] txn the transaction that's being committed
3418 * @return 0 on success, non-zero on failure.
3421 mdb_env_write_meta(MDB_txn *txn)
3424 MDB_meta meta, metab, *mp;
3426 int rc, len, toggle;
3435 toggle = txn->mt_txnid & 1;
3436 DPRINTF(("writing meta page %d for root page %"Z"u",
3437 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3440 mp = env->me_metas[toggle];
3442 if (env->me_flags & MDB_WRITEMAP) {
3443 /* Persist any changes of mapsize config */
3444 if (env->me_flags & MDB_RESIZING) {
3445 mp->mm_mapsize = env->me_mapsize;
3446 env->me_flags ^= MDB_RESIZING;
3448 mp->mm_dbs[0] = txn->mt_dbs[0];
3449 mp->mm_dbs[1] = txn->mt_dbs[1];
3450 mp->mm_last_pg = txn->mt_next_pgno - 1;
3451 mp->mm_txnid = txn->mt_txnid;
3452 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3453 unsigned meta_size = env->me_psize;
3454 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3457 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3458 if (meta_size < env->me_os_psize)
3459 meta_size += meta_size;
3464 if (MDB_MSYNC(ptr, meta_size, rc)) {
3471 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3472 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3474 ptr = (char *)&meta;
3475 if (env->me_flags & MDB_RESIZING) {
3476 /* Persist any changes of mapsize config */
3477 meta.mm_mapsize = env->me_mapsize;
3478 off = offsetof(MDB_meta, mm_mapsize);
3479 env->me_flags ^= MDB_RESIZING;
3481 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
3483 len = sizeof(MDB_meta) - off;
3486 meta.mm_dbs[0] = txn->mt_dbs[0];
3487 meta.mm_dbs[1] = txn->mt_dbs[1];
3488 meta.mm_last_pg = txn->mt_next_pgno - 1;
3489 meta.mm_txnid = txn->mt_txnid;
3492 off += env->me_psize;
3495 /* Write to the SYNC fd */
3496 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3497 env->me_fd : env->me_mfd;
3500 memset(&ov, 0, sizeof(ov));
3502 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3506 rc = pwrite(mfd, ptr, len, off);
3509 rc = rc < 0 ? ErrCode() : EIO;
3510 DPUTS("write failed, disk error?");
3511 /* On a failure, the pagecache still contains the new data.
3512 * Write some old data back, to prevent it from being used.
3513 * Use the non-SYNC fd; we know it will fail anyway.
3515 meta.mm_last_pg = metab.mm_last_pg;
3516 meta.mm_txnid = metab.mm_txnid;
3518 memset(&ov, 0, sizeof(ov));
3520 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3522 r2 = pwrite(env->me_fd, ptr, len, off);
3523 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3526 env->me_flags |= MDB_FATAL_ERROR;
3530 /* Memory ordering issues are irrelevant; since the entire writer
3531 * is wrapped by wmutex, all of these changes will become visible
3532 * after the wmutex is unlocked. Since the DB is multi-version,
3533 * readers will get consistent data regardless of how fresh or
3534 * how stale their view of these values is.
3537 env->me_txns->mti_txnid = txn->mt_txnid;
3542 /** Check both meta pages to see which one is newer.
3543 * @param[in] env the environment handle
3544 * @return meta toggle (0 or 1).
3547 mdb_env_pick_meta(const MDB_env *env)
3549 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3553 mdb_env_create(MDB_env **env)
3557 e = calloc(1, sizeof(MDB_env));
3561 e->me_maxreaders = DEFAULT_READERS;
3562 e->me_maxdbs = e->me_numdbs = 2;
3563 e->me_fd = INVALID_HANDLE_VALUE;
3564 e->me_lfd = INVALID_HANDLE_VALUE;
3565 e->me_mfd = INVALID_HANDLE_VALUE;
3566 #ifdef MDB_USE_POSIX_SEM
3567 e->me_rmutex = SEM_FAILED;
3568 e->me_wmutex = SEM_FAILED;
3570 e->me_pid = getpid();
3571 GET_PAGESIZE(e->me_os_psize);
3572 VGMEMP_CREATE(e,0,0);
3578 mdb_env_map(MDB_env *env, void *addr, int newsize)
3581 unsigned int flags = env->me_flags;
3585 LONG sizelo, sizehi;
3588 if (flags & MDB_RDONLY) {
3593 msize = env->me_mapsize;
3594 sizelo = msize & 0xffffffff;
3595 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3598 /* Windows won't create mappings for zero length files.
3599 * Just allocate the maxsize right now.
3602 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3603 || !SetEndOfFile(env->me_fd)
3604 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3607 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3608 PAGE_READWRITE : PAGE_READONLY,
3609 sizehi, sizelo, NULL);
3612 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3613 FILE_MAP_WRITE : FILE_MAP_READ,
3615 rc = env->me_map ? 0 : ErrCode();
3620 int prot = PROT_READ;
3621 if (flags & MDB_WRITEMAP) {
3623 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3626 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3628 if (env->me_map == MAP_FAILED) {
3633 if (flags & MDB_NORDAHEAD) {
3634 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3636 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3638 #ifdef POSIX_MADV_RANDOM
3639 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3640 #endif /* POSIX_MADV_RANDOM */
3641 #endif /* MADV_RANDOM */
3645 /* Can happen because the address argument to mmap() is just a
3646 * hint. mmap() can pick another, e.g. if the range is in use.
3647 * The MAP_FIXED flag would prevent that, but then mmap could
3648 * instead unmap existing pages to make room for the new map.
3650 if (addr && env->me_map != addr)
3651 return EBUSY; /* TODO: Make a new MDB_* error code? */
3653 p = (MDB_page *)env->me_map;
3654 env->me_metas[0] = METADATA(p);
3655 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3661 mdb_env_set_mapsize(MDB_env *env, size_t size)
3663 /* If env is already open, caller is responsible for making
3664 * sure there are no active txns.
3672 size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3674 if (size < env->me_mapsize) {
3675 /* If the configured size is smaller, make sure it's
3676 * still big enough. Silently round up to minimum if not.
3678 size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3682 /* nothing actually changed */
3683 if (size == env->me_mapsize)
3687 munmap(env->me_map, env->me_mapsize);
3688 env->me_mapsize = size;
3689 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3690 rc = mdb_env_map(env, old, 1);
3694 env->me_flags |= MDB_RESIZING;
3696 env->me_mapsize = size;
3698 env->me_maxpg = env->me_mapsize / env->me_psize;
3703 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3707 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3712 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3714 if (env->me_map || readers < 1)
3716 env->me_maxreaders = readers;
3721 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3723 if (!env || !readers)
3725 *readers = env->me_maxreaders;
3729 /** Further setup required for opening an LMDB environment
3732 mdb_env_open2(MDB_env *env)
3734 unsigned int flags = env->me_flags;
3735 int i, newenv = 0, rc;
3739 /* See if we should use QueryLimited */
3741 if ((rc & 0xff) > 5)
3742 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3744 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3747 memset(&meta, 0, sizeof(meta));
3749 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3752 DPUTS("new mdbenv");
3754 env->me_psize = env->me_os_psize;
3755 if (env->me_psize > MAX_PAGESIZE)
3756 env->me_psize = MAX_PAGESIZE;
3758 env->me_psize = meta.mm_psize;
3761 /* Was a mapsize configured? */
3762 if (!env->me_mapsize) {
3763 /* If this is a new environment, take the default,
3764 * else use the size recorded in the existing env.
3766 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3767 } else if (env->me_mapsize < meta.mm_mapsize) {
3768 /* If the configured size is smaller, make sure it's
3769 * still big enough. Silently round up to minimum if not.
3771 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3772 if (env->me_mapsize < minsize)
3773 env->me_mapsize = minsize;
3776 rc = mdb_env_map(env, meta.mm_address, newenv || env->me_mapsize != meta.mm_mapsize);
3781 if (flags & MDB_FIXEDMAP)
3782 meta.mm_address = env->me_map;
3783 i = mdb_env_init_meta(env, &meta);
3784 if (i != MDB_SUCCESS) {
3789 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3790 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
3792 #if !(MDB_MAXKEYSIZE)
3793 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
3795 env->me_maxpg = env->me_mapsize / env->me_psize;
3799 int toggle = mdb_env_pick_meta(env);
3800 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3802 DPRINTF(("opened database version %u, pagesize %u",
3803 env->me_metas[0]->mm_version, env->me_psize));
3804 DPRINTF(("using meta page %d", toggle));
3805 DPRINTF(("depth: %u", db->md_depth));
3806 DPRINTF(("entries: %"Z"u", db->md_entries));
3807 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
3808 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
3809 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3810 DPRINTF(("root: %"Z"u", db->md_root));
3818 /** Release a reader thread's slot in the reader lock table.
3819 * This function is called automatically when a thread exits.
3820 * @param[in] ptr This points to the slot in the reader lock table.
3823 mdb_env_reader_dest(void *ptr)
3825 MDB_reader *reader = ptr;
3831 /** Junk for arranging thread-specific callbacks on Windows. This is
3832 * necessarily platform and compiler-specific. Windows supports up
3833 * to 1088 keys. Let's assume nobody opens more than 64 environments
3834 * in a single process, for now. They can override this if needed.
3836 #ifndef MAX_TLS_KEYS
3837 #define MAX_TLS_KEYS 64
3839 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3840 static int mdb_tls_nkeys;
3842 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3846 case DLL_PROCESS_ATTACH: break;
3847 case DLL_THREAD_ATTACH: break;
3848 case DLL_THREAD_DETACH:
3849 for (i=0; i<mdb_tls_nkeys; i++) {
3850 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3852 mdb_env_reader_dest(r);
3856 case DLL_PROCESS_DETACH: break;
3861 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3863 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3867 /* Force some symbol references.
3868 * _tls_used forces the linker to create the TLS directory if not already done
3869 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3871 #pragma comment(linker, "/INCLUDE:_tls_used")
3872 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3873 #pragma const_seg(".CRT$XLB")
3874 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
3875 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3878 #pragma comment(linker, "/INCLUDE:__tls_used")
3879 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3880 #pragma data_seg(".CRT$XLB")
3881 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3883 #endif /* WIN 32/64 */
3884 #endif /* !__GNUC__ */
3887 /** Downgrade the exclusive lock on the region back to shared */
3889 mdb_env_share_locks(MDB_env *env, int *excl)
3891 int rc = 0, toggle = mdb_env_pick_meta(env);
3893 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3898 /* First acquire a shared lock. The Unlock will
3899 * then release the existing exclusive lock.
3901 memset(&ov, 0, sizeof(ov));
3902 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3905 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3911 struct flock lock_info;
3912 /* The shared lock replaces the existing lock */
3913 memset((void *)&lock_info, 0, sizeof(lock_info));
3914 lock_info.l_type = F_RDLCK;
3915 lock_info.l_whence = SEEK_SET;
3916 lock_info.l_start = 0;
3917 lock_info.l_len = 1;
3918 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3919 (rc = ErrCode()) == EINTR) ;
3920 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3927 /** Try to get exlusive lock, otherwise shared.
3928 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3931 mdb_env_excl_lock(MDB_env *env, int *excl)
3935 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3939 memset(&ov, 0, sizeof(ov));
3940 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3947 struct flock lock_info;
3948 memset((void *)&lock_info, 0, sizeof(lock_info));
3949 lock_info.l_type = F_WRLCK;
3950 lock_info.l_whence = SEEK_SET;
3951 lock_info.l_start = 0;
3952 lock_info.l_len = 1;
3953 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3954 (rc = ErrCode()) == EINTR) ;
3958 # ifdef MDB_USE_POSIX_SEM
3959 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3962 lock_info.l_type = F_RDLCK;
3963 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3964 (rc = ErrCode()) == EINTR) ;
3974 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3976 * @(#) $Revision: 5.1 $
3977 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3978 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3980 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3984 * Please do not copyright this code. This code is in the public domain.
3986 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3987 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3988 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3989 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3990 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3991 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3992 * PERFORMANCE OF THIS SOFTWARE.
3995 * chongo <Landon Curt Noll> /\oo/\
3996 * http://www.isthe.com/chongo/
3998 * Share and Enjoy! :-)
4001 typedef unsigned long long mdb_hash_t;
4002 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4004 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4005 * @param[in] val value to hash
4006 * @param[in] hval initial value for hash
4007 * @return 64 bit hash
4009 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4010 * hval arg on the first call.
4013 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4015 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4016 unsigned char *end = s + val->mv_size;
4018 * FNV-1a hash each octet of the string
4021 /* xor the bottom with the current octet */
4022 hval ^= (mdb_hash_t)*s++;
4024 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4025 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4026 (hval << 7) + (hval << 8) + (hval << 40);
4028 /* return our new hash value */
4032 /** Hash the string and output the encoded hash.
4033 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4034 * very short name limits. We don't care about the encoding being reversible,
4035 * we just want to preserve as many bits of the input as possible in a
4036 * small printable string.
4037 * @param[in] str string to hash
4038 * @param[out] encbuf an array of 11 chars to hold the hash
4040 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4043 mdb_pack85(unsigned long l, char *out)
4047 for (i=0; i<5; i++) {
4048 *out++ = mdb_a85[l % 85];
4054 mdb_hash_enc(MDB_val *val, char *encbuf)
4056 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4058 mdb_pack85(h, encbuf);
4059 mdb_pack85(h>>32, encbuf+5);
4064 /** Open and/or initialize the lock region for the environment.
4065 * @param[in] env The LMDB environment.
4066 * @param[in] lpath The pathname of the file used for the lock region.
4067 * @param[in] mode The Unix permissions for the file, if we create it.
4068 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
4069 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4070 * @return 0 on success, non-zero on failure.
4073 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4076 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4078 # define MDB_ERRCODE_ROFS EROFS
4079 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4080 # define MDB_CLOEXEC O_CLOEXEC
4083 # define MDB_CLOEXEC 0
4090 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
4091 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4092 FILE_ATTRIBUTE_NORMAL, NULL);
4094 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4096 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4098 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4103 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4104 /* Lose record locks when exec*() */
4105 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4106 fcntl(env->me_lfd, F_SETFD, fdflags);
4109 if (!(env->me_flags & MDB_NOTLS)) {
4110 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4113 env->me_flags |= MDB_ENV_TXKEY;
4115 /* Windows TLS callbacks need help finding their TLS info. */
4116 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4120 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4124 /* Try to get exclusive lock. If we succeed, then
4125 * nobody is using the lock region and we should initialize it.
4127 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4130 size = GetFileSize(env->me_lfd, NULL);
4132 size = lseek(env->me_lfd, 0, SEEK_END);
4133 if (size == -1) goto fail_errno;
4135 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4136 if (size < rsize && *excl > 0) {
4138 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4139 || !SetEndOfFile(env->me_lfd))
4142 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4146 size = rsize - sizeof(MDB_txninfo);
4147 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4152 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4154 if (!mh) goto fail_errno;
4155 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4157 if (!env->me_txns) goto fail_errno;
4159 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4161 if (m == MAP_FAILED) goto fail_errno;
4167 BY_HANDLE_FILE_INFORMATION stbuf;
4176 if (!mdb_sec_inited) {
4177 InitializeSecurityDescriptor(&mdb_null_sd,
4178 SECURITY_DESCRIPTOR_REVISION);
4179 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4180 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4181 mdb_all_sa.bInheritHandle = FALSE;
4182 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4185 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4186 idbuf.volume = stbuf.dwVolumeSerialNumber;
4187 idbuf.nhigh = stbuf.nFileIndexHigh;
4188 idbuf.nlow = stbuf.nFileIndexLow;
4189 val.mv_data = &idbuf;
4190 val.mv_size = sizeof(idbuf);
4191 mdb_hash_enc(&val, encbuf);
4192 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4193 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4194 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4195 if (!env->me_rmutex) goto fail_errno;
4196 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4197 if (!env->me_wmutex) goto fail_errno;
4198 #elif defined(MDB_USE_POSIX_SEM)
4207 #if defined(__NetBSD__)
4208 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4210 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4211 idbuf.dev = stbuf.st_dev;
4212 idbuf.ino = stbuf.st_ino;
4213 val.mv_data = &idbuf;
4214 val.mv_size = sizeof(idbuf);
4215 mdb_hash_enc(&val, encbuf);
4216 #ifdef MDB_SHORT_SEMNAMES
4217 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4219 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4220 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4221 /* Clean up after a previous run, if needed: Try to
4222 * remove both semaphores before doing anything else.
4224 sem_unlink(env->me_txns->mti_rmname);
4225 sem_unlink(env->me_txns->mti_wmname);
4226 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4227 O_CREAT|O_EXCL, mode, 1);
4228 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4229 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4230 O_CREAT|O_EXCL, mode, 1);
4231 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4232 #else /* MDB_USE_POSIX_SEM */
4233 pthread_mutexattr_t mattr;
4235 if ((rc = pthread_mutexattr_init(&mattr))
4236 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4237 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
4238 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
4240 pthread_mutexattr_destroy(&mattr);
4241 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4243 env->me_txns->mti_magic = MDB_MAGIC;
4244 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4245 env->me_txns->mti_txnid = 0;
4246 env->me_txns->mti_numreaders = 0;
4249 if (env->me_txns->mti_magic != MDB_MAGIC) {
4250 DPUTS("lock region has invalid magic");
4254 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4255 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4256 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4257 rc = MDB_VERSION_MISMATCH;
4261 if (rc && rc != EACCES && rc != EAGAIN) {
4265 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4266 if (!env->me_rmutex) goto fail_errno;
4267 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4268 if (!env->me_wmutex) goto fail_errno;
4269 #elif defined(MDB_USE_POSIX_SEM)
4270 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4271 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4272 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4273 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4284 /** The name of the lock file in the DB environment */
4285 #define LOCKNAME "/lock.mdb"
4286 /** The name of the data file in the DB environment */
4287 #define DATANAME "/data.mdb"
4288 /** The suffix of the lock file when no subdir is used */
4289 #define LOCKSUFF "-lock"
4290 /** Only a subset of the @ref mdb_env flags can be changed
4291 * at runtime. Changing other flags requires closing the
4292 * environment and re-opening it with the new flags.
4294 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4295 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP| \
4296 MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4298 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4299 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4303 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4305 int oflags, rc, len, excl = -1;
4306 char *lpath, *dpath;
4308 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4312 if (flags & MDB_NOSUBDIR) {
4313 rc = len + sizeof(LOCKSUFF) + len + 1;
4315 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4320 if (flags & MDB_NOSUBDIR) {
4321 dpath = lpath + len + sizeof(LOCKSUFF);
4322 sprintf(lpath, "%s" LOCKSUFF, path);
4323 strcpy(dpath, path);
4325 dpath = lpath + len + sizeof(LOCKNAME);
4326 sprintf(lpath, "%s" LOCKNAME, path);
4327 sprintf(dpath, "%s" DATANAME, path);
4331 flags |= env->me_flags;
4332 if (flags & MDB_RDONLY) {
4333 /* silently ignore WRITEMAP when we're only getting read access */
4334 flags &= ~MDB_WRITEMAP;
4336 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4337 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4340 env->me_flags = flags |= MDB_ENV_ACTIVE;
4344 env->me_path = strdup(path);
4345 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4346 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4347 if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
4352 /* For RDONLY, get lockfile after we know datafile exists */
4353 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4354 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4360 if (F_ISSET(flags, MDB_RDONLY)) {
4361 oflags = GENERIC_READ;
4362 len = OPEN_EXISTING;
4364 oflags = GENERIC_READ|GENERIC_WRITE;
4367 mode = FILE_ATTRIBUTE_NORMAL;
4368 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4369 NULL, len, mode, NULL);
4371 if (F_ISSET(flags, MDB_RDONLY))
4374 oflags = O_RDWR | O_CREAT;
4376 env->me_fd = open(dpath, oflags, mode);
4378 if (env->me_fd == INVALID_HANDLE_VALUE) {
4383 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4384 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4389 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4390 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4391 env->me_mfd = env->me_fd;
4393 /* Synchronous fd for meta writes. Needed even with
4394 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4397 len = OPEN_EXISTING;
4398 env->me_mfd = CreateFile(dpath, oflags,
4399 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4400 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4403 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4405 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4410 DPRINTF(("opened dbenv %p", (void *) env));
4412 rc = mdb_env_share_locks(env, &excl);
4416 if (!((flags & MDB_RDONLY) ||
4417 (env->me_pbuf = calloc(1, env->me_psize))))
4423 mdb_env_close0(env, excl);
4429 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4431 mdb_env_close0(MDB_env *env, int excl)
4435 if (!(env->me_flags & MDB_ENV_ACTIVE))
4438 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4439 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4440 free(env->me_dbxs[i].md_name.mv_data);
4443 free(env->me_dbflags);
4446 free(env->me_dirty_list);
4447 mdb_midl_free(env->me_free_pgs);
4449 if (env->me_flags & MDB_ENV_TXKEY) {
4450 pthread_key_delete(env->me_txkey);
4452 /* Delete our key from the global list */
4453 for (i=0; i<mdb_tls_nkeys; i++)
4454 if (mdb_tls_keys[i] == env->me_txkey) {
4455 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4463 munmap(env->me_map, env->me_mapsize);
4465 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4466 (void) close(env->me_mfd);
4467 if (env->me_fd != INVALID_HANDLE_VALUE)
4468 (void) close(env->me_fd);
4470 MDB_PID_T pid = env->me_pid;
4471 /* Clearing readers is done in this function because
4472 * me_txkey with its destructor must be disabled first.
4474 for (i = env->me_numreaders; --i >= 0; )
4475 if (env->me_txns->mti_readers[i].mr_pid == pid)
4476 env->me_txns->mti_readers[i].mr_pid = 0;
4478 if (env->me_rmutex) {
4479 CloseHandle(env->me_rmutex);
4480 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4482 /* Windows automatically destroys the mutexes when
4483 * the last handle closes.
4485 #elif defined(MDB_USE_POSIX_SEM)
4486 if (env->me_rmutex != SEM_FAILED) {
4487 sem_close(env->me_rmutex);
4488 if (env->me_wmutex != SEM_FAILED)
4489 sem_close(env->me_wmutex);
4490 /* If we have the filelock: If we are the
4491 * only remaining user, clean up semaphores.
4494 mdb_env_excl_lock(env, &excl);
4496 sem_unlink(env->me_txns->mti_rmname);
4497 sem_unlink(env->me_txns->mti_wmname);
4501 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4503 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4506 /* Unlock the lockfile. Windows would have unlocked it
4507 * after closing anyway, but not necessarily at once.
4509 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4512 (void) close(env->me_lfd);
4515 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4520 mdb_env_close(MDB_env *env)
4527 VGMEMP_DESTROY(env);
4528 while ((dp = env->me_dpages) != NULL) {
4529 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4530 env->me_dpages = dp->mp_next;
4534 mdb_env_close0(env, 0);
4538 /** Compare two items pointing at aligned size_t's */
4540 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4542 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4543 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4546 /** Compare two items pointing at aligned unsigned int's */
4548 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4550 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4551 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4554 /** Compare two items pointing at unsigned ints of unknown alignment.
4555 * Nodes and keys are guaranteed to be 2-byte aligned.
4558 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4560 #if BYTE_ORDER == LITTLE_ENDIAN
4561 unsigned short *u, *c;
4564 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4565 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4568 } while(!x && u > (unsigned short *)a->mv_data);
4571 unsigned short *u, *c, *end;
4574 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4575 u = (unsigned short *)a->mv_data;
4576 c = (unsigned short *)b->mv_data;
4579 } while(!x && u < end);
4584 /** Compare two items pointing at size_t's of unknown alignment. */
4585 #ifdef MISALIGNED_OK
4586 # define mdb_cmp_clong mdb_cmp_long
4588 # define mdb_cmp_clong mdb_cmp_cint
4591 /** Compare two items lexically */
4593 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4600 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4606 diff = memcmp(a->mv_data, b->mv_data, len);
4607 return diff ? diff : len_diff<0 ? -1 : len_diff;
4610 /** Compare two items in reverse byte order */
4612 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4614 const unsigned char *p1, *p2, *p1_lim;
4618 p1_lim = (const unsigned char *)a->mv_data;
4619 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4620 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4622 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4628 while (p1 > p1_lim) {
4629 diff = *--p1 - *--p2;
4633 return len_diff<0 ? -1 : len_diff;
4636 /** Search for key within a page, using binary search.
4637 * Returns the smallest entry larger or equal to the key.
4638 * If exactp is non-null, stores whether the found entry was an exact match
4639 * in *exactp (1 or 0).
4640 * Updates the cursor index with the index of the found entry.
4641 * If no entry larger or equal to the key is found, returns NULL.
4644 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4646 unsigned int i = 0, nkeys;
4649 MDB_page *mp = mc->mc_pg[mc->mc_top];
4650 MDB_node *node = NULL;
4655 nkeys = NUMKEYS(mp);
4657 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4658 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4661 low = IS_LEAF(mp) ? 0 : 1;
4663 cmp = mc->mc_dbx->md_cmp;
4665 /* Branch pages have no data, so if using integer keys,
4666 * alignment is guaranteed. Use faster mdb_cmp_int.
4668 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4669 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4676 nodekey.mv_size = mc->mc_db->md_pad;
4677 node = NODEPTR(mp, 0); /* fake */
4678 while (low <= high) {
4679 i = (low + high) >> 1;
4680 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4681 rc = cmp(key, &nodekey);
4682 DPRINTF(("found leaf index %u [%s], rc = %i",
4683 i, DKEY(&nodekey), rc));
4692 while (low <= high) {
4693 i = (low + high) >> 1;
4695 node = NODEPTR(mp, i);
4696 nodekey.mv_size = NODEKSZ(node);
4697 nodekey.mv_data = NODEKEY(node);
4699 rc = cmp(key, &nodekey);
4702 DPRINTF(("found leaf index %u [%s], rc = %i",
4703 i, DKEY(&nodekey), rc));
4705 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4706 i, DKEY(&nodekey), NODEPGNO(node), rc));
4717 if (rc > 0) { /* Found entry is less than the key. */
4718 i++; /* Skip to get the smallest entry larger than key. */
4720 node = NODEPTR(mp, i);
4723 *exactp = (rc == 0 && nkeys > 0);
4724 /* store the key index */
4725 mc->mc_ki[mc->mc_top] = i;
4727 /* There is no entry larger or equal to the key. */
4730 /* nodeptr is fake for LEAF2 */
4736 mdb_cursor_adjust(MDB_cursor *mc, func)
4740 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4741 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4748 /** Pop a page off the top of the cursor's stack. */
4750 mdb_cursor_pop(MDB_cursor *mc)
4754 MDB_page *top = mc->mc_pg[mc->mc_top];
4760 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4761 DDBI(mc), (void *) mc));
4765 /** Push a page onto the top of the cursor's stack. */
4767 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4769 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4770 DDBI(mc), (void *) mc));
4772 if (mc->mc_snum >= CURSOR_STACK) {
4773 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4774 return MDB_CURSOR_FULL;
4777 mc->mc_top = mc->mc_snum++;
4778 mc->mc_pg[mc->mc_top] = mp;
4779 mc->mc_ki[mc->mc_top] = 0;
4784 /** Find the address of the page corresponding to a given page number.
4785 * @param[in] txn the transaction for this access.
4786 * @param[in] pgno the page number for the page to retrieve.
4787 * @param[out] ret address of a pointer where the page's address will be stored.
4788 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4789 * @return 0 on success, non-zero on failure.
4792 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4794 MDB_env *env = txn->mt_env;
4798 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
4802 MDB_ID2L dl = tx2->mt_u.dirty_list;
4804 /* Spilled pages were dirtied in this txn and flushed
4805 * because the dirty list got full. Bring this page
4806 * back in from the map (but don't unspill it here,
4807 * leave that unless page_touch happens again).
4809 if (tx2->mt_spill_pgs) {
4810 MDB_ID pn = pgno << 1;
4811 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
4812 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
4813 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4818 unsigned x = mdb_mid2l_search(dl, pgno);
4819 if (x <= dl[0].mid && dl[x].mid == pgno) {
4825 } while ((tx2 = tx2->mt_parent) != NULL);
4828 if (pgno < txn->mt_next_pgno) {
4830 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4832 DPRINTF(("page %"Z"u not found", pgno));
4833 txn->mt_flags |= MDB_TXN_ERROR;
4834 return MDB_PAGE_NOTFOUND;
4844 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
4845 * The cursor is at the root page, set up the rest of it.
4848 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
4850 MDB_page *mp = mc->mc_pg[mc->mc_top];
4854 while (IS_BRANCH(mp)) {
4858 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
4859 mdb_cassert(mc, NUMKEYS(mp) > 1);
4860 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
4862 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
4864 if (flags & MDB_PS_LAST)
4865 i = NUMKEYS(mp) - 1;
4868 node = mdb_node_search(mc, key, &exact);
4870 i = NUMKEYS(mp) - 1;
4872 i = mc->mc_ki[mc->mc_top];
4874 mdb_cassert(mc, i > 0);
4878 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
4881 mdb_cassert(mc, i < NUMKEYS(mp));
4882 node = NODEPTR(mp, i);
4884 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4887 mc->mc_ki[mc->mc_top] = i;
4888 if ((rc = mdb_cursor_push(mc, mp)))
4891 if (flags & MDB_PS_MODIFY) {
4892 if ((rc = mdb_page_touch(mc)) != 0)
4894 mp = mc->mc_pg[mc->mc_top];
4899 DPRINTF(("internal error, index points to a %02X page!?",
4901 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4902 return MDB_CORRUPTED;
4905 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
4906 key ? DKEY(key) : "null"));
4907 mc->mc_flags |= C_INITIALIZED;
4908 mc->mc_flags &= ~C_EOF;
4913 /** Search for the lowest key under the current branch page.
4914 * This just bypasses a NUMKEYS check in the current page
4915 * before calling mdb_page_search_root(), because the callers
4916 * are all in situations where the current page is known to
4920 mdb_page_search_lowest(MDB_cursor *mc)
4922 MDB_page *mp = mc->mc_pg[mc->mc_top];
4923 MDB_node *node = NODEPTR(mp, 0);
4926 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4929 mc->mc_ki[mc->mc_top] = 0;
4930 if ((rc = mdb_cursor_push(mc, mp)))
4932 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
4935 /** Search for the page a given key should be in.
4936 * Push it and its parent pages on the cursor stack.
4937 * @param[in,out] mc the cursor for this operation.
4938 * @param[in] key the key to search for, or NULL for first/last page.
4939 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
4940 * are touched (updated with new page numbers).
4941 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
4942 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
4943 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4944 * @return 0 on success, non-zero on failure.
4947 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4952 /* Make sure the txn is still viable, then find the root from
4953 * the txn's db table and set it as the root of the cursor's stack.
4955 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4956 DPUTS("transaction has failed, must abort");
4959 /* Make sure we're using an up-to-date root */
4960 if (*mc->mc_dbflag & DB_STALE) {
4962 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4963 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
4970 MDB_node *leaf = mdb_node_search(&mc2,
4971 &mc->mc_dbx->md_name, &exact);
4973 return MDB_NOTFOUND;
4974 rc = mdb_node_read(mc->mc_txn, leaf, &data);
4977 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4979 /* The txn may not know this DBI, or another process may
4980 * have dropped and recreated the DB with other flags.
4982 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4983 return MDB_INCOMPATIBLE;
4984 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4986 *mc->mc_dbflag &= ~DB_STALE;
4988 root = mc->mc_db->md_root;
4990 if (root == P_INVALID) { /* Tree is empty. */
4991 DPUTS("tree is empty");
4992 return MDB_NOTFOUND;
4996 mdb_cassert(mc, root > 1);
4997 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4998 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
5004 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5005 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5007 if (flags & MDB_PS_MODIFY) {
5008 if ((rc = mdb_page_touch(mc)))
5012 if (flags & MDB_PS_ROOTONLY)
5015 return mdb_page_search_root(mc, key, flags);
5019 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5021 MDB_txn *txn = mc->mc_txn;
5022 pgno_t pg = mp->mp_pgno;
5023 unsigned x = 0, ovpages = mp->mp_pages;
5024 MDB_env *env = txn->mt_env;
5025 MDB_IDL sl = txn->mt_spill_pgs;
5026 MDB_ID pn = pg << 1;
5029 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5030 /* If the page is dirty or on the spill list we just acquired it,
5031 * so we should give it back to our current free list, if any.
5032 * Otherwise put it onto the list of pages we freed in this txn.
5034 * Won't create me_pghead: me_pglast must be inited along with it.
5035 * Unsupported in nested txns: They would need to hide the page
5036 * range in ancestor txns' dirty and spilled lists.
5038 if (env->me_pghead &&
5040 ((mp->mp_flags & P_DIRTY) ||
5041 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5045 MDB_ID2 *dl, ix, iy;
5046 rc = mdb_midl_need(&env->me_pghead, ovpages);
5049 if (!(mp->mp_flags & P_DIRTY)) {
5050 /* This page is no longer spilled */
5057 /* Remove from dirty list */
5058 dl = txn->mt_u.dirty_list;
5060 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5066 mdb_cassert(mc, x > 1);
5068 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5069 txn->mt_flags |= MDB_TXN_ERROR;
5070 return MDB_CORRUPTED;
5073 if (!(env->me_flags & MDB_WRITEMAP))
5074 mdb_dpage_free(env, mp);
5076 /* Insert in me_pghead */
5077 mop = env->me_pghead;
5078 j = mop[0] + ovpages;
5079 for (i = mop[0]; i && mop[i] < pg; i--)
5085 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5089 mc->mc_db->md_overflow_pages -= ovpages;
5093 /** Return the data associated with a given node.
5094 * @param[in] txn The transaction for this operation.
5095 * @param[in] leaf The node being read.
5096 * @param[out] data Updated to point to the node's data.
5097 * @return 0 on success, non-zero on failure.
5100 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5102 MDB_page *omp; /* overflow page */
5106 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5107 data->mv_size = NODEDSZ(leaf);
5108 data->mv_data = NODEDATA(leaf);
5112 /* Read overflow data.
5114 data->mv_size = NODEDSZ(leaf);
5115 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5116 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5117 DPRINTF(("read overflow page %"Z"u failed", pgno));
5120 data->mv_data = METADATA(omp);
5126 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5127 MDB_val *key, MDB_val *data)
5134 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5136 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
5139 if (txn->mt_flags & MDB_TXN_ERROR)
5142 mdb_cursor_init(&mc, txn, dbi, &mx);
5143 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5146 /** Find a sibling for a page.
5147 * Replaces the page at the top of the cursor's stack with the
5148 * specified sibling, if one exists.
5149 * @param[in] mc The cursor for this operation.
5150 * @param[in] move_right Non-zero if the right sibling is requested,
5151 * otherwise the left sibling.
5152 * @return 0 on success, non-zero on failure.
5155 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5161 if (mc->mc_snum < 2) {
5162 return MDB_NOTFOUND; /* root has no siblings */
5166 DPRINTF(("parent page is page %"Z"u, index %u",
5167 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5169 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5170 : (mc->mc_ki[mc->mc_top] == 0)) {
5171 DPRINTF(("no more keys left, moving to %s sibling",
5172 move_right ? "right" : "left"));
5173 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5174 /* undo cursor_pop before returning */
5181 mc->mc_ki[mc->mc_top]++;
5183 mc->mc_ki[mc->mc_top]--;
5184 DPRINTF(("just moving to %s index key %u",
5185 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5187 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5189 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5190 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5191 /* mc will be inconsistent if caller does mc_snum++ as above */
5192 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5196 mdb_cursor_push(mc, mp);
5198 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5203 /** Move the cursor to the next data item. */
5205 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5211 if (mc->mc_flags & C_EOF) {
5212 return MDB_NOTFOUND;
5215 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5217 mp = mc->mc_pg[mc->mc_top];
5219 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5220 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5221 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5222 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5223 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5224 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5225 if (rc == MDB_SUCCESS)
5226 MDB_GET_KEY(leaf, key);
5231 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5232 if (op == MDB_NEXT_DUP)
5233 return MDB_NOTFOUND;
5237 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5238 mdb_dbg_pgno(mp), (void *) mc));
5239 if (mc->mc_flags & C_DEL)
5242 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5243 DPUTS("=====> move to next sibling page");
5244 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5245 mc->mc_flags |= C_EOF;
5248 mp = mc->mc_pg[mc->mc_top];
5249 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5251 mc->mc_ki[mc->mc_top]++;
5254 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5255 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5258 key->mv_size = mc->mc_db->md_pad;
5259 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5263 mdb_cassert(mc, IS_LEAF(mp));
5264 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5266 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5267 mdb_xcursor_init1(mc, leaf);
5270 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5273 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5274 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5275 if (rc != MDB_SUCCESS)
5280 MDB_GET_KEY(leaf, key);
5284 /** Move the cursor to the previous data item. */
5286 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5292 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5294 mp = mc->mc_pg[mc->mc_top];
5296 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5297 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5298 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5299 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5300 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5301 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5302 if (rc == MDB_SUCCESS)
5303 MDB_GET_KEY(leaf, key);
5307 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5308 if (op == MDB_PREV_DUP)
5309 return MDB_NOTFOUND;
5314 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5315 mdb_dbg_pgno(mp), (void *) mc));
5317 if (mc->mc_ki[mc->mc_top] == 0) {
5318 DPUTS("=====> move to prev sibling page");
5319 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5322 mp = mc->mc_pg[mc->mc_top];
5323 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5324 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5326 mc->mc_ki[mc->mc_top]--;
5328 mc->mc_flags &= ~C_EOF;
5330 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5331 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5334 key->mv_size = mc->mc_db->md_pad;
5335 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5339 mdb_cassert(mc, IS_LEAF(mp));
5340 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5342 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5343 mdb_xcursor_init1(mc, leaf);
5346 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5349 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5350 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5351 if (rc != MDB_SUCCESS)
5356 MDB_GET_KEY(leaf, key);
5360 /** Set the cursor on a specific data item. */
5362 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5363 MDB_cursor_op op, int *exactp)
5367 MDB_node *leaf = NULL;
5370 if (key->mv_size == 0)
5371 return MDB_BAD_VALSIZE;
5374 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5376 /* See if we're already on the right page */
5377 if (mc->mc_flags & C_INITIALIZED) {
5380 mp = mc->mc_pg[mc->mc_top];
5382 mc->mc_ki[mc->mc_top] = 0;
5383 return MDB_NOTFOUND;
5385 if (mp->mp_flags & P_LEAF2) {
5386 nodekey.mv_size = mc->mc_db->md_pad;
5387 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5389 leaf = NODEPTR(mp, 0);
5390 MDB_GET_KEY2(leaf, nodekey);
5392 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5394 /* Probably happens rarely, but first node on the page
5395 * was the one we wanted.
5397 mc->mc_ki[mc->mc_top] = 0;
5404 unsigned int nkeys = NUMKEYS(mp);
5406 if (mp->mp_flags & P_LEAF2) {
5407 nodekey.mv_data = LEAF2KEY(mp,
5408 nkeys-1, nodekey.mv_size);
5410 leaf = NODEPTR(mp, nkeys-1);
5411 MDB_GET_KEY2(leaf, nodekey);
5413 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5415 /* last node was the one we wanted */
5416 mc->mc_ki[mc->mc_top] = nkeys-1;
5422 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5423 /* This is definitely the right page, skip search_page */
5424 if (mp->mp_flags & P_LEAF2) {
5425 nodekey.mv_data = LEAF2KEY(mp,
5426 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5428 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5429 MDB_GET_KEY2(leaf, nodekey);
5431 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5433 /* current node was the one we wanted */
5443 /* If any parents have right-sibs, search.
5444 * Otherwise, there's nothing further.
5446 for (i=0; i<mc->mc_top; i++)
5448 NUMKEYS(mc->mc_pg[i])-1)
5450 if (i == mc->mc_top) {
5451 /* There are no other pages */
5452 mc->mc_ki[mc->mc_top] = nkeys;
5453 return MDB_NOTFOUND;
5457 /* There are no other pages */
5458 mc->mc_ki[mc->mc_top] = 0;
5459 if (op == MDB_SET_RANGE && !exactp) {
5463 return MDB_NOTFOUND;
5467 rc = mdb_page_search(mc, key, 0);
5468 if (rc != MDB_SUCCESS)
5471 mp = mc->mc_pg[mc->mc_top];
5472 mdb_cassert(mc, IS_LEAF(mp));
5475 leaf = mdb_node_search(mc, key, exactp);
5476 if (exactp != NULL && !*exactp) {
5477 /* MDB_SET specified and not an exact match. */
5478 return MDB_NOTFOUND;
5482 DPUTS("===> inexact leaf not found, goto sibling");
5483 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5484 return rc; /* no entries matched */
5485 mp = mc->mc_pg[mc->mc_top];
5486 mdb_cassert(mc, IS_LEAF(mp));
5487 leaf = NODEPTR(mp, 0);
5491 mc->mc_flags |= C_INITIALIZED;
5492 mc->mc_flags &= ~C_EOF;
5495 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5496 key->mv_size = mc->mc_db->md_pad;
5497 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5502 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5503 mdb_xcursor_init1(mc, leaf);
5506 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5507 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5508 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5511 if (op == MDB_GET_BOTH) {
5517 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5518 if (rc != MDB_SUCCESS)
5521 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5523 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5525 rc = mc->mc_dbx->md_dcmp(data, &d2);
5527 if (op == MDB_GET_BOTH || rc > 0)
5528 return MDB_NOTFOUND;
5535 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5536 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5541 /* The key already matches in all other cases */
5542 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5543 MDB_GET_KEY(leaf, key);
5544 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5549 /** Move the cursor to the first item in the database. */
5551 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5557 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5559 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5560 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5561 if (rc != MDB_SUCCESS)
5564 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5566 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5567 mc->mc_flags |= C_INITIALIZED;
5568 mc->mc_flags &= ~C_EOF;
5570 mc->mc_ki[mc->mc_top] = 0;
5572 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5573 key->mv_size = mc->mc_db->md_pad;
5574 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5579 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5580 mdb_xcursor_init1(mc, leaf);
5581 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5585 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5589 MDB_GET_KEY(leaf, key);
5593 /** Move the cursor to the last item in the database. */
5595 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5601 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5603 if (!(mc->mc_flags & C_EOF)) {
5605 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5606 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5607 if (rc != MDB_SUCCESS)
5610 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5613 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5614 mc->mc_flags |= C_INITIALIZED|C_EOF;
5615 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5617 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5618 key->mv_size = mc->mc_db->md_pad;
5619 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5624 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5625 mdb_xcursor_init1(mc, leaf);
5626 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5630 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5635 MDB_GET_KEY(leaf, key);
5640 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5645 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5650 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5654 case MDB_GET_CURRENT:
5655 if (!(mc->mc_flags & C_INITIALIZED)) {
5658 MDB_page *mp = mc->mc_pg[mc->mc_top];
5659 int nkeys = NUMKEYS(mp);
5660 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5661 mc->mc_ki[mc->mc_top] = nkeys;
5667 key->mv_size = mc->mc_db->md_pad;
5668 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5670 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5671 MDB_GET_KEY(leaf, key);
5673 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5674 if (mc->mc_flags & C_DEL)
5675 mdb_xcursor_init1(mc, leaf);
5676 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5678 rc = mdb_node_read(mc->mc_txn, leaf, data);
5685 case MDB_GET_BOTH_RANGE:
5690 if (mc->mc_xcursor == NULL) {
5691 rc = MDB_INCOMPATIBLE;
5701 rc = mdb_cursor_set(mc, key, data, op,
5702 op == MDB_SET_RANGE ? NULL : &exact);
5705 case MDB_GET_MULTIPLE:
5706 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5710 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5711 rc = MDB_INCOMPATIBLE;
5715 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5716 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5719 case MDB_NEXT_MULTIPLE:
5724 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5725 rc = MDB_INCOMPATIBLE;
5728 if (!(mc->mc_flags & C_INITIALIZED))
5729 rc = mdb_cursor_first(mc, key, data);
5731 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5732 if (rc == MDB_SUCCESS) {
5733 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5736 mx = &mc->mc_xcursor->mx_cursor;
5737 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5739 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5740 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5748 case MDB_NEXT_NODUP:
5749 if (!(mc->mc_flags & C_INITIALIZED))
5750 rc = mdb_cursor_first(mc, key, data);
5752 rc = mdb_cursor_next(mc, key, data, op);
5756 case MDB_PREV_NODUP:
5757 if (!(mc->mc_flags & C_INITIALIZED)) {
5758 rc = mdb_cursor_last(mc, key, data);
5761 mc->mc_flags |= C_INITIALIZED;
5762 mc->mc_ki[mc->mc_top]++;
5764 rc = mdb_cursor_prev(mc, key, data, op);
5767 rc = mdb_cursor_first(mc, key, data);
5770 mfunc = mdb_cursor_first;
5772 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5776 if (mc->mc_xcursor == NULL) {
5777 rc = MDB_INCOMPATIBLE;
5780 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5784 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
5787 rc = mdb_cursor_last(mc, key, data);
5790 mfunc = mdb_cursor_last;
5793 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
5798 if (mc->mc_flags & C_DEL)
5799 mc->mc_flags ^= C_DEL;
5804 /** Touch all the pages in the cursor stack. Set mc_top.
5805 * Makes sure all the pages are writable, before attempting a write operation.
5806 * @param[in] mc The cursor to operate on.
5809 mdb_cursor_touch(MDB_cursor *mc)
5811 int rc = MDB_SUCCESS;
5813 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5816 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5817 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5820 *mc->mc_dbflag |= DB_DIRTY;
5825 rc = mdb_page_touch(mc);
5826 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
5827 mc->mc_top = mc->mc_snum-1;
5832 /** Do not spill pages to disk if txn is getting full, may fail instead */
5833 #define MDB_NOSPILL 0x8000
5836 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5839 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5841 MDB_node *leaf = NULL;
5844 MDB_val xdata, *rdata, dkey, olddata;
5846 int do_sub = 0, insert_key, insert_data;
5847 unsigned int mcount = 0, dcount = 0, nospill;
5850 unsigned int nflags;
5853 if (mc == NULL || key == NULL)
5856 env = mc->mc_txn->mt_env;
5858 /* Check this first so counter will always be zero on any
5861 if (flags & MDB_MULTIPLE) {
5862 dcount = data[1].mv_size;
5863 data[1].mv_size = 0;
5864 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5865 return MDB_INCOMPATIBLE;
5868 nospill = flags & MDB_NOSPILL;
5869 flags &= ~MDB_NOSPILL;
5871 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
5872 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
5874 if (key->mv_size-1 >= ENV_MAXKEY(env))
5875 return MDB_BAD_VALSIZE;
5877 #if SIZE_MAX > MAXDATASIZE
5878 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
5879 return MDB_BAD_VALSIZE;
5881 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
5882 return MDB_BAD_VALSIZE;
5885 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
5886 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
5890 if (flags == MDB_CURRENT) {
5891 if (!(mc->mc_flags & C_INITIALIZED))
5894 } else if (mc->mc_db->md_root == P_INVALID) {
5895 /* new database, cursor has nothing to point to */
5898 mc->mc_flags &= ~C_INITIALIZED;
5903 if (flags & MDB_APPEND) {
5905 rc = mdb_cursor_last(mc, &k2, &d2);
5907 rc = mc->mc_dbx->md_cmp(key, &k2);
5910 mc->mc_ki[mc->mc_top]++;
5912 /* new key is <= last key */
5917 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5919 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5920 DPRINTF(("duplicate key [%s]", DKEY(key)));
5922 return MDB_KEYEXIST;
5924 if (rc && rc != MDB_NOTFOUND)
5928 if (mc->mc_flags & C_DEL)
5929 mc->mc_flags ^= C_DEL;
5931 /* Cursor is positioned, check for room in the dirty list */
5933 if (flags & MDB_MULTIPLE) {
5935 xdata.mv_size = data->mv_size * dcount;
5939 if ((rc2 = mdb_page_spill(mc, key, rdata)))
5943 if (rc == MDB_NO_ROOT) {
5945 /* new database, write a root leaf page */
5946 DPUTS("allocating new root leaf page");
5947 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
5950 mdb_cursor_push(mc, np);
5951 mc->mc_db->md_root = np->mp_pgno;
5952 mc->mc_db->md_depth++;
5953 *mc->mc_dbflag |= DB_DIRTY;
5954 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5956 np->mp_flags |= P_LEAF2;
5957 mc->mc_flags |= C_INITIALIZED;
5959 /* make sure all cursor pages are writable */
5960 rc2 = mdb_cursor_touch(mc);
5965 insert_key = insert_data = rc;
5967 /* The key does not exist */
5968 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
5969 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
5970 LEAFSIZE(key, data) > env->me_nodemax)
5972 /* Too big for a node, insert in sub-DB. Set up an empty
5973 * "old sub-page" for prep_subDB to expand to a full page.
5975 fp_flags = P_LEAF|P_DIRTY;
5977 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
5978 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
5979 olddata.mv_size = PAGEHDRSZ;
5983 /* there's only a key anyway, so this is a no-op */
5984 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5986 unsigned int ksize = mc->mc_db->md_pad;
5987 if (key->mv_size != ksize)
5988 return MDB_BAD_VALSIZE;
5989 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5990 memcpy(ptr, key->mv_data, ksize);
5995 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5996 olddata.mv_size = NODEDSZ(leaf);
5997 olddata.mv_data = NODEDATA(leaf);
6000 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6001 /* Prepare (sub-)page/sub-DB to accept the new item,
6002 * if needed. fp: old sub-page or a header faking
6003 * it. mp: new (sub-)page. offset: growth in page
6004 * size. xdata: node data with new page or DB.
6006 unsigned i, offset = 0;
6007 mp = fp = xdata.mv_data = env->me_pbuf;
6008 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6010 /* Was a single item before, must convert now */
6011 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6012 /* Just overwrite the current item */
6013 if (flags == MDB_CURRENT)
6016 #if UINT_MAX < SIZE_MAX
6017 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6018 mc->mc_dbx->md_dcmp = mdb_cmp_clong;
6020 /* does data match? */
6021 if (!mc->mc_dbx->md_dcmp(data, &olddata)) {
6022 if (flags & MDB_NODUPDATA)
6023 return MDB_KEYEXIST;
6028 /* Back up original data item */
6029 dkey.mv_size = olddata.mv_size;
6030 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6032 /* Make sub-page header for the dup items, with dummy body */
6033 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6034 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6035 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6036 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6037 fp->mp_flags |= P_LEAF2;
6038 fp->mp_pad = data->mv_size;
6039 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6041 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6042 (dkey.mv_size & 1) + (data->mv_size & 1);
6044 fp->mp_upper = xdata.mv_size - PAGEBASE;
6045 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6046 } else if (leaf->mn_flags & F_SUBDATA) {
6047 /* Data is on sub-DB, just store it */
6048 flags |= F_DUPDATA|F_SUBDATA;
6051 /* Data is on sub-page */
6052 fp = olddata.mv_data;
6055 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6056 offset = EVEN(NODESIZE + sizeof(indx_t) +
6060 offset = fp->mp_pad;
6061 if (SIZELEFT(fp) < offset) {
6062 offset *= 4; /* space for 4 more */
6065 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6067 fp->mp_flags |= P_DIRTY;
6068 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6069 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6073 xdata.mv_size = olddata.mv_size + offset;
6076 fp_flags = fp->mp_flags;
6077 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6078 /* Too big for a sub-page, convert to sub-DB */
6079 fp_flags &= ~P_SUBP;
6081 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6082 fp_flags |= P_LEAF2;
6083 dummy.md_pad = fp->mp_pad;
6084 dummy.md_flags = MDB_DUPFIXED;
6085 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6086 dummy.md_flags |= MDB_INTEGERKEY;
6092 dummy.md_branch_pages = 0;
6093 dummy.md_leaf_pages = 1;
6094 dummy.md_overflow_pages = 0;
6095 dummy.md_entries = NUMKEYS(fp);
6096 xdata.mv_size = sizeof(MDB_db);
6097 xdata.mv_data = &dummy;
6098 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6100 offset = env->me_psize - olddata.mv_size;
6101 flags |= F_DUPDATA|F_SUBDATA;
6102 dummy.md_root = mp->mp_pgno;
6105 mp->mp_flags = fp_flags | P_DIRTY;
6106 mp->mp_pad = fp->mp_pad;
6107 mp->mp_lower = fp->mp_lower;
6108 mp->mp_upper = fp->mp_upper + offset;
6109 if (fp_flags & P_LEAF2) {
6110 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6112 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6113 olddata.mv_size - fp->mp_upper - PAGEBASE);
6114 for (i=0; i<NUMKEYS(fp); i++)
6115 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6123 mdb_node_del(mc, 0);
6127 /* overflow page overwrites need special handling */
6128 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6131 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6133 memcpy(&pg, olddata.mv_data, sizeof(pg));
6134 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6136 ovpages = omp->mp_pages;
6138 /* Is the ov page large enough? */
6139 if (ovpages >= dpages) {
6140 if (!(omp->mp_flags & P_DIRTY) &&
6141 (level || (env->me_flags & MDB_WRITEMAP)))
6143 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6146 level = 0; /* dirty in this txn or clean */
6149 if (omp->mp_flags & P_DIRTY) {
6150 /* yes, overwrite it. Note in this case we don't
6151 * bother to try shrinking the page if the new data
6152 * is smaller than the overflow threshold.
6155 /* It is writable only in a parent txn */
6156 size_t sz = (size_t) env->me_psize * ovpages, off;
6157 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6163 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6164 mdb_cassert(mc, rc2 == 0);
6165 if (!(flags & MDB_RESERVE)) {
6166 /* Copy end of page, adjusting alignment so
6167 * compiler may copy words instead of bytes.
6169 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6170 memcpy((size_t *)((char *)np + off),
6171 (size_t *)((char *)omp + off), sz - off);
6174 memcpy(np, omp, sz); /* Copy beginning of page */
6177 SETDSZ(leaf, data->mv_size);
6178 if (F_ISSET(flags, MDB_RESERVE))
6179 data->mv_data = METADATA(omp);
6181 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6185 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6187 } else if (data->mv_size == olddata.mv_size) {
6188 /* same size, just replace it. Note that we could
6189 * also reuse this node if the new data is smaller,
6190 * but instead we opt to shrink the node in that case.
6192 if (F_ISSET(flags, MDB_RESERVE))
6193 data->mv_data = olddata.mv_data;
6194 else if (!(mc->mc_flags & C_SUB))
6195 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6197 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6200 mdb_node_del(mc, 0);
6206 nflags = flags & NODE_ADD_FLAGS;
6207 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6208 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6209 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6210 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6212 nflags |= MDB_SPLIT_REPLACE;
6213 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6215 /* There is room already in this leaf page. */
6216 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6217 if (rc == 0 && insert_key) {
6218 /* Adjust other cursors pointing to mp */
6219 MDB_cursor *m2, *m3;
6220 MDB_dbi dbi = mc->mc_dbi;
6221 unsigned i = mc->mc_top;
6222 MDB_page *mp = mc->mc_pg[i];
6224 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6225 if (mc->mc_flags & C_SUB)
6226 m3 = &m2->mc_xcursor->mx_cursor;
6229 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6230 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6237 if (rc == MDB_SUCCESS) {
6238 /* Now store the actual data in the child DB. Note that we're
6239 * storing the user data in the keys field, so there are strict
6240 * size limits on dupdata. The actual data fields of the child
6241 * DB are all zero size.
6249 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6250 if (flags & MDB_CURRENT) {
6251 xflags = MDB_CURRENT|MDB_NOSPILL;
6253 mdb_xcursor_init1(mc, leaf);
6254 xflags = (flags & MDB_NODUPDATA) ?
6255 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6257 /* converted, write the original data first */
6259 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6263 /* Adjust other cursors pointing to mp */
6265 unsigned i = mc->mc_top;
6266 MDB_page *mp = mc->mc_pg[i];
6268 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6269 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6270 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6271 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6272 mdb_xcursor_init1(m2, leaf);
6276 /* we've done our job */
6279 ecount = mc->mc_xcursor->mx_db.md_entries;
6280 if (flags & MDB_APPENDDUP)
6281 xflags |= MDB_APPEND;
6282 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6283 if (flags & F_SUBDATA) {
6284 void *db = NODEDATA(leaf);
6285 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6287 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6289 /* Increment count unless we just replaced an existing item. */
6291 mc->mc_db->md_entries++;
6293 /* Invalidate txn if we created an empty sub-DB */
6296 /* If we succeeded and the key didn't exist before,
6297 * make sure the cursor is marked valid.
6299 mc->mc_flags |= C_INITIALIZED;
6301 if (flags & MDB_MULTIPLE) {
6304 /* let caller know how many succeeded, if any */
6305 data[1].mv_size = mcount;
6306 if (mcount < dcount) {
6307 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6308 insert_key = insert_data = 0;
6315 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6318 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6323 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6329 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6330 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6332 if (!(mc->mc_flags & C_INITIALIZED))
6335 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6336 return MDB_NOTFOUND;
6338 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6341 rc = mdb_cursor_touch(mc);
6345 mp = mc->mc_pg[mc->mc_top];
6348 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6350 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6351 if (flags & MDB_NODUPDATA) {
6352 /* mdb_cursor_del0() will subtract the final entry */
6353 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6355 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6356 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6358 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6361 /* If sub-DB still has entries, we're done */
6362 if (mc->mc_xcursor->mx_db.md_entries) {
6363 if (leaf->mn_flags & F_SUBDATA) {
6364 /* update subDB info */
6365 void *db = NODEDATA(leaf);
6366 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6369 /* shrink fake page */
6370 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6371 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6372 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6373 /* fix other sub-DB cursors pointed at this fake page */
6374 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6375 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6376 if (m2->mc_pg[mc->mc_top] == mp &&
6377 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6378 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6381 mc->mc_db->md_entries--;
6382 mc->mc_flags |= C_DEL;
6385 /* otherwise fall thru and delete the sub-DB */
6388 if (leaf->mn_flags & F_SUBDATA) {
6389 /* add all the child DB's pages to the free list */
6390 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6396 /* add overflow pages to free list */
6397 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6401 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6402 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6403 (rc = mdb_ovpage_free(mc, omp)))
6408 return mdb_cursor_del0(mc);
6411 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6415 /** Allocate and initialize new pages for a database.
6416 * @param[in] mc a cursor on the database being added to.
6417 * @param[in] flags flags defining what type of page is being allocated.
6418 * @param[in] num the number of pages to allocate. This is usually 1,
6419 * unless allocating overflow pages for a large record.
6420 * @param[out] mp Address of a page, or NULL on failure.
6421 * @return 0 on success, non-zero on failure.
6424 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6429 if ((rc = mdb_page_alloc(mc, num, &np)))
6431 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6432 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6433 np->mp_flags = flags | P_DIRTY;
6434 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
6435 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
6438 mc->mc_db->md_branch_pages++;
6439 else if (IS_LEAF(np))
6440 mc->mc_db->md_leaf_pages++;
6441 else if (IS_OVERFLOW(np)) {
6442 mc->mc_db->md_overflow_pages += num;
6450 /** Calculate the size of a leaf node.
6451 * The size depends on the environment's page size; if a data item
6452 * is too large it will be put onto an overflow page and the node
6453 * size will only include the key and not the data. Sizes are always
6454 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6455 * of the #MDB_node headers.
6456 * @param[in] env The environment handle.
6457 * @param[in] key The key for the node.
6458 * @param[in] data The data for the node.
6459 * @return The number of bytes needed to store the node.
6462 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6466 sz = LEAFSIZE(key, data);
6467 if (sz > env->me_nodemax) {
6468 /* put on overflow page */
6469 sz -= data->mv_size - sizeof(pgno_t);
6472 return EVEN(sz + sizeof(indx_t));
6475 /** Calculate the size of a branch node.
6476 * The size should depend on the environment's page size but since
6477 * we currently don't support spilling large keys onto overflow
6478 * pages, it's simply the size of the #MDB_node header plus the
6479 * size of the key. Sizes are always rounded up to an even number
6480 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6481 * @param[in] env The environment handle.
6482 * @param[in] key The key for the node.
6483 * @return The number of bytes needed to store the node.
6486 mdb_branch_size(MDB_env *env, MDB_val *key)
6491 if (sz > env->me_nodemax) {
6492 /* put on overflow page */
6493 /* not implemented */
6494 /* sz -= key->size - sizeof(pgno_t); */
6497 return sz + sizeof(indx_t);
6500 /** Add a node to the page pointed to by the cursor.
6501 * @param[in] mc The cursor for this operation.
6502 * @param[in] indx The index on the page where the new node should be added.
6503 * @param[in] key The key for the new node.
6504 * @param[in] data The data for the new node, if any.
6505 * @param[in] pgno The page number, if adding a branch node.
6506 * @param[in] flags Flags for the node.
6507 * @return 0 on success, non-zero on failure. Possible errors are:
6509 * <li>ENOMEM - failed to allocate overflow pages for the node.
6510 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6511 * should never happen since all callers already calculate the
6512 * page's free space before calling this function.
6516 mdb_node_add(MDB_cursor *mc, indx_t indx,
6517 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6520 size_t node_size = NODESIZE;
6524 MDB_page *mp = mc->mc_pg[mc->mc_top];
6525 MDB_page *ofp = NULL; /* overflow page */
6528 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
6530 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6531 IS_LEAF(mp) ? "leaf" : "branch",
6532 IS_SUBP(mp) ? "sub-" : "",
6533 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
6534 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6537 /* Move higher keys up one slot. */
6538 int ksize = mc->mc_db->md_pad, dif;
6539 char *ptr = LEAF2KEY(mp, indx, ksize);
6540 dif = NUMKEYS(mp) - indx;
6542 memmove(ptr+ksize, ptr, dif*ksize);
6543 /* insert new key */
6544 memcpy(ptr, key->mv_data, ksize);
6546 /* Just using these for counting */
6547 mp->mp_lower += sizeof(indx_t);
6548 mp->mp_upper -= ksize - sizeof(indx_t);
6552 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6554 node_size += key->mv_size;
6556 mdb_cassert(mc, data);
6557 if (F_ISSET(flags, F_BIGDATA)) {
6558 /* Data already on overflow page. */
6559 node_size += sizeof(pgno_t);
6560 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
6561 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6563 /* Put data on overflow page. */
6564 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6565 data->mv_size, node_size+data->mv_size));
6566 node_size = EVEN(node_size + sizeof(pgno_t));
6567 if ((ssize_t)node_size > room)
6569 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6571 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6575 node_size += data->mv_size;
6578 node_size = EVEN(node_size);
6579 if ((ssize_t)node_size > room)
6583 /* Move higher pointers up one slot. */
6584 for (i = NUMKEYS(mp); i > indx; i--)
6585 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6587 /* Adjust free space offsets. */
6588 ofs = mp->mp_upper - node_size;
6589 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
6590 mp->mp_ptrs[indx] = ofs;
6592 mp->mp_lower += sizeof(indx_t);
6594 /* Write the node data. */
6595 node = NODEPTR(mp, indx);
6596 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6597 node->mn_flags = flags;
6599 SETDSZ(node,data->mv_size);
6604 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6607 mdb_cassert(mc, key);
6609 if (F_ISSET(flags, F_BIGDATA))
6610 memcpy(node->mn_data + key->mv_size, data->mv_data,
6612 else if (F_ISSET(flags, MDB_RESERVE))
6613 data->mv_data = node->mn_data + key->mv_size;
6615 memcpy(node->mn_data + key->mv_size, data->mv_data,
6618 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6620 if (F_ISSET(flags, MDB_RESERVE))
6621 data->mv_data = METADATA(ofp);
6623 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6630 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6631 mdb_dbg_pgno(mp), NUMKEYS(mp)));
6632 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6633 DPRINTF(("node size = %"Z"u", node_size));
6634 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6635 return MDB_PAGE_FULL;
6638 /** Delete the specified node from a page.
6639 * @param[in] mc Cursor pointing to the node to delete.
6640 * @param[in] ksize The size of a node. Only used if the page is
6641 * part of a #MDB_DUPFIXED database.
6644 mdb_node_del(MDB_cursor *mc, int ksize)
6646 MDB_page *mp = mc->mc_pg[mc->mc_top];
6647 indx_t indx = mc->mc_ki[mc->mc_top];
6649 indx_t i, j, numkeys, ptr;
6653 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6654 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
6655 numkeys = NUMKEYS(mp);
6656 mdb_cassert(mc, indx < numkeys);
6659 int x = numkeys - 1 - indx;
6660 base = LEAF2KEY(mp, indx, ksize);
6662 memmove(base, base + ksize, x * ksize);
6663 mp->mp_lower -= sizeof(indx_t);
6664 mp->mp_upper += ksize - sizeof(indx_t);
6668 node = NODEPTR(mp, indx);
6669 sz = NODESIZE + node->mn_ksize;
6671 if (F_ISSET(node->mn_flags, F_BIGDATA))
6672 sz += sizeof(pgno_t);
6674 sz += NODEDSZ(node);
6678 ptr = mp->mp_ptrs[indx];
6679 for (i = j = 0; i < numkeys; i++) {
6681 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6682 if (mp->mp_ptrs[i] < ptr)
6683 mp->mp_ptrs[j] += sz;
6688 base = (char *)mp + mp->mp_upper + PAGEBASE;
6689 memmove(base + sz, base, ptr - mp->mp_upper);
6691 mp->mp_lower -= sizeof(indx_t);
6695 /** Compact the main page after deleting a node on a subpage.
6696 * @param[in] mp The main page to operate on.
6697 * @param[in] indx The index of the subpage on the main page.
6700 mdb_node_shrink(MDB_page *mp, indx_t indx)
6706 indx_t i, numkeys, ptr;
6708 node = NODEPTR(mp, indx);
6709 sp = (MDB_page *)NODEDATA(node);
6710 delta = SIZELEFT(sp);
6711 xp = (MDB_page *)((char *)sp + delta);
6713 /* shift subpage upward */
6715 nsize = NUMKEYS(sp) * sp->mp_pad;
6717 return; /* do not make the node uneven-sized */
6718 memmove(METADATA(xp), METADATA(sp), nsize);
6721 numkeys = NUMKEYS(sp);
6722 for (i=numkeys-1; i>=0; i--)
6723 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6725 xp->mp_upper = sp->mp_lower;
6726 xp->mp_lower = sp->mp_lower;
6727 xp->mp_flags = sp->mp_flags;
6728 xp->mp_pad = sp->mp_pad;
6729 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6731 nsize = NODEDSZ(node) - delta;
6732 SETDSZ(node, nsize);
6734 /* shift lower nodes upward */
6735 ptr = mp->mp_ptrs[indx];
6736 numkeys = NUMKEYS(mp);
6737 for (i = 0; i < numkeys; i++) {
6738 if (mp->mp_ptrs[i] <= ptr)
6739 mp->mp_ptrs[i] += delta;
6742 base = (char *)mp + mp->mp_upper + PAGEBASE;
6743 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6744 mp->mp_upper += delta;
6747 /** Initial setup of a sorted-dups cursor.
6748 * Sorted duplicates are implemented as a sub-database for the given key.
6749 * The duplicate data items are actually keys of the sub-database.
6750 * Operations on the duplicate data items are performed using a sub-cursor
6751 * initialized when the sub-database is first accessed. This function does
6752 * the preliminary setup of the sub-cursor, filling in the fields that
6753 * depend only on the parent DB.
6754 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6757 mdb_xcursor_init0(MDB_cursor *mc)
6759 MDB_xcursor *mx = mc->mc_xcursor;
6761 mx->mx_cursor.mc_xcursor = NULL;
6762 mx->mx_cursor.mc_txn = mc->mc_txn;
6763 mx->mx_cursor.mc_db = &mx->mx_db;
6764 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6765 mx->mx_cursor.mc_dbi = mc->mc_dbi;
6766 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6767 mx->mx_cursor.mc_snum = 0;
6768 mx->mx_cursor.mc_top = 0;
6769 mx->mx_cursor.mc_flags = C_SUB;
6770 mx->mx_dbx.md_name.mv_size = 0;
6771 mx->mx_dbx.md_name.mv_data = NULL;
6772 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6773 mx->mx_dbx.md_dcmp = NULL;
6774 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6777 /** Final setup of a sorted-dups cursor.
6778 * Sets up the fields that depend on the data from the main cursor.
6779 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6780 * @param[in] node The data containing the #MDB_db record for the
6781 * sorted-dup database.
6784 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6786 MDB_xcursor *mx = mc->mc_xcursor;
6788 if (node->mn_flags & F_SUBDATA) {
6789 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6790 mx->mx_cursor.mc_pg[0] = 0;
6791 mx->mx_cursor.mc_snum = 0;
6792 mx->mx_cursor.mc_top = 0;
6793 mx->mx_cursor.mc_flags = C_SUB;
6795 MDB_page *fp = NODEDATA(node);
6796 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6797 mx->mx_db.md_flags = 0;
6798 mx->mx_db.md_depth = 1;
6799 mx->mx_db.md_branch_pages = 0;
6800 mx->mx_db.md_leaf_pages = 1;
6801 mx->mx_db.md_overflow_pages = 0;
6802 mx->mx_db.md_entries = NUMKEYS(fp);
6803 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6804 mx->mx_cursor.mc_snum = 1;
6805 mx->mx_cursor.mc_top = 0;
6806 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6807 mx->mx_cursor.mc_pg[0] = fp;
6808 mx->mx_cursor.mc_ki[0] = 0;
6809 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6810 mx->mx_db.md_flags = MDB_DUPFIXED;
6811 mx->mx_db.md_pad = fp->mp_pad;
6812 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6813 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6816 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
6817 mx->mx_db.md_root));
6818 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
6819 #if UINT_MAX < SIZE_MAX
6820 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6821 mx->mx_dbx.md_cmp = mdb_cmp_clong;
6825 /** Initialize a cursor for a given transaction and database. */
6827 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6830 mc->mc_backup = NULL;
6833 mc->mc_db = &txn->mt_dbs[dbi];
6834 mc->mc_dbx = &txn->mt_dbxs[dbi];
6835 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6840 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6841 mdb_tassert(txn, mx != NULL);
6842 mc->mc_xcursor = mx;
6843 mdb_xcursor_init0(mc);
6845 mc->mc_xcursor = NULL;
6847 if (*mc->mc_dbflag & DB_STALE) {
6848 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6853 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6856 size_t size = sizeof(MDB_cursor);
6858 if (!ret || !TXN_DBI_EXIST(txn, dbi))
6861 if (txn->mt_flags & MDB_TXN_ERROR)
6864 /* Allow read access to the freelist */
6865 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6868 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6869 size += sizeof(MDB_xcursor);
6871 if ((mc = malloc(size)) != NULL) {
6872 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6873 if (txn->mt_cursors) {
6874 mc->mc_next = txn->mt_cursors[dbi];
6875 txn->mt_cursors[dbi] = mc;
6876 mc->mc_flags |= C_UNTRACK;
6888 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6890 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi))
6893 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6896 if (txn->mt_flags & MDB_TXN_ERROR)
6899 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6903 /* Return the count of duplicate data items for the current key */
6905 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6909 if (mc == NULL || countp == NULL)
6912 if (mc->mc_xcursor == NULL)
6913 return MDB_INCOMPATIBLE;
6915 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
6918 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6919 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6922 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
6925 *countp = mc->mc_xcursor->mx_db.md_entries;
6931 mdb_cursor_close(MDB_cursor *mc)
6933 if (mc && !mc->mc_backup) {
6934 /* remove from txn, if tracked */
6935 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
6936 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
6937 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
6939 *prev = mc->mc_next;
6946 mdb_cursor_txn(MDB_cursor *mc)
6948 if (!mc) return NULL;
6953 mdb_cursor_dbi(MDB_cursor *mc)
6958 /** Replace the key for a branch node with a new key.
6959 * @param[in] mc Cursor pointing to the node to operate on.
6960 * @param[in] key The new key to use.
6961 * @return 0 on success, non-zero on failure.
6964 mdb_update_key(MDB_cursor *mc, MDB_val *key)
6970 int delta, ksize, oksize;
6971 indx_t ptr, i, numkeys, indx;
6974 indx = mc->mc_ki[mc->mc_top];
6975 mp = mc->mc_pg[mc->mc_top];
6976 node = NODEPTR(mp, indx);
6977 ptr = mp->mp_ptrs[indx];
6981 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
6982 k2.mv_data = NODEKEY(node);
6983 k2.mv_size = node->mn_ksize;
6984 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
6986 mdb_dkey(&k2, kbuf2),
6992 /* Sizes must be 2-byte aligned. */
6993 ksize = EVEN(key->mv_size);
6994 oksize = EVEN(node->mn_ksize);
6995 delta = ksize - oksize;
6997 /* Shift node contents if EVEN(key length) changed. */
6999 if (delta > 0 && SIZELEFT(mp) < delta) {
7001 /* not enough space left, do a delete and split */
7002 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7003 pgno = NODEPGNO(node);
7004 mdb_node_del(mc, 0);
7005 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7008 numkeys = NUMKEYS(mp);
7009 for (i = 0; i < numkeys; i++) {
7010 if (mp->mp_ptrs[i] <= ptr)
7011 mp->mp_ptrs[i] -= delta;
7014 base = (char *)mp + mp->mp_upper + PAGEBASE;
7015 len = ptr - mp->mp_upper + NODESIZE;
7016 memmove(base - delta, base, len);
7017 mp->mp_upper -= delta;
7019 node = NODEPTR(mp, indx);
7022 /* But even if no shift was needed, update ksize */
7023 if (node->mn_ksize != key->mv_size)
7024 node->mn_ksize = key->mv_size;
7027 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7033 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7035 /** Move a node from csrc to cdst.
7038 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
7045 unsigned short flags;
7049 /* Mark src and dst as dirty. */
7050 if ((rc = mdb_page_touch(csrc)) ||
7051 (rc = mdb_page_touch(cdst)))
7054 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7055 key.mv_size = csrc->mc_db->md_pad;
7056 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7058 data.mv_data = NULL;
7062 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7063 mdb_cassert(csrc, !((size_t)srcnode & 1));
7064 srcpg = NODEPGNO(srcnode);
7065 flags = srcnode->mn_flags;
7066 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7067 unsigned int snum = csrc->mc_snum;
7069 /* must find the lowest key below src */
7070 rc = mdb_page_search_lowest(csrc);
7073 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7074 key.mv_size = csrc->mc_db->md_pad;
7075 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7077 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7078 key.mv_size = NODEKSZ(s2);
7079 key.mv_data = NODEKEY(s2);
7081 csrc->mc_snum = snum--;
7082 csrc->mc_top = snum;
7084 key.mv_size = NODEKSZ(srcnode);
7085 key.mv_data = NODEKEY(srcnode);
7087 data.mv_size = NODEDSZ(srcnode);
7088 data.mv_data = NODEDATA(srcnode);
7090 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7091 unsigned int snum = cdst->mc_snum;
7094 /* must find the lowest key below dst */
7095 mdb_cursor_copy(cdst, &mn);
7096 rc = mdb_page_search_lowest(&mn);
7099 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7100 bkey.mv_size = mn.mc_db->md_pad;
7101 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7103 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7104 bkey.mv_size = NODEKSZ(s2);
7105 bkey.mv_data = NODEKEY(s2);
7107 mn.mc_snum = snum--;
7110 rc = mdb_update_key(&mn, &bkey);
7115 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7116 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7117 csrc->mc_ki[csrc->mc_top],
7119 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7120 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7122 /* Add the node to the destination page.
7124 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7125 if (rc != MDB_SUCCESS)
7128 /* Delete the node from the source page.
7130 mdb_node_del(csrc, key.mv_size);
7133 /* Adjust other cursors pointing to mp */
7134 MDB_cursor *m2, *m3;
7135 MDB_dbi dbi = csrc->mc_dbi;
7136 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
7138 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7139 if (csrc->mc_flags & C_SUB)
7140 m3 = &m2->mc_xcursor->mx_cursor;
7143 if (m3 == csrc) continue;
7144 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
7145 csrc->mc_ki[csrc->mc_top]) {
7146 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7147 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7152 /* Update the parent separators.
7154 if (csrc->mc_ki[csrc->mc_top] == 0) {
7155 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7156 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7157 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7159 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7160 key.mv_size = NODEKSZ(srcnode);
7161 key.mv_data = NODEKEY(srcnode);
7163 DPRINTF(("update separator for source page %"Z"u to [%s]",
7164 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7165 mdb_cursor_copy(csrc, &mn);
7168 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7171 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7173 indx_t ix = csrc->mc_ki[csrc->mc_top];
7174 nullkey.mv_size = 0;
7175 csrc->mc_ki[csrc->mc_top] = 0;
7176 rc = mdb_update_key(csrc, &nullkey);
7177 csrc->mc_ki[csrc->mc_top] = ix;
7178 mdb_cassert(csrc, rc == MDB_SUCCESS);
7182 if (cdst->mc_ki[cdst->mc_top] == 0) {
7183 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7184 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7185 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7187 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7188 key.mv_size = NODEKSZ(srcnode);
7189 key.mv_data = NODEKEY(srcnode);
7191 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7192 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7193 mdb_cursor_copy(cdst, &mn);
7196 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7199 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7201 indx_t ix = cdst->mc_ki[cdst->mc_top];
7202 nullkey.mv_size = 0;
7203 cdst->mc_ki[cdst->mc_top] = 0;
7204 rc = mdb_update_key(cdst, &nullkey);
7205 cdst->mc_ki[cdst->mc_top] = ix;
7206 mdb_cassert(csrc, rc == MDB_SUCCESS);
7213 /** Merge one page into another.
7214 * The nodes from the page pointed to by \b csrc will
7215 * be copied to the page pointed to by \b cdst and then
7216 * the \b csrc page will be freed.
7217 * @param[in] csrc Cursor pointing to the source page.
7218 * @param[in] cdst Cursor pointing to the destination page.
7219 * @return 0 on success, non-zero on failure.
7222 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7224 MDB_page *psrc, *pdst;
7231 psrc = csrc->mc_pg[csrc->mc_top];
7232 pdst = cdst->mc_pg[cdst->mc_top];
7234 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7236 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7237 mdb_cassert(csrc, cdst->mc_snum > 1);
7239 /* Mark dst as dirty. */
7240 if ((rc = mdb_page_touch(cdst)))
7243 /* Move all nodes from src to dst.
7245 j = nkeys = NUMKEYS(pdst);
7246 if (IS_LEAF2(psrc)) {
7247 key.mv_size = csrc->mc_db->md_pad;
7248 key.mv_data = METADATA(psrc);
7249 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7250 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7251 if (rc != MDB_SUCCESS)
7253 key.mv_data = (char *)key.mv_data + key.mv_size;
7256 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7257 srcnode = NODEPTR(psrc, i);
7258 if (i == 0 && IS_BRANCH(psrc)) {
7261 mdb_cursor_copy(csrc, &mn);
7262 /* must find the lowest key below src */
7263 rc = mdb_page_search_lowest(&mn);
7266 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7267 key.mv_size = mn.mc_db->md_pad;
7268 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7270 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7271 key.mv_size = NODEKSZ(s2);
7272 key.mv_data = NODEKEY(s2);
7275 key.mv_size = srcnode->mn_ksize;
7276 key.mv_data = NODEKEY(srcnode);
7279 data.mv_size = NODEDSZ(srcnode);
7280 data.mv_data = NODEDATA(srcnode);
7281 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7282 if (rc != MDB_SUCCESS)
7287 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7288 pdst->mp_pgno, NUMKEYS(pdst),
7289 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7291 /* Unlink the src page from parent and add to free list.
7294 mdb_node_del(csrc, 0);
7295 if (csrc->mc_ki[csrc->mc_top] == 0) {
7297 rc = mdb_update_key(csrc, &key);
7305 psrc = csrc->mc_pg[csrc->mc_top];
7306 /* If not operating on FreeDB, allow this page to be reused
7307 * in this txn. Otherwise just add to free list.
7309 rc = mdb_page_loose(csrc, psrc);
7313 csrc->mc_db->md_leaf_pages--;
7315 csrc->mc_db->md_branch_pages--;
7317 /* Adjust other cursors pointing to mp */
7318 MDB_cursor *m2, *m3;
7319 MDB_dbi dbi = csrc->mc_dbi;
7321 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7322 if (csrc->mc_flags & C_SUB)
7323 m3 = &m2->mc_xcursor->mx_cursor;
7326 if (m3 == csrc) continue;
7327 if (m3->mc_snum < csrc->mc_snum) continue;
7328 if (m3->mc_pg[csrc->mc_top] == psrc) {
7329 m3->mc_pg[csrc->mc_top] = pdst;
7330 m3->mc_ki[csrc->mc_top] += nkeys;
7335 unsigned int snum = cdst->mc_snum;
7336 uint16_t depth = cdst->mc_db->md_depth;
7337 mdb_cursor_pop(cdst);
7338 rc = mdb_rebalance(cdst);
7339 /* Did the tree shrink? */
7340 if (depth > cdst->mc_db->md_depth)
7342 cdst->mc_snum = snum;
7343 cdst->mc_top = snum-1;
7348 /** Copy the contents of a cursor.
7349 * @param[in] csrc The cursor to copy from.
7350 * @param[out] cdst The cursor to copy to.
7353 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7357 cdst->mc_txn = csrc->mc_txn;
7358 cdst->mc_dbi = csrc->mc_dbi;
7359 cdst->mc_db = csrc->mc_db;
7360 cdst->mc_dbx = csrc->mc_dbx;
7361 cdst->mc_snum = csrc->mc_snum;
7362 cdst->mc_top = csrc->mc_top;
7363 cdst->mc_flags = csrc->mc_flags;
7365 for (i=0; i<csrc->mc_snum; i++) {
7366 cdst->mc_pg[i] = csrc->mc_pg[i];
7367 cdst->mc_ki[i] = csrc->mc_ki[i];
7371 /** Rebalance the tree after a delete operation.
7372 * @param[in] mc Cursor pointing to the page where rebalancing
7374 * @return 0 on success, non-zero on failure.
7377 mdb_rebalance(MDB_cursor *mc)
7381 unsigned int ptop, minkeys;
7385 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7386 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7387 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7388 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7389 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7391 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7392 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7393 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7394 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7398 if (mc->mc_snum < 2) {
7399 MDB_page *mp = mc->mc_pg[0];
7401 DPUTS("Can't rebalance a subpage, ignoring");
7404 if (NUMKEYS(mp) == 0) {
7405 DPUTS("tree is completely empty");
7406 mc->mc_db->md_root = P_INVALID;
7407 mc->mc_db->md_depth = 0;
7408 mc->mc_db->md_leaf_pages = 0;
7409 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7412 /* Adjust cursors pointing to mp */
7415 mc->mc_flags &= ~C_INITIALIZED;
7417 MDB_cursor *m2, *m3;
7418 MDB_dbi dbi = mc->mc_dbi;
7420 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7421 if (mc->mc_flags & C_SUB)
7422 m3 = &m2->mc_xcursor->mx_cursor;
7425 if (m3->mc_snum < mc->mc_snum) continue;
7426 if (m3->mc_pg[0] == mp) {
7429 m3->mc_flags &= ~C_INITIALIZED;
7433 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7435 DPUTS("collapsing root page!");
7436 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7439 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7440 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7443 mc->mc_db->md_depth--;
7444 mc->mc_db->md_branch_pages--;
7445 mc->mc_ki[0] = mc->mc_ki[1];
7446 for (i = 1; i<mc->mc_db->md_depth; i++) {
7447 mc->mc_pg[i] = mc->mc_pg[i+1];
7448 mc->mc_ki[i] = mc->mc_ki[i+1];
7451 /* Adjust other cursors pointing to mp */
7452 MDB_cursor *m2, *m3;
7453 MDB_dbi dbi = mc->mc_dbi;
7455 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7456 if (mc->mc_flags & C_SUB)
7457 m3 = &m2->mc_xcursor->mx_cursor;
7460 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7461 if (m3->mc_pg[0] == mp) {
7464 for (i=0; i<m3->mc_snum; i++) {
7465 m3->mc_pg[i] = m3->mc_pg[i+1];
7466 m3->mc_ki[i] = m3->mc_ki[i+1];
7472 DPUTS("root page doesn't need rebalancing");
7476 /* The parent (branch page) must have at least 2 pointers,
7477 * otherwise the tree is invalid.
7479 ptop = mc->mc_top-1;
7480 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
7482 /* Leaf page fill factor is below the threshold.
7483 * Try to move keys from left or right neighbor, or
7484 * merge with a neighbor page.
7489 mdb_cursor_copy(mc, &mn);
7490 mn.mc_xcursor = NULL;
7492 oldki = mc->mc_ki[mc->mc_top];
7493 if (mc->mc_ki[ptop] == 0) {
7494 /* We're the leftmost leaf in our parent.
7496 DPUTS("reading right neighbor");
7498 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7499 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7502 mn.mc_ki[mn.mc_top] = 0;
7503 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7505 /* There is at least one neighbor to the left.
7507 DPUTS("reading left neighbor");
7509 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7510 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7513 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7514 mc->mc_ki[mc->mc_top] = 0;
7517 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7518 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7519 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7521 /* If the neighbor page is above threshold and has enough keys,
7522 * move one key from it. Otherwise we should try to merge them.
7523 * (A branch page must never have less than 2 keys.)
7525 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7526 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
7527 rc = mdb_node_move(&mn, mc);
7528 if (mc->mc_ki[ptop]) {
7532 if (mc->mc_ki[ptop] == 0) {
7533 rc = mdb_page_merge(&mn, mc);
7535 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
7536 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7537 rc = mdb_page_merge(mc, &mn);
7538 mdb_cursor_copy(&mn, mc);
7540 mc->mc_flags &= ~C_EOF;
7542 mc->mc_ki[mc->mc_top] = oldki;
7546 /** Complete a delete operation started by #mdb_cursor_del(). */
7548 mdb_cursor_del0(MDB_cursor *mc)
7555 ki = mc->mc_ki[mc->mc_top];
7556 mdb_node_del(mc, mc->mc_db->md_pad);
7557 mc->mc_db->md_entries--;
7558 rc = mdb_rebalance(mc);
7560 if (rc == MDB_SUCCESS) {
7561 MDB_cursor *m2, *m3;
7562 MDB_dbi dbi = mc->mc_dbi;
7564 mp = mc->mc_pg[mc->mc_top];
7565 nkeys = NUMKEYS(mp);
7567 /* if mc points past last node in page, find next sibling */
7568 if (mc->mc_ki[mc->mc_top] >= nkeys) {
7569 rc = mdb_cursor_sibling(mc, 1);
7570 if (rc == MDB_NOTFOUND) {
7571 mc->mc_flags |= C_EOF;
7576 /* Adjust other cursors pointing to mp */
7577 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
7578 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
7579 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7581 if (m3 == mc || m3->mc_snum < mc->mc_snum)
7583 if (m3->mc_pg[mc->mc_top] == mp) {
7584 if (m3->mc_ki[mc->mc_top] >= ki) {
7585 m3->mc_flags |= C_DEL;
7586 if (m3->mc_ki[mc->mc_top] > ki)
7587 m3->mc_ki[mc->mc_top]--;
7589 if (m3->mc_ki[mc->mc_top] >= nkeys) {
7590 rc = mdb_cursor_sibling(m3, 1);
7591 if (rc == MDB_NOTFOUND) {
7592 m3->mc_flags |= C_EOF;
7598 mc->mc_flags |= C_DEL;
7602 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7607 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7608 MDB_val *key, MDB_val *data)
7610 if (!key || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
7613 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7614 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7616 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7617 /* must ignore any data */
7621 return mdb_del0(txn, dbi, key, data, 0);
7625 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
7626 MDB_val *key, MDB_val *data, unsigned flags)
7631 MDB_val rdata, *xdata;
7635 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7637 mdb_cursor_init(&mc, txn, dbi, &mx);
7646 flags |= MDB_NODUPDATA;
7648 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7650 /* let mdb_page_split know about this cursor if needed:
7651 * delete will trigger a rebalance; if it needs to move
7652 * a node from one page to another, it will have to
7653 * update the parent's separator key(s). If the new sepkey
7654 * is larger than the current one, the parent page may
7655 * run out of space, triggering a split. We need this
7656 * cursor to be consistent until the end of the rebalance.
7658 mc.mc_flags |= C_UNTRACK;
7659 mc.mc_next = txn->mt_cursors[dbi];
7660 txn->mt_cursors[dbi] = &mc;
7661 rc = mdb_cursor_del(&mc, flags);
7662 txn->mt_cursors[dbi] = mc.mc_next;
7667 /** Split a page and insert a new node.
7668 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7669 * The cursor will be updated to point to the actual page and index where
7670 * the node got inserted after the split.
7671 * @param[in] newkey The key for the newly inserted node.
7672 * @param[in] newdata The data for the newly inserted node.
7673 * @param[in] newpgno The page number, if the new node is a branch node.
7674 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7675 * @return 0 on success, non-zero on failure.
7678 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7679 unsigned int nflags)
7682 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7685 int i, j, split_indx, nkeys, pmax;
7686 MDB_env *env = mc->mc_txn->mt_env;
7688 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7689 MDB_page *copy = NULL;
7690 MDB_page *mp, *rp, *pp;
7695 mp = mc->mc_pg[mc->mc_top];
7696 newindx = mc->mc_ki[mc->mc_top];
7697 nkeys = NUMKEYS(mp);
7699 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
7700 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7701 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
7703 /* Create a right sibling. */
7704 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7706 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7708 if (mc->mc_snum < 2) {
7709 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7711 /* shift current top to make room for new parent */
7712 mc->mc_pg[1] = mc->mc_pg[0];
7713 mc->mc_ki[1] = mc->mc_ki[0];
7716 mc->mc_db->md_root = pp->mp_pgno;
7717 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7718 mc->mc_db->md_depth++;
7721 /* Add left (implicit) pointer. */
7722 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7723 /* undo the pre-push */
7724 mc->mc_pg[0] = mc->mc_pg[1];
7725 mc->mc_ki[0] = mc->mc_ki[1];
7726 mc->mc_db->md_root = mp->mp_pgno;
7727 mc->mc_db->md_depth--;
7734 ptop = mc->mc_top-1;
7735 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7738 mc->mc_flags |= C_SPLITTING;
7739 mdb_cursor_copy(mc, &mn);
7740 mn.mc_pg[mn.mc_top] = rp;
7741 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7743 if (nflags & MDB_APPEND) {
7744 mn.mc_ki[mn.mc_top] = 0;
7746 split_indx = newindx;
7750 split_indx = (nkeys+1) / 2;
7755 unsigned int lsize, rsize, ksize;
7756 /* Move half of the keys to the right sibling */
7757 x = mc->mc_ki[mc->mc_top] - split_indx;
7758 ksize = mc->mc_db->md_pad;
7759 split = LEAF2KEY(mp, split_indx, ksize);
7760 rsize = (nkeys - split_indx) * ksize;
7761 lsize = (nkeys - split_indx) * sizeof(indx_t);
7762 mp->mp_lower -= lsize;
7763 rp->mp_lower += lsize;
7764 mp->mp_upper += rsize - lsize;
7765 rp->mp_upper -= rsize - lsize;
7766 sepkey.mv_size = ksize;
7767 if (newindx == split_indx) {
7768 sepkey.mv_data = newkey->mv_data;
7770 sepkey.mv_data = split;
7773 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7774 memcpy(rp->mp_ptrs, split, rsize);
7775 sepkey.mv_data = rp->mp_ptrs;
7776 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7777 memcpy(ins, newkey->mv_data, ksize);
7778 mp->mp_lower += sizeof(indx_t);
7779 mp->mp_upper -= ksize - sizeof(indx_t);
7782 memcpy(rp->mp_ptrs, split, x * ksize);
7783 ins = LEAF2KEY(rp, x, ksize);
7784 memcpy(ins, newkey->mv_data, ksize);
7785 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7786 rp->mp_lower += sizeof(indx_t);
7787 rp->mp_upper -= ksize - sizeof(indx_t);
7788 mc->mc_ki[mc->mc_top] = x;
7789 mc->mc_pg[mc->mc_top] = rp;
7792 int psize, nsize, k;
7793 /* Maximum free space in an empty page */
7794 pmax = env->me_psize - PAGEHDRSZ;
7796 nsize = mdb_leaf_size(env, newkey, newdata);
7798 nsize = mdb_branch_size(env, newkey);
7799 nsize = EVEN(nsize);
7801 /* grab a page to hold a temporary copy */
7802 copy = mdb_page_malloc(mc->mc_txn, 1);
7807 copy->mp_pgno = mp->mp_pgno;
7808 copy->mp_flags = mp->mp_flags;
7809 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
7810 copy->mp_upper = env->me_psize - PAGEBASE;
7812 /* prepare to insert */
7813 for (i=0, j=0; i<nkeys; i++) {
7815 copy->mp_ptrs[j++] = 0;
7817 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
7820 /* When items are relatively large the split point needs
7821 * to be checked, because being off-by-one will make the
7822 * difference between success or failure in mdb_node_add.
7824 * It's also relevant if a page happens to be laid out
7825 * such that one half of its nodes are all "small" and
7826 * the other half of its nodes are "large." If the new
7827 * item is also "large" and falls on the half with
7828 * "large" nodes, it also may not fit.
7830 * As a final tweak, if the new item goes on the last
7831 * spot on the page (and thus, onto the new page), bias
7832 * the split so the new page is emptier than the old page.
7833 * This yields better packing during sequential inserts.
7835 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
7836 /* Find split point */
7838 if (newindx <= split_indx || newindx >= nkeys) {
7840 k = newindx >= nkeys ? nkeys : split_indx+2;
7845 for (; i!=k; i+=j) {
7850 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
7851 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7853 if (F_ISSET(node->mn_flags, F_BIGDATA))
7854 psize += sizeof(pgno_t);
7856 psize += NODEDSZ(node);
7858 psize = EVEN(psize);
7860 if (psize > pmax || i == k-j) {
7861 split_indx = i + (j<0);
7866 if (split_indx == newindx) {
7867 sepkey.mv_size = newkey->mv_size;
7868 sepkey.mv_data = newkey->mv_data;
7870 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
7871 sepkey.mv_size = node->mn_ksize;
7872 sepkey.mv_data = NODEKEY(node);
7877 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
7879 /* Copy separator key to the parent.
7881 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
7885 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7890 if (mn.mc_snum == mc->mc_snum) {
7891 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7892 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7893 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7894 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7899 /* Right page might now have changed parent.
7900 * Check if left page also changed parent.
7902 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7903 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7904 for (i=0; i<ptop; i++) {
7905 mc->mc_pg[i] = mn.mc_pg[i];
7906 mc->mc_ki[i] = mn.mc_ki[i];
7908 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7909 if (mn.mc_ki[ptop]) {
7910 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7912 /* find right page's left sibling */
7913 mc->mc_ki[ptop] = mn.mc_ki[ptop];
7914 mdb_cursor_sibling(mc, 0);
7919 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7922 mc->mc_flags ^= C_SPLITTING;
7923 if (rc != MDB_SUCCESS) {
7926 if (nflags & MDB_APPEND) {
7927 mc->mc_pg[mc->mc_top] = rp;
7928 mc->mc_ki[mc->mc_top] = 0;
7929 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
7932 for (i=0; i<mc->mc_top; i++)
7933 mc->mc_ki[i] = mn.mc_ki[i];
7934 } else if (!IS_LEAF2(mp)) {
7936 mc->mc_pg[mc->mc_top] = rp;
7941 rkey.mv_data = newkey->mv_data;
7942 rkey.mv_size = newkey->mv_size;
7948 /* Update index for the new key. */
7949 mc->mc_ki[mc->mc_top] = j;
7951 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
7952 rkey.mv_data = NODEKEY(node);
7953 rkey.mv_size = node->mn_ksize;
7955 xdata.mv_data = NODEDATA(node);
7956 xdata.mv_size = NODEDSZ(node);
7959 pgno = NODEPGNO(node);
7960 flags = node->mn_flags;
7963 if (!IS_LEAF(mp) && j == 0) {
7964 /* First branch index doesn't need key data. */
7968 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
7974 mc->mc_pg[mc->mc_top] = copy;
7979 } while (i != split_indx);
7981 nkeys = NUMKEYS(copy);
7982 for (i=0; i<nkeys; i++)
7983 mp->mp_ptrs[i] = copy->mp_ptrs[i];
7984 mp->mp_lower = copy->mp_lower;
7985 mp->mp_upper = copy->mp_upper;
7986 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
7987 env->me_psize - copy->mp_upper - PAGEBASE);
7989 /* reset back to original page */
7990 if (newindx < split_indx) {
7991 mc->mc_pg[mc->mc_top] = mp;
7992 if (nflags & MDB_RESERVE) {
7993 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7994 if (!(node->mn_flags & F_BIGDATA))
7995 newdata->mv_data = NODEDATA(node);
7998 mc->mc_pg[mc->mc_top] = rp;
8000 /* Make sure mc_ki is still valid.
8002 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8003 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8004 for (i=0; i<=ptop; i++) {
8005 mc->mc_pg[i] = mn.mc_pg[i];
8006 mc->mc_ki[i] = mn.mc_ki[i];
8013 /* Adjust other cursors pointing to mp */
8014 MDB_cursor *m2, *m3;
8015 MDB_dbi dbi = mc->mc_dbi;
8016 int fixup = NUMKEYS(mp);
8018 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8019 if (mc->mc_flags & C_SUB)
8020 m3 = &m2->mc_xcursor->mx_cursor;
8025 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8027 if (m3->mc_flags & C_SPLITTING)
8032 for (k=m3->mc_top; k>=0; k--) {
8033 m3->mc_ki[k+1] = m3->mc_ki[k];
8034 m3->mc_pg[k+1] = m3->mc_pg[k];
8036 if (m3->mc_ki[0] >= split_indx) {
8041 m3->mc_pg[0] = mc->mc_pg[0];
8045 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8046 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8047 m3->mc_ki[mc->mc_top]++;
8048 if (m3->mc_ki[mc->mc_top] >= fixup) {
8049 m3->mc_pg[mc->mc_top] = rp;
8050 m3->mc_ki[mc->mc_top] -= fixup;
8051 m3->mc_ki[ptop] = mn.mc_ki[ptop];
8053 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8054 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8059 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8062 if (copy) /* tmp page */
8063 mdb_page_free(env, copy);
8065 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8070 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8071 MDB_val *key, MDB_val *data, unsigned int flags)
8076 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8079 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
8082 mdb_cursor_init(&mc, txn, dbi, &mx);
8083 return mdb_cursor_put(&mc, key, data, flags);
8087 #define MDB_WBUF (1024*1024)
8090 /** State needed for a compacting copy. */
8091 typedef struct mdb_copy {
8092 pthread_mutex_t mc_mutex;
8093 pthread_cond_t mc_cond;
8100 pgno_t mc_next_pgno;
8103 volatile int mc_new;
8108 /** Dedicated writer thread for compacting copy. */
8109 static THREAD_RET ESECT
8110 mdb_env_copythr(void *arg)
8114 int toggle = 0, wsize, rc;
8117 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8120 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8123 pthread_mutex_lock(&my->mc_mutex);
8125 pthread_cond_signal(&my->mc_cond);
8128 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8129 if (my->mc_new < 0) {
8134 wsize = my->mc_wlen[toggle];
8135 ptr = my->mc_wbuf[toggle];
8138 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8142 } else if (len > 0) {
8156 /* If there's an overflow page tail, write it too */
8157 if (my->mc_olen[toggle]) {
8158 wsize = my->mc_olen[toggle];
8159 ptr = my->mc_over[toggle];
8160 my->mc_olen[toggle] = 0;
8163 my->mc_wlen[toggle] = 0;
8165 pthread_cond_signal(&my->mc_cond);
8167 pthread_cond_signal(&my->mc_cond);
8168 pthread_mutex_unlock(&my->mc_mutex);
8169 return (THREAD_RET)0;
8173 /** Tell the writer thread there's a buffer ready to write */
8175 mdb_env_cthr_toggle(mdb_copy *my, int st)
8177 int toggle = my->mc_toggle ^ 1;
8178 pthread_mutex_lock(&my->mc_mutex);
8179 if (my->mc_status) {
8180 pthread_mutex_unlock(&my->mc_mutex);
8181 return my->mc_status;
8183 while (my->mc_new == 1)
8184 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8186 my->mc_toggle = toggle;
8187 pthread_cond_signal(&my->mc_cond);
8188 pthread_mutex_unlock(&my->mc_mutex);
8192 /** Depth-first tree traversal for compacting copy. */
8194 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8197 MDB_txn *txn = my->mc_txn;
8199 MDB_page *mo, *mp, *leaf;
8204 /* Empty DB, nothing to do */
8205 if (*pg == P_INVALID)
8212 rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
8215 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8219 /* Make cursor pages writable */
8220 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8224 for (i=0; i<mc.mc_top; i++) {
8225 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8226 mc.mc_pg[i] = (MDB_page *)ptr;
8227 ptr += my->mc_env->me_psize;
8230 /* This is writable space for a leaf page. Usually not needed. */
8231 leaf = (MDB_page *)ptr;
8233 toggle = my->mc_toggle;
8234 while (mc.mc_snum > 0) {
8236 mp = mc.mc_pg[mc.mc_top];
8240 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8241 for (i=0; i<n; i++) {
8242 ni = NODEPTR(mp, i);
8243 if (ni->mn_flags & F_BIGDATA) {
8247 /* Need writable leaf */
8249 mc.mc_pg[mc.mc_top] = leaf;
8250 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8252 ni = NODEPTR(mp, i);
8255 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8256 rc = mdb_page_get(txn, pg, &omp, NULL);
8259 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8260 rc = mdb_env_cthr_toggle(my, 1);
8263 toggle = my->mc_toggle;
8265 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8266 memcpy(mo, omp, my->mc_env->me_psize);
8267 mo->mp_pgno = my->mc_next_pgno;
8268 my->mc_next_pgno += omp->mp_pages;
8269 my->mc_wlen[toggle] += my->mc_env->me_psize;
8270 if (omp->mp_pages > 1) {
8271 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
8272 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
8273 rc = mdb_env_cthr_toggle(my, 1);
8276 toggle = my->mc_toggle;
8278 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
8279 } else if (ni->mn_flags & F_SUBDATA) {
8282 /* Need writable leaf */
8284 mc.mc_pg[mc.mc_top] = leaf;
8285 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8287 ni = NODEPTR(mp, i);
8290 memcpy(&db, NODEDATA(ni), sizeof(db));
8291 my->mc_toggle = toggle;
8292 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
8295 toggle = my->mc_toggle;
8296 memcpy(NODEDATA(ni), &db, sizeof(db));
8301 mc.mc_ki[mc.mc_top]++;
8302 if (mc.mc_ki[mc.mc_top] < n) {
8305 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
8307 rc = mdb_page_get(txn, pg, &mp, NULL);
8312 mc.mc_ki[mc.mc_top] = 0;
8313 if (IS_BRANCH(mp)) {
8314 /* Whenever we advance to a sibling branch page,
8315 * we must proceed all the way down to its first leaf.
8317 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
8320 mc.mc_pg[mc.mc_top] = mp;
8324 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8325 rc = mdb_env_cthr_toggle(my, 1);
8328 toggle = my->mc_toggle;
8330 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8331 mdb_page_copy(mo, mp, my->mc_env->me_psize);
8332 mo->mp_pgno = my->mc_next_pgno++;
8333 my->mc_wlen[toggle] += my->mc_env->me_psize;
8335 /* Update parent if there is one */
8336 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
8337 SETPGNO(ni, mo->mp_pgno);
8338 mdb_cursor_pop(&mc);
8340 /* Otherwise we're done */
8350 /** Copy environment with compaction. */
8352 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
8357 MDB_txn *txn = NULL;
8362 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
8363 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
8364 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_psize);
8365 if (my.mc_wbuf[0] == NULL)
8368 pthread_mutex_init(&my.mc_mutex, NULL);
8369 pthread_cond_init(&my.mc_cond, NULL);
8370 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_psize, MDB_WBUF*2);
8374 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
8379 my.mc_next_pgno = 2;
8385 THREAD_CREATE(thr, mdb_env_copythr, &my);
8387 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8391 mp = (MDB_page *)my.mc_wbuf[0];
8392 memset(mp, 0, 2*env->me_psize);
8394 mp->mp_flags = P_META;
8395 mm = (MDB_meta *)METADATA(mp);
8396 mdb_env_init_meta0(env, mm);
8397 mm->mm_address = env->me_metas[0]->mm_address;
8399 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
8401 mp->mp_flags = P_META;
8402 *(MDB_meta *)METADATA(mp) = *mm;
8403 mm = (MDB_meta *)METADATA(mp);
8405 /* Count the number of free pages, subtract from lastpg to find
8406 * number of active pages
8409 MDB_ID freecount = 0;
8412 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
8413 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
8414 freecount += *(MDB_ID *)data.mv_data;
8415 freecount += txn->mt_dbs[0].md_branch_pages +
8416 txn->mt_dbs[0].md_leaf_pages +
8417 txn->mt_dbs[0].md_overflow_pages;
8419 /* Set metapage 1 */
8420 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
8421 mm->mm_dbs[1] = txn->mt_dbs[1];
8422 mm->mm_dbs[1].md_root = mm->mm_last_pg;
8425 my.mc_wlen[0] = env->me_psize * 2;
8427 pthread_mutex_lock(&my.mc_mutex);
8429 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8430 pthread_mutex_unlock(&my.mc_mutex);
8431 rc = mdb_env_cwalk(&my, &txn->mt_dbs[1].md_root, 0);
8432 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
8433 rc = mdb_env_cthr_toggle(&my, 1);
8434 mdb_env_cthr_toggle(&my, -1);
8435 pthread_mutex_lock(&my.mc_mutex);
8437 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8438 pthread_mutex_unlock(&my.mc_mutex);
8443 CloseHandle(my.mc_cond);
8444 CloseHandle(my.mc_mutex);
8445 _aligned_free(my.mc_wbuf[0]);
8447 pthread_cond_destroy(&my.mc_cond);
8448 pthread_mutex_destroy(&my.mc_mutex);
8449 free(my.mc_wbuf[0]);
8454 /** Copy environment as-is. */
8456 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
8458 MDB_txn *txn = NULL;
8464 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8468 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8471 /* Do the lock/unlock of the reader mutex before starting the
8472 * write txn. Otherwise other read txns could block writers.
8474 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8479 /* We must start the actual read txn after blocking writers */
8480 mdb_txn_reset0(txn, "reset-stage1");
8482 /* Temporarily block writers until we snapshot the meta pages */
8485 rc = mdb_txn_renew0(txn);
8487 UNLOCK_MUTEX_W(env);
8492 wsize = env->me_psize * 2;
8496 DO_WRITE(rc, fd, ptr, w2, len);
8500 } else if (len > 0) {
8506 /* Non-blocking or async handles are not supported */
8512 UNLOCK_MUTEX_W(env);
8517 w2 = txn->mt_next_pgno * env->me_psize;
8520 LARGE_INTEGER fsize;
8521 GetFileSizeEx(env->me_fd, &fsize);
8522 if (w2 > fsize.QuadPart)
8523 w2 = fsize.QuadPart;
8528 fstat(env->me_fd, &st);
8529 if (w2 > (size_t)st.st_size)
8535 if (wsize > MAX_WRITE)
8539 DO_WRITE(rc, fd, ptr, w2, len);
8543 } else if (len > 0) {
8560 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
8562 if (flags & MDB_CP_COMPACT)
8563 return mdb_env_copyfd1(env, fd);
8565 return mdb_env_copyfd0(env, fd);
8569 mdb_env_copyfd(MDB_env *env, HANDLE fd)
8571 return mdb_env_copyfd2(env, fd, 0);
8575 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
8579 HANDLE newfd = INVALID_HANDLE_VALUE;
8581 if (env->me_flags & MDB_NOSUBDIR) {
8582 lpath = (char *)path;
8585 len += sizeof(DATANAME);
8586 lpath = malloc(len);
8589 sprintf(lpath, "%s" DATANAME, path);
8592 /* The destination path must exist, but the destination file must not.
8593 * We don't want the OS to cache the writes, since the source data is
8594 * already in the OS cache.
8597 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
8598 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
8600 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
8602 if (newfd == INVALID_HANDLE_VALUE) {
8608 /* Set O_DIRECT if the file system supports it */
8609 if ((rc = fcntl(newfd, F_GETFL)) != -1)
8610 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
8612 #ifdef F_NOCACHE /* __APPLE__ */
8613 rc = fcntl(newfd, F_NOCACHE, 1);
8620 rc = mdb_env_copyfd2(env, newfd, flags);
8623 if (!(env->me_flags & MDB_NOSUBDIR))
8625 if (newfd != INVALID_HANDLE_VALUE)
8626 if (close(newfd) < 0 && rc == MDB_SUCCESS)
8633 mdb_env_copy(MDB_env *env, const char *path)
8635 return mdb_env_copy2(env, path, 0);
8639 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
8641 if ((flag & CHANGEABLE) != flag)
8644 env->me_flags |= flag;
8646 env->me_flags &= ~flag;
8651 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
8656 *arg = env->me_flags;
8661 mdb_env_set_userctx(MDB_env *env, void *ctx)
8665 env->me_userctx = ctx;
8670 mdb_env_get_userctx(MDB_env *env)
8672 return env ? env->me_userctx : NULL;
8676 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
8681 env->me_assert_func = func;
8687 mdb_env_get_path(MDB_env *env, const char **arg)
8692 *arg = env->me_path;
8697 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
8706 /** Common code for #mdb_stat() and #mdb_env_stat().
8707 * @param[in] env the environment to operate in.
8708 * @param[in] db the #MDB_db record containing the stats to return.
8709 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
8710 * @return 0, this function always succeeds.
8713 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
8715 arg->ms_psize = env->me_psize;
8716 arg->ms_depth = db->md_depth;
8717 arg->ms_branch_pages = db->md_branch_pages;
8718 arg->ms_leaf_pages = db->md_leaf_pages;
8719 arg->ms_overflow_pages = db->md_overflow_pages;
8720 arg->ms_entries = db->md_entries;
8726 mdb_env_stat(MDB_env *env, MDB_stat *arg)
8730 if (env == NULL || arg == NULL)
8733 toggle = mdb_env_pick_meta(env);
8735 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
8739 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
8743 if (env == NULL || arg == NULL)
8746 toggle = mdb_env_pick_meta(env);
8747 arg->me_mapaddr = env->me_metas[toggle]->mm_address;
8748 arg->me_mapsize = env->me_mapsize;
8749 arg->me_maxreaders = env->me_maxreaders;
8751 /* me_numreaders may be zero if this process never used any readers. Use
8752 * the shared numreader count if it exists.
8754 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
8756 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
8757 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
8761 /** Set the default comparison functions for a database.
8762 * Called immediately after a database is opened to set the defaults.
8763 * The user can then override them with #mdb_set_compare() or
8764 * #mdb_set_dupsort().
8765 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
8766 * @param[in] dbi A database handle returned by #mdb_dbi_open()
8769 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
8771 uint16_t f = txn->mt_dbs[dbi].md_flags;
8773 txn->mt_dbxs[dbi].md_cmp =
8774 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
8775 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
8777 txn->mt_dbxs[dbi].md_dcmp =
8778 !(f & MDB_DUPSORT) ? 0 :
8779 ((f & MDB_INTEGERDUP)
8780 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
8781 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
8784 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
8789 int rc, dbflag, exact;
8790 unsigned int unused = 0;
8793 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
8794 mdb_default_cmp(txn, FREE_DBI);
8797 if ((flags & VALID_FLAGS) != flags)
8799 if (txn->mt_flags & MDB_TXN_ERROR)
8805 if (flags & PERSISTENT_FLAGS) {
8806 uint16_t f2 = flags & PERSISTENT_FLAGS;
8807 /* make sure flag changes get committed */
8808 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
8809 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
8810 txn->mt_flags |= MDB_TXN_DIRTY;
8813 mdb_default_cmp(txn, MAIN_DBI);
8817 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
8818 mdb_default_cmp(txn, MAIN_DBI);
8821 /* Is the DB already open? */
8823 for (i=2; i<txn->mt_numdbs; i++) {
8824 if (!txn->mt_dbxs[i].md_name.mv_size) {
8825 /* Remember this free slot */
8826 if (!unused) unused = i;
8829 if (len == txn->mt_dbxs[i].md_name.mv_size &&
8830 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
8836 /* If no free slot and max hit, fail */
8837 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
8838 return MDB_DBS_FULL;
8840 /* Cannot mix named databases with some mainDB flags */
8841 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
8842 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
8844 /* Find the DB info */
8845 dbflag = DB_NEW|DB_VALID;
8848 key.mv_data = (void *)name;
8849 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
8850 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
8851 if (rc == MDB_SUCCESS) {
8852 /* make sure this is actually a DB */
8853 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
8854 if (!(node->mn_flags & F_SUBDATA))
8855 return MDB_INCOMPATIBLE;
8856 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
8857 /* Create if requested */
8859 data.mv_size = sizeof(MDB_db);
8860 data.mv_data = &dummy;
8861 memset(&dummy, 0, sizeof(dummy));
8862 dummy.md_root = P_INVALID;
8863 dummy.md_flags = flags & PERSISTENT_FLAGS;
8864 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
8868 /* OK, got info, add to table */
8869 if (rc == MDB_SUCCESS) {
8870 unsigned int slot = unused ? unused : txn->mt_numdbs;
8871 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
8872 txn->mt_dbxs[slot].md_name.mv_size = len;
8873 txn->mt_dbxs[slot].md_rel = NULL;
8874 txn->mt_dbflags[slot] = dbflag;
8875 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
8877 mdb_default_cmp(txn, slot);
8886 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
8888 if (!arg || !TXN_DBI_EXIST(txn, dbi))
8891 if (txn->mt_flags & MDB_TXN_ERROR)
8894 if (txn->mt_dbflags[dbi] & DB_STALE) {
8897 /* Stale, must read the DB's root. cursor_init does it for us. */
8898 mdb_cursor_init(&mc, txn, dbi, &mx);
8900 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
8903 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
8906 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
8908 ptr = env->me_dbxs[dbi].md_name.mv_data;
8909 env->me_dbxs[dbi].md_name.mv_data = NULL;
8910 env->me_dbxs[dbi].md_name.mv_size = 0;
8911 env->me_dbflags[dbi] = 0;
8915 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
8917 /* We could return the flags for the FREE_DBI too but what's the point? */
8918 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8920 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
8924 /** Add all the DB's pages to the free list.
8925 * @param[in] mc Cursor on the DB to free.
8926 * @param[in] subs non-Zero to check for sub-DBs in this DB.
8927 * @return 0 on success, non-zero on failure.
8930 mdb_drop0(MDB_cursor *mc, int subs)
8934 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
8935 if (rc == MDB_SUCCESS) {
8936 MDB_txn *txn = mc->mc_txn;
8941 /* LEAF2 pages have no nodes, cannot have sub-DBs */
8942 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
8945 mdb_cursor_copy(mc, &mx);
8946 while (mc->mc_snum > 0) {
8947 MDB_page *mp = mc->mc_pg[mc->mc_top];
8948 unsigned n = NUMKEYS(mp);
8950 for (i=0; i<n; i++) {
8951 ni = NODEPTR(mp, i);
8952 if (ni->mn_flags & F_BIGDATA) {
8955 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8956 rc = mdb_page_get(txn, pg, &omp, NULL);
8959 mdb_cassert(mc, IS_OVERFLOW(omp));
8960 rc = mdb_midl_append_range(&txn->mt_free_pgs,
8964 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
8965 mdb_xcursor_init1(mc, ni);
8966 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
8972 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
8974 for (i=0; i<n; i++) {
8976 ni = NODEPTR(mp, i);
8979 mdb_midl_xappend(txn->mt_free_pgs, pg);
8984 mc->mc_ki[mc->mc_top] = i;
8985 rc = mdb_cursor_sibling(mc, 1);
8987 if (rc != MDB_NOTFOUND)
8989 /* no more siblings, go back to beginning
8990 * of previous level.
8994 for (i=1; i<mc->mc_snum; i++) {
8996 mc->mc_pg[i] = mx.mc_pg[i];
9001 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9004 txn->mt_flags |= MDB_TXN_ERROR;
9005 } else if (rc == MDB_NOTFOUND) {
9011 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9013 MDB_cursor *mc, *m2;
9016 if ((unsigned)del > 1 || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9019 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9022 rc = mdb_cursor_open(txn, dbi, &mc);
9026 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9027 /* Invalidate the dropped DB's cursors */
9028 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9029 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9033 /* Can't delete the main DB */
9034 if (del && dbi > MAIN_DBI) {
9035 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, 0);
9037 txn->mt_dbflags[dbi] = DB_STALE;
9038 mdb_dbi_close(txn->mt_env, dbi);
9040 txn->mt_flags |= MDB_TXN_ERROR;
9043 /* reset the DB record, mark it dirty */
9044 txn->mt_dbflags[dbi] |= DB_DIRTY;
9045 txn->mt_dbs[dbi].md_depth = 0;
9046 txn->mt_dbs[dbi].md_branch_pages = 0;
9047 txn->mt_dbs[dbi].md_leaf_pages = 0;
9048 txn->mt_dbs[dbi].md_overflow_pages = 0;
9049 txn->mt_dbs[dbi].md_entries = 0;
9050 txn->mt_dbs[dbi].md_root = P_INVALID;
9052 txn->mt_flags |= MDB_TXN_DIRTY;
9055 mdb_cursor_close(mc);
9059 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9061 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9064 txn->mt_dbxs[dbi].md_cmp = cmp;
9068 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9070 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9073 txn->mt_dbxs[dbi].md_dcmp = cmp;
9077 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9079 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9082 txn->mt_dbxs[dbi].md_rel = rel;
9086 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9088 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9091 txn->mt_dbxs[dbi].md_relctx = ctx;
9096 mdb_env_get_maxkeysize(MDB_env *env)
9098 return ENV_MAXKEY(env);
9102 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9104 unsigned int i, rdrs;
9107 int rc = 0, first = 1;
9111 if (!env->me_txns) {
9112 return func("(no reader locks)\n", ctx);
9114 rdrs = env->me_txns->mti_numreaders;
9115 mr = env->me_txns->mti_readers;
9116 for (i=0; i<rdrs; i++) {
9118 txnid_t txnid = mr[i].mr_txnid;
9119 sprintf(buf, txnid == (txnid_t)-1 ?
9120 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9121 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9124 rc = func(" pid thread txnid\n", ctx);
9128 rc = func(buf, ctx);
9134 rc = func("(no active readers)\n", ctx);
9139 /** Insert pid into list if not already present.
9140 * return -1 if already present.
9143 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9145 /* binary search of pid in list */
9147 unsigned cursor = 1;
9149 unsigned n = ids[0];
9152 unsigned pivot = n >> 1;
9153 cursor = base + pivot + 1;
9154 val = pid - ids[cursor];
9159 } else if ( val > 0 ) {
9164 /* found, so it's a duplicate */
9173 for (n = ids[0]; n > cursor; n--)
9180 mdb_reader_check(MDB_env *env, int *dead)
9182 unsigned int i, j, rdrs;
9184 MDB_PID_T *pids, pid;
9193 rdrs = env->me_txns->mti_numreaders;
9194 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
9198 mr = env->me_txns->mti_readers;
9199 for (i=0; i<rdrs; i++) {
9200 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
9202 if (mdb_pid_insert(pids, pid) == 0) {
9203 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9205 /* Recheck, a new process may have reused pid */
9206 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9207 for (j=i; j<rdrs; j++)
9208 if (mr[j].mr_pid == pid) {
9209 DPRINTF(("clear stale reader pid %u txn %"Z"d",
9210 (unsigned) pid, mr[j].mr_txnid));
9215 UNLOCK_MUTEX_R(env);